[antlr-interest] Return values from listener methods (was "Appropriate use of honey badger listeners")

Terence Parr parrt at cs.usfca.edu
Thu Jan 12 15:12:44 PST 2012


On Jan 12, 2012, at 1:59 PM, Sam Harwell wrote:

> I've used listeners for several tasks in ANTLRWorks 2 and haven't
> encountered any problems in returning values which I wasn't able to work
> around in a clean manner.
> 
> For the case of expressions like your example below, once you realize that
> exitRule behaves as an RPN calculator you just use a simple stack to track
> computed results. For other tasks I've used stacks, flags, counters, or
> whatever else was relevant to the specific task.
> 
> For a simple calculator, you might have this:
> 
> public void exitRule(multContext context) {
>    double right = stack.pop();
>    double left = stack.pop();
>    stack.push(left * right);
> }
> 
> If you don't mind reversing the operand order of a commutative operator, you
> could also write:
> 
> public void exitRule(multContext context) {
>    stack.push(stack.pop() * stack.pop());
> }

This seems like a good solution for expressions. I wonder if we can come up with a solution that users don't have to manage…

Ter


More information about the antlr-interest mailing list