如果你有这样的代码,如控制台还是摇摆,你如何显示AST GUI? 我的ANTLR是第3版。
CharStream stream = new ANTLRStringStream("program XLSample1 =\n" +
"constant one : Integer := 1;\n" +
"constant two : Integer := 2;\n" +
"var a, b,c : Integer := 42;\n" +
"begin\n" +
" x:= (12 + 6) - (7 * 41) - x mod y;\n" +
" y := 21;\n" +
"\n" +
"if x < 10 then\n" +
" y :=2;\n" +
" elseif x < 20 then\n" +
" y := 20;\n" +
" else\n" +
" y := 30;\n" +
"end if; \n" +
"end XLSample1.");
SampleLexer lexer = new SampleLexer(stream);
TokenStream tokenStream = new CommonTokenStream(lexer);
SampleParser parser = new SampleParser(tokenStream);
parser.program();
System.out.println("OK");
}
答案 0 :(得分:11)
我喜欢ANLTR,所以我试着回答它。
使用Antlr V4(对于V3尝试查找类似的API),要显示gui AST,可以使用org.antlr.v4.runtime.tree.gui.TreeViewer。
你可以从ANTLR's site获得Hello演示,一旦你得到它,运行这个简单的演示:
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 viewr = new TreeViewer(Arrays.asList(
parser.getRuleNames()),tree);
viewr.setScale(1.5);//scale a little
panel.add(viewr);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
}
}
然后你将在控制台中获得AST打印并在JFrame中显示。 更多细节,请参考ANLTR API。
确保您的语法正常,然后您可以修改此演示以满足您的需求。
ANTLR 4的更新:TreeViewer
已从ANTLR 4 Tool移至org.antlr.v4.gui.TreeViewer
个包裹。
答案 1 :(得分:1)
在ANTLR 4中使用import org.antlr.v4.runtime.tree.gui.TreeViewer ...其作品:)
答案 2 :(得分:0)
经过几次尝试自定义wangdq代码的尝试,我发现可以调用TreeViewer类的open方法来获得令人愉悦的效果(因为它已经完成了:))解析树检查器。
应用于wangdq示例:
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 viewr = new TreeViewer(Arrays.asList(
parser.getRuleNames()),tree);
viewr.open();
}
}