2017-09-13 53 views
1

我想將Java方法名稱與正則表達式匹配,但我不確定如何在Rascal中執行此操作。我想匹配名稱以test(例如JUnit 3測試用例)開頭的方法,並將其轉換爲JUnit 4測試用例,並使用@Test註釋和刪除前綴test。我的代碼如下所示:將聲明的方法名稱與正則表達式匹配

public tuple[int, CompilationUnit] refactorJUnitTestCaseDeclaration(CompilationUnit cu) { 
    int total = 0; 
    println(cu); 

    CompilationUnit unit = visit(cu) { 
      case(MethodDeclaration)`public void <Identifier name>() <MethodBody body>`: { 
      if(/test[A-Z]*/ := name) { 
       total += 1; 
       newName = name[4..]; 
       insert (MethodDeclaration)`@Test public void <Identifier newName>() <MethodBody body>`; 
      }; 
     } 
    }; 
    return <total, unit>; 
} 

該代碼產生以下錯誤:

Expected str, but got Identifier 

有什麼辦法來訪問name方法標識符爲字符串,所以我可以嘗試搭配呢?如果沒有,完成這個任務的最好方法是什麼?

回答

1
  • 的正則表達式模式運營商想只能匹配字符串,所以你要的name解析樹(這是類型的標識符)映射到一個字符串,像這樣:"<name>"
  • 同樣,要將新名稱字符串拼接回標識符的位置,您必須將其映射回標識符,如下所示:[Identifier] newName

最終的結果看起來是這樣的:

public tuple[int, CompilationUnit] refactorJUnitTestCaseDeclaration(CompilationUnit cu) { 
    int total = 0; 
    println(cu); 

    CompilationUnit unit = visit(cu) { 
      case(MethodDeclaration)`public void <Identifier name>() <MethodBody body>`: { 
      if(/test[A-Z]*/ := "<name>") { 
       total += 1; 
       newName = [Identifier] "<name>"[4..]; 
       insert (MethodDeclaration)`@Test public void <Identifier newName>() <MethodBody body>`; 
      }; 
     } 
    }; 
    return <total, unit>; 
} 

您也可以直接尾部匹配出與一組命名:

public tuple[int, CompilationUnit] refactorJUnitTestCaseDeclaration(CompilationUnit cu) { 
    int total = 0; 
    println(cu); 

    CompilationUnit unit = visit(cu) { 
      case(MethodDeclaration)`public void <Identifier name>() <MethodBody body>`: { 
      if(/test<rest:[A-Z]*>/ := "<name>") { 
       total += 1; 
       newName = [Identifier] rest; 
       insert (MethodDeclaration)`@Test public void <Identifier newName>() <MethodBody body>`; 
      }; 
     } 
    }; 
    return <total, unit>; 
} 
+0

它的工作太棒了!謝謝! – urielSilva