[antlr-interest] How to fix the ambiguous grammar

Jie Li jay23jack at gmail.com
Tue Jun 5 16:33:07 PDT 2012


Thanks a lot! Somehow it works though it didn't.

Jie

On Tue, Jun 5, 2012 at 3:37 PM, Terence Parr <parrt at cs.usfca.edu> wrote:

> a : A B | A ;
>
> On Jun 5, 2012, at 9:26 AM, Jie Li wrote:
>
> I'm afraid I need 'a' to match both "A" and "A B", so I tried
>
> a:  A
>    | A {input.LT(1).getText().equals("B")}? B;
>
> which works though it doesn't look nice. Do you have any better idea?
>
> Jie
>
> On Tue, Jun 5, 2012 at 9:10 AM, Terence Parr <parrt at cs.usfca.edu> wrote:
>
>> Easiest thing to do is simply reorder those alternatives if you want 'a'
>>  to match A B not A.
>> T
>> On Jun 4, 2012, at 10:18 PM, Jie Li wrote:
>>
>> > Thanks Ter. Do you mean I should turn the backbracking off? If I can't,
>> do
>> > you have any suggestion?
>> >
>> > Jie
>> >
>> > On Mon, Jun 4, 2012 at 9:57 PM, Terence Parr <parrt at cs.usfca.edu>
>> wrote:
>> >
>> >> It sounds like you have backtracking turned on and that whichever rule
>> >> calls 'a' has B following the reference to 'a'. When it can't figure
>> out
>> >> what to do with an ambiguity it picks the 1st match.
>> >> Ter
>> >> On Jun 4, 2012, at 9:49 PM, Jie Li wrote:
>> >>
>> >>> Hi all,
>> >>>
>> >>> I'm new to antlr and struggling to fix the grammar like below:
>> >>>
>> >>> a:   A
>> >>>   | A B ;
>> >>>
>> >>> But this grammar doesn't support "A B" as it complains it expects the
>> end
>> >>> character after "A". If I switch the order of this grammar, e.g. "A B"
>> >>> comes before "A", then it doesn't support "A" as it complains it
>> expects
>> >>> "B" after "A".
>> >>>
>> >>> Then I tried:
>> >>>
>> >>> a:  A
>> >>>  | A {input.LT(1).getText().equals("B")}? B;
>> >>>
>> >>> It does work for both rules now. But I wonder if there is some more
>> >> elegant
>> >>> way?
>> >>>
>> >>> Thanks,
>> >>> Jie Li
>> >>>
>> >>> 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