简体   繁体   English

为什么不显示分析树?

[英]Why is parse tree not being displayed?

I have an ANTLR grammar and trying to make a parse tree to display using jFrame in Java. 我有一个ANTLR语法,并尝试制作一个解析树以在Java中使用jFrame进行显示。 However, the parse tree is not being displayed as it can be seen below. 但是,解析树未显示,如下所示。

解析树无法正确显示

I do notice that if I remove the call to the visitor line Object answer = new ExpAnalyserBaseVisitor<>().visit(parser.exp()); 我确实注意到,如果我删除了对访客行Object answer = new ExpAnalyserBaseVisitor<>().visit(parser.exp());的调用,则Object answer = new ExpAnalyserBaseVisitor<>().visit(parser.exp()); then the parse tree is displayed correctly. 则分析树将正确显示。 I am not sure why that is a problem and how to fix it. 我不知道为什么这是一个问题以及如何解决。

解析树正确显示

Here is my code for displaying it: 这是我显示它的代码:

CharStream charStream = CharStreams.fromString(exp);

ExpAnalyserLexer lexer = new ExpAnalyserLexer(charStream);
lexer.removeErrorListeners();

CommonTokenStream tokens = new CommonTokenStream(lexer);

ExpAnalyserParser parser = new ExpAnalyserParser(tokens);
parser.removeErrorListeners();

try {
    Object answer = new ExpAnalyserBaseVisitor<>().visit(parser.exp());
    System.out.println("Postfix Expression: " + answer);
}
catch (EmptyStackException e){
    System.out.println("Invalid expression!");
    return;
}

ParseTree tree = parser.exp();
JFrame frame = new JFrame("Parse Tree");
JPanel panel = new JPanel();
TreeViewer treeViewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree);
treeViewer.setScale(1.5);
panel.add(treeViewer);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);

Is there a better way to display the parse tree? 有没有更好的方法来显示分析树? Also can I remove the rule names to display in the parse tree also? 还可以删除规则名称以显示在分析树中吗?

You are calling parser.exp() 2 times without rewinding your input stream. 您正在调用parser.exp() 2次,而不parser.exp()您的输入流。 The first call consumes all tokens and the second call doesn't find any input, so it cannot parse anything. 第一个调用消耗了所有令牌,第二个调用没有找到任何输入,因此无法解析任何内容。 You should at least call tokens.reset() before the second call to parse.expr() . 在第二次调用tokens.reset()之前,至少应调用parse.expr() Maybe you also have to reset your char stream and the lexer. 也许您还必须重置字符流和词法分析器。 Play with them. 和他们一起玩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM