I basically follow the step of the answer in the url: ANTLR 4 - Tree pattern matching . However, I get the error:
Error:(29, 5) java: cannot find symbol symbol: class JavaLexer location: class Main.
My code is exactly same. It seems like Java does not know that JavaLexer is. Can anyone help me?
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.pattern.ParseTreeMatch;
import org.antlr.v4.runtime.tree.pattern.ParseTreePattern;
import java.util.List;
public class Main {
public static void main(String[] args) {
String source = "package sampleCodes;\n" +
"\n" +
"public class fruits {\n" +
"\n" +
" static { int q = 42; }\n" +
"\n" +
" public static void main(String[] args){\n" +
" int a = 10;\n" +
" System.out.println(a);\n" +
" }\n" +
"}\n";
JavaLexer lexer = new JavaLexer(CharStreams.fromString(source));
JavaParser parser = new JavaParser(new CommonTokenStream(lexer));
ParseTree tree = parser.compilationUnit();
ParseTreePattern p = parser.compileParseTreePattern("<IDENTIFIER> = <expression>", JavaParser.RULE_variableDeclarator);
List<ParseTreeMatch> matches = p.findAll(tree, "//variableDeclarator");
for (ParseTreeMatch match : matches) {
System.out.println("\nMATCH:");
System.out.printf(" - IDENTIFIER: %s\n", match.get("IDENTIFIER").getText());
System.out.printf(" - expression: %s\n", match.get("expression").getText());
}
}
}
You have to generate the lexer and parser classes first. Do the following:
Main.java
file) open a terminal, navigate to the folder you've downloaded the files and generate the lexer and parser classes from the Java grammar:
java -jar antlr-4.8-complete.jar *.g4
compile all .java
source files:
javac -cp antlr-4.8-complete.jar *.java
run the Main
class:
# For Mac & *nix java -cp antlr-4.8-complete.jar:. Main # or on Windows java -cp antlr-4.8-complete.jar;. Main
The following will be printed on your console:
MATCH:
- IDENTIFIER: q
- expression: 42
MATCH:
- IDENTIFIER: a
- expression: 10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.