[antlr-interest] Rule rewrite confusion!

Kay Roepke kroepke at classdump.org
Sat Aug 11 15:04:44 PDT 2007


Hi!

On Aug 11, 2007, at 11:51 PM, xkrebstarx wrote:

> However, we cannot have a choice in a rewrite as the root node for  
> an AST.
> We can write the rewrite mid-rule, like this...
>
>     A    :    B ( X -> ^(IMAGINARY_NODE X B C)
>             | Y   -> ^(Y B C)
>             | Z   -> ^(Z B C)
>             ) C
>         ;
>
>     X    :    X
>         ;
> but we do not know what C is yet.
>
> How can this be fixed?

Rewrite rules always set the tree for the whole rule. Because of that  
you can refer to the previously built tree using $rulename.
Please note that in ANTLR parser rules must begin with a lowercase  
letter, thus your example is bound to cause confusion.

In ANTLR notation you'd do something like this:

a  :  B
       (  x   -> ^(IMAGINARY_NODE x B)
       |  Y   -> ^(Y B)
       |  Z   -> ^(Z B)
       )
       C  -> ^($a C)
    ;

x  :  X
    ;


This will built the tree you want by refering to the result of the  
rewrite rule of one of the alts.
Of course, any sort of nesting would work if you have complex  
requirements. You can also insert actions
into rewrite rules, if you have requirements that cannot (easily) be  
expressed declaratively.


HTH,
-k
-- 
Kay Röpke
http://classdump.org/






More information about the antlr-interest mailing list