简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM