ANTLR V4, javalexer, and javaparser return null as a parse tree

I am using ANTLR V4 to extract the parse tree of Java programs for other purposes Let me start with this sample: ANTLR V4 visitor sample

I have tested the steps on a given link to see if it works and everything is OK:

java Run
a = 1+2
b = a^2
c = a+b*(a-1)
a+b+c
^Z
Result: 33.0

Then I wrote my own parsing Java program, as shown in the following structure:

|_Java.g4                                                               
|_Java.tokens                                                           
|_JavaBaseVisitor.java                                                  
|_JavaLexer.java                                                        
|_JavaLexer.tokens                                                      
|_JavaParser.java                                                       
|_JavaTreeExtractorVisitor.java                                         
|_JavaVisitor.java           
|_Run.java

Run. Java is as follows:

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);
    }
}

But in the statement parsetree tree = parser getContext(); The tree object becomes null Because I am a novice of ANTLR, what suggestions do you have for me to check or any solution?

(please let me know if you need more information)

TG.

Solution

Assuming you are using the syntax here, you need to parse the starting point of the java file

ParseTree tree = parser.compilationUnit();

(for anyone who doesn't use this syntax, you need anything you name the top-level parser rule.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>