[antlr-interest] zero-or-more or one-or-more in tree grammars

Jim Idle jimi at temporal-wave.com
Thu May 28 09:45:54 PDT 2009


Mike J. Bell wrote:
> I'm having trouble finding examples to show how to handle accumulation 
> of rule components in a tree parser.
>
> For instance, given a grammar snippet:
>
> big_definition: ^(DEFINITION_TOKEN str=collection) { 
> System.out.println("definition " + $str.value); };
>
> collection returns [String value]:
>     t=thing* { /* insert magic to accumulate all the t's into $value */ };
>
> thing: ...
I think that perhaps people just assume that this is obvious, but it 
seems to get a lot of people so perhaps you can add this to the Wiki? ;-) :

collection returns [String value]
:
    ( t=thing
        {  $value += $t.text; }
    )*
;

Note that because of the *, you may return a null string, so perhaps you 
need an @init block to set it to "" or something?

However, if your collection is empty, then you will get a single node, 
not a tree, so you should probably have:

big_definition
: ^(DEFINITION_TOKEN

            str=collection) { System.out.println("definition " + 
$str.value); };

| DEFINITION_TOKEN { Sout("empty collection"); }
;


collection returns [String value]
:
    ( t=thing
        {  $value += $t.text; }
    )+
;

Jim




More information about the antlr-interest mailing list