我正在使用antlr v4来提取
java程序的解析树以用于其他目的.我从这个样本开始:
ANTLR v4 visitor sample
我已经测试了给定链接上的步骤,以检查它是否有效以及一切正常:
java Run a = 1+2 b = a^2 c = a+b*(a-1) a+b+c ^Z Result: 33.0
然后我编写了自己的解析java程序如下面的结构:
|_Java.g4 |_Java.tokens |_JavaBaseVisitor.java |_JavaLexer.java |_JavaLexer.tokens |_JavaParser.java |_JavaTreeExtractorVisitor.java |_JavaVisitor.java |_Run.java
Run.java如下:
import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; public class Run { public static void main(String[] args) throws Exception { CharStream input = CharStreams.fromFileName("F:\\Projects\\Java\\Netbeans\\ASTProj\\JavaTreeExtractor\\prog.java"); JavaLexer lexer = new JavaLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); JavaParser parser = new JavaParser(tokens); ParseTree tree = parser.getContext(); JavaTreeExtractorVisitor calcVisitor = new JavaTreeExtractorVisitor(); String result = calcVisitor.visit(tree); System.out.println("Result: " + result); } }
但是在语句ParseTree tree = parser.getContext();树对象变为null.
因为我是antlr的新手,有什么建议让我检查或任何解决方案?
(如果需要更多信息,请通知我).
TG.