[antlr-interest] Re: Antlr grammar to parse Java classfile?
mzukowski at bco.com
mzukowski at bco.com
Fri Dec 7 07:05:14 PST 2001
> Actually, I would argue that semantic predicates are the way
> to go; as
> Monty pointed out
>
> ( { n > 0 }? foo { n--; } )*
>
> will parse at most n iterations and you can add a sem pred as a
> termination check, as Ter suggested. Recursive definitions also work:
>
> loop
> { int n = N; }
> :
> { n > 0 }? foo { n--; } loop
> | { n == 0}?
> ;
>
> will parse exactly n copies of foo or throw an exception.
>
> Unfortunately, syntactic predicates don't behave the same in loops as
> they do in recursive definitions--the recursive solution works as
> ANTLR is currently implemented.
It doesn't work quite as you have it above. The action n-- is ignored when
guessing. But you are right that recursive definitions will do the trick:
loop[int N]
{ int n = N; }
:
{ n > 0 }? foo loop[n-1]
| { n == 0}?
;
generates:
if (((LA(1)==LITERAL_hey))&&( n > 0 )) {
foo();
loop(n-1);
}
else if (((LA(1)==EOF||LA(1)==LITERAL_hey))&&( n == 0)) {
}
else {
throw new NoViableAltException(LT(1), getFilename());
}
With a (valid) warning that is generated because of the possibility of
matching nothing in the loop rule.
Monty
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list