Satnam Sandhu
Satnam Sandhu

Reputation: 680

JAVA Tree parser for ANTLR

I want to make a JAVA AST parser and i came across this extremely useful answer.

So as per the instructions i created all the files and there were no errors generating the lexer and parser using the Java.g file but when compiling *.java file i get an error in Main.java

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;

public class Main {
    public static void main(String[] args) throws Exception {
        JavaLexer lexer = new JavaLexer(new ANTLRFileStream("Test.java"));
        JavaParser parser = new JavaParser(new CommonTokenStream(lexer));
        CommonTree tree = (CommonTree)parser.javaSource().getTree();
        DOTTreeGenerator gen = new DOTTreeGenerator();
        StringTemplate st = gen.toDOT(tree);
        System.out.println(st);
    }
}

for compilation:

javac -cp antlr-3.4-complete.jar *.java

and the error is:

Main.java:9: error: cannot find symbol
        CommonTree tree = (CommonTree)parser.javaSource().getTree();
                                            ^
  symbol:   method javaSource()
  location: variable parser of type JavaParser
1 error

I am a beginner and i am really unable to find the problem. Thanks in advance.

Upvotes: 3

Views: 871

Answers (1)

Jiri Tousek
Jiri Tousek

Reputation: 12450

CommonTree tree = (CommonTree)parser.javaSource().getTree();

This assumes that the start point for the Java grammar you are using is the javaSource rule.

Check your grammar to see whether that is indeed the case. If not, identify the correct starting rule and use that. The methods of the parser are named the same as the rules in the grammar.

Upvotes: 1

Related Questions