-
Notifications
You must be signed in to change notification settings - Fork 0
/
comtest.java
44 lines (36 loc) · 1.42 KB
/
comtest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.gui.TreeViewer;
public class comtest {
public static void main( String[] args) throws Exception
{
ANTLRInputStream input = new ANTLRInputStream( System.in);
CLexer lexer = new CLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CParser parser = new CParser(tokens);
ParseTree tree = parser.compilationUnit(); // begin parsing at rule compilationUnit
// ParseTree tree=parser.blockItemList(); //ÁÙʱʹÓõÄ
// System.out.println(tree.toStringTree(parser)); // print LISP-style tree
TreeViewer viewr = new TreeViewer(Arrays.asList(parser.getRuleNames()),tree);
showtree(viewr);
ParseTreeWalker walker = new ParseTreeWalker();
//step2:´´½¨ParseTreeListenerºÍParseTree
walker.walk(new realListener(), tree);
}
private static void showtree(TreeViewer treev) {
// show AST in GUI
JFrame frame = new JFrame("Antlr AST");
JPanel panel = new JPanel();
treev.setScale(0.8);//scale a little
panel.add(treev);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}