2017-09-13 6 views
1

Javaメソッド名を正規表現にマッチさせようとしていますが、Rascalでそれを行う方法がわかりません。私はtestで始まる名前のメソッド(JUnit 3のテストケースなど)と一致させ、@Testというアノテーションを付けて、testの接頭辞を削除してJUnit 4テストケースに変換したいと考えています。次のエラーで正規表現へのメソッド名の一致

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