Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR v4, JavaLexer and JavaParser returning null as parse tree

I am using antlr v4 for extracting parse tree of java programs for other purposes. I have started from this sample: ANTLR v4 visitor sample

And I have tested the steps on given link to check if it works and everything gone right:

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

And then I wrote my own to parse java programs as Structure below:

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

And the Run.java is as below:

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 at the statement ParseTree tree = parser.getContext(); the tree object gets null. As I am new to antlr, any suggestions for me to check or any solution?

(If more info is required, just notify me).

TG.

like image 848
ConductedClever Avatar asked Aug 11 '17 12:08

ConductedClever


2 Answers

Assuming you're using the grammar here, you want the starting point for parsing a Java file to be

ParseTree tree = parser.compilationUnit();

(For anyone not using that grammar, you want whatever you named your top-level parser rule.)

like image 169
Bill the Lizard Avatar answered Nov 17 '22 11:11

Bill the Lizard


Shouldn't you be doing:

    ParseTree tree = parser.input();

as in the calculator example?

like image 27
Maurice Perry Avatar answered Nov 17 '22 10:11

Maurice Perry