[antlr-interest] How to use greedy in antlr3
Pantzagias, Martina
Martina.Pantzagias at Elektrobit.com
Wed Nov 29 01:18:16 PST 2006
Hay Kay, :-)
Thanks a lot for your help. Now I´ve taken your option with the syntactic predicate and it works fine.
Best wishes,
Martina
-----Original Message-----
From: Kay Roepke [mailto:kroepke at classdump.org]
Sent: Tuesday, November 28, 2006 4:41 PM
To: Pantzagias, Martina
Cc: antlr-interest at antlr.org
Subject: Re: [antlr-interest] How to use greedy in antlr3
Hi Martina!
On 28. Nov 2006, at 16:00 , Pantzagias, Martina wrote:
> This works fine, but if I add the second alternative an warning occurs
> (--> multiple alternatives):
>
> Tag
> : '{' (options{greedy=false;}: .)* '}'
> | '{!{' (options{greedy=false;}: .)* '}!}'
>
>
> How can I solve this problem?
There are two ways:
One with a warning, but correct behavior, the other without a warning but a (slight) performance hit.
The important thing to note with ANTLR is that it will always do the matching in the order of the alts in a rule.
In your rule ANTLR tells you that it disabled alt2 for input like '{', because the first alt already matches.
Simply reversing the alts will match correctly.
The second option you can take is to use a syntactic predicate to disambiguate (and to shut up the warning).
The grammar below will make it clear (hopefully :)...
grammar Greedy;
tags: TAG+;
/* This rule doesn't warn */
/*
TAG : ('{!{') => '{!{' (options{greedy=false;}: .)*
{ System.err.println("alt1"); }'}!}'
| '{' (options{greedy=false;}: .)*{ System.err.println("alt2"); } '}'
;
*/
/* This warns, but will match correctly */
TAG : '{!{' (options{greedy=false;}: .)* { System.err.println("{!
{"); } '}!}'
| '{' (options{greedy=false;}: .)* { System.err.println("plain
{"); }'}'
;
WS : (' ' | '\t' | '\n' | '\r') { skip(); }
;
In AW, you need to use the debugger and watch the "Output" to see the System.err... calls.
HTH,
-k
--
Kay Röpke
http://classdump.org/
----------------------------------------------------------------
Please note: This e-mail may contain confidential information
intended solely for the addressee. If you have received this
e-mail in error, please do not disclose it to anyone, notify
the sender promptly, and delete the message from your system.
Thank you.
More information about the antlr-interest
mailing list