[antlr-interest] rewrite rule for optional root insertion?

Krešimir Tonković kresimir.tonkovic at multimodus.hr
Fri Apr 6 07:35:29 PDT 2012


On Fri, Apr 6, 2012 at 12:25 AM, John B. Brodie <jbb at acm.org> wrote:

> 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
>

Thanks, that did the trick.

Is this covered in the ANTLR reference guide book?
-- 
Krešimir Tonković
Multimodus d.o.o.


More information about the antlr-interest mailing list