[antlr-interest] How to use greedy in antlr3
Kay Roepke
kroepke at classdump.org
Tue Nov 28 07:41:05 PST 2006
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/
More information about the antlr-interest
mailing list