[ACCEPTED]-How to Display ANTLR Tree GUI-antlr
Using ANTLR V4 (for V3 try to find out the 9 similar API),to show a gui AST, you can 8 use org.antlr.v4.runtime.tree.gui.TreeViewer
.
You can get the Hello demo from ANTLR's site. Once 7 you got it, run this simple demo:
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.gui.TreeViewer;
/**
* A simple demo to show AST GUI with ANTLR
* @see http://www.antlr.org/api/Java/org/antlr/v4/runtime/tree/gui/TreeViewer.html
*
* @author wangdq
* 2014-5-24
*
*/
public class HelloTestDrive {
public static void main(String[] args) {
//prepare token stream
CharStream stream = new ANTLRInputStream("hello antlr");
HelloLexer lexer = new HelloLexer(stream);
TokenStream tokenStream = new CommonTokenStream(lexer);
HelloParser parser = new HelloParser(tokenStream);
ParseTree tree = parser.r();
//show AST in console
System.out.println(tree.toStringTree(parser));
//show AST in GUI
JFrame frame = new JFrame("Antlr AST");
JPanel panel = new JPanel();
TreeViewer viewer = new TreeViewer(Arrays.asList(
parser.getRuleNames()),tree);
viewer.setScale(1.5); // Scale a little
panel.add(viewer);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Then you 6 will get the AST print in the console and 5 show in JFrame
.
more details, please refer ANTLR API.
Make 4 sure your grammar work fine, then you can 3 modify this demo to meet your requirement.
Update for ANTLR 4: TreeViewer
has 2 moved to org.antlr.v4.gui.TreeViewer
package from ANTLR 4 Tool.
When using maven
, TreeViewer
requires 1 the following dependency:
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId>
<version>4.7.2</version>
</dependency>
After a few attempts trying to customize 5 wangdq code, I figured out that it's possible 4 to call the open method of TreeViewer class 3 to get a delightful (because it's already 2 done :)) Parse Tree Inspector.
Applied to 1 wangdq example:
public class HelloTestDrive {
public static void main(String[] args) {
//prepare token stream
CharStream stream = new ANTLRInputStream("hello antlr");
HelloLexer lexer = new HelloLexer(stream);
TokenStream tokenStream = new CommonTokenStream(lexer);
HelloParser parser = new HelloParser(tokenStream);
ParseTree tree = parser.r();
//show AST in console
System.out.println(tree.toStringTree(parser));
//show AST in GUI
TreeViewer viewr = new TreeViewer(Arrays.asList(
parser.getRuleNames()),tree);
viewr.open();
}
}
use import org.antlr.v4.runtime.tree.gui.TreeViewer 1 in ANTLR 4...its works :)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.