[antlr-interest] rewrite rule for optional root insertion?
John B. Brodie
jbb at acm.org
Thu Apr 5 15:25:08 PDT 2012
Greetings!
On 04/05/2012 08:59 AM, Krešimir Tonković wrote:
> Hi!
>
> I have many rules like this in my grammar:
>
> plus_minus_exp :
> mult_div_exp ('+'^ | '-'^ mult_div_exp)?
> ;
>
> which produces desired trees:
> 1+2 -> ^(+ 1 2)
> 1+2*3 ->^(+ 1 ^(* 2 3))
> 2*3 -> ^(* 2 3)
> for correct operator precedence and no superfluous nodes.
>
> However, I have some cases where tree operators are not enough. I need more
> control that rewrite rules provide. I have tried with syntactic predicates,
> but I find they hurt the performance of my parser and I would like to avoid
> that.
>
> How would I rewrite above rule with rewrite rules and no syntactic
> predicates?
>
> Regards,
Off the top of my head. Untested. Your Mileage May Vary.
pme :
( mde -> mde ) // init pme's tree result
( ( (o='+' | o='-') mde ) -> ^($o pme mde) )? // reset the result
using prior
;
sorry for the abbreviations.
note that the "o=" stuff only works because both alternative assignments
are tokens.
this is the general idea, hope it gets you going...
-jbb
More information about the antlr-interest
mailing list