I’ve found a sample template in the ANTLR website, its the Javatreeparser.g, which the site says could produce the AST that I need, but since I’m new to ANTLR, how do I make it show? What I’ve done so far is placing the grammar file together with my existing java grammar. But I have no idea on how to use and output the AST that I need from the file. How do I do it?
I’ve found a sample template in the ANTLR website, its the Javatreeparser.g, which the
Share
No, the combined grammar
Java.gfrom the ANTLR wiki produces a lexer and parser for Java source files. The parser then constructs an AST of this source and this AST can then be used byJavaTreeParser.gto traverse it. The tree grammarJavaTreeParser.gis not used to create an AST. This is done by the parser created fromJava.g.That is incorrect. The tree grammar
JavaTreeParser.gexpects an AST as input that the parser generated fromJava.gproduced. You can’t just plug in another parser (or other tree grammar, for that matter).See this previous Q&A: Visualizing an AST created with ANTLR (in a .Net environment)
EDIT
I didn’t want to post this immediately, because I wanted you to give it a try yourself first (yes, I’m mean!) 😉
Here’s a quick demo:
Java.gin a directory and remove the@header{...}and@lexer:::header{...}declarations from it;antlr-3.3.jarinto the same directory;Main.javaandTest.javain this directory (see below).Test.java
Main.java
Now generate a lexer and parser:
Then compile all
.javasource files:And finally run the
Mainclass and pipe the output to a file calledast.dot.(on Windows, do:
java -cp .;antlr-3.3.jar Main > ast.dot)If you now open the file
ast.dot, you see a DOT representation of the AST produced by the parser. You can visualize this AST by copy-pasting the DOT-source in here: http://graphviz-dev.appspot.com resulting in the following image: