ANTLR v4, JavaLexer and JavaParser returning null as parse tree
Asked Answered
C

2

8

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.

Cousins answered 11/8, 2017 at 12:17 Comment(0)
T
3

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.)

Tilth answered 11/8, 2017 at 13:6 Comment(0)
A
1

Shouldn't you be doing:

    ParseTree tree = parser.input();

as in the calculator example?

Andersen answered 11/8, 2017 at 12:54 Comment(3)
ParseTree tree = parser.compilationUnit(); would be the starting point for parsing a Java file. (Assuming the Java grammar here)Tilth
@BilltheLizard thanks.make that an answer, so i can +1 itAndersen
@BilltheLizard that's right. Please post this as an answer. Thanks.Cousins

© 2022 - 2024 — McMap. All rights reserved.