Reputation: 429
i have a Antlr generated Listener, and i call my tree walker to go through the tree from a parse function in another class. Looks like this:
public double calculate(){
ANTLRInputStream input = new ANTLRInputStream("5+2");
Lexer lexer = new Lexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
Parser parser = new Parser(tokens);
ParseTree tree = parser.calculate();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(new Listener(), tree);
return 0;
}
So the listener works perfect with the enter() and quit() Functions and prints the correct value in the end:
public void exitParser(ParserContext ctx) {
result = stack.peek();
System.out.println(result);
}
But i wanna receive the final value in my calculate() function to return it there. Since exitParser(...) is void i dont know how to deal with it.
With the visitor i was able to do it like that:
public double calculate(){
// ...
String value = new WRBVisitor().visit(tree);
return Double.parseDouble(value);
}
Hope someone understands my problem and knows a solution for it.
Best regards
Upvotes: 4
Views: 2062
Reputation: 170158
As mentioned in the comments: a visitor might be a better option in your case. A visitor's methods will always return a value, which is what you seem to be after. That could be a Double
if your expressions always evaluate to a numeric value, or some sort of home-grown Value
that could represent a Double
, Boolean
, etc.
Have a look at my demo expression evaluator (using a visitor) on GitHub: https://github.com/bkiers/Mu
Upvotes: 1