简体   繁体   中英

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. 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()); 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. 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() . Maybe you also have to reset your char stream and the lexer. Play with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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