I am trying to understand parse tree matching in ANTLR 4, so for that I have the following java code:
package sampleCodes;
public class fruits {
public static void main(String[] args){
int a = 10;
System.out.println(a);
}
}
I am using ANTLR 4 to create a parse tree of this code. Now, I want to use tree pattern matching function to find "int a = 10;". There is a doc on GitHub: https://github.com/antlr/antlr4/blob/master/doc/tree-matching.md which explains this(something like this) by an example:
ParseTree t = ...; // assume t is a statement
ParseTreePattern p = parser.compileParseTreePattern("<ID> = <expr>;", MyParser.RULE_statement);
ParseTreeMatch m = p.match(t);
if ( m.succeeded() ) {...}
From reading through this doc and few other resources, what I understood was that in:
ParseTreePattern p = parser.compileParseTreePattern("<ID> = <expr>;", MyParser.RULE_statement);
The rule to be passed as second argument must be able to correctly parse the pattern provided as first argument. Now the grammar I am using is of java given here: https://github.com/antlr/grammars-v4/tree/master/java
JavaLexer.g4, JavaParser.g4
I cannot get much info on how to structure your pattern string and its corresponding rule from the above GitHub doc. So I have tried few combinations to get the match, but none of them seems to work.For example:
ParseTreePattern p = parser.compileParseTreePattern("<variableDeclaratorId> = <variableInitializer>", parser.RULE_variableDeclarator);
ParseTreeMatch m = p.match(tree);
System.out.println(m);
This gives:
Match failed; found 0 labels
I know i am certainly doing something wrong in my string pattern. Can anyone please help me with explaining this pattern matching function, and tell what should be the correct arguments to be used in this case. Also, it will will be really helpful to provide links to some useful resources where I can learn more about this and work on complex patterns.(I could not find it in ANTLR4 reference)
ParseTreePattern p = parser.compileParseTreePattern("IDENTIFIER = 10", parser.RULE_variableDeclarator);does not work either. - RajatDevSharma