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

Oliver Zeigermann oliver.zeigermann at gmail.com
Sat Jan 14 04:39:30 PST 2012


Obviously, we have different ideas how to use the parse tree. If I did
something like a static type computation this clearly would be beyond
the scope of a parse tree for me.  For a project like this I would use
a heterogeneous AST and a custom visitor that could easily contain
this type of information.

But this is a matter of definition I guess. If I wanted to do this
kind of thing, I agree, there should be a way of extending the
context. AFAIK right now the only way to define a context is via the
grammar. Could it be possible to extend theses contexts manually (by
subclassing) and tell ANTLR to create a custom context instead of the
generated ones? I lost track of the ongoing discussion a little bit,
so if this has been proposed already, please be lenient toward me :)

- Oliver

2012/1/13 Terence Parr <parrt at cs.usfca.edu>:
> 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
>
>
> 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