[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:14:28 PST 2012


Ah. I knew something was missing. Sometimes you really do need to annotate the tree. During static type computation, you not only need to compute the type of an expression, you want to annotate tree with it to save the answer. We need some way to associate a value to a node. As we do passes over the parse tree, we want to annotate it with information.

Ter
On Jan 12, 2012, at 3:12 PM, Terence Parr wrote:

> 
> 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
> 
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address



More information about the antlr-interest mailing list