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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
No, the combined grammar
Java.g
from 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.g
to traverse it. The tree grammarJavaTreeParser.g
is not used to create an AST. This is done by the parser created fromJava.g
.That is incorrect. The tree grammar
JavaTreeParser.g
expects an AST as input that the parser generated fromJava.g
produced. 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.g
in a directory and remove the@header{...}
and@lexer:::header{...}
declarations from it;antlr-3.3.jar
into the same directory;Main.java
andTest.java
in this directory (see below).Test.java
Main.java
Now generate a lexer and parser:
Then compile all
.java
source files:And finally run the
Main
class 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:I really recommend you to use antlr4.
First, set your CLASSPATH (including antlr-4.5.3-complete.jar) and JAVA_HOME.
Second, generate a lexer and parser from the grammar Java.g4:
Third, compile all Java*.java genereated:
Finally, run TestRig:
You will see AST visually as follows: