[antlr-interest] predicate and ambiguity

Kay Roepke kroepke at classdump.org
Sun Jul 8 08:40:41 PDT 2007


On Jul 8, 2007, at 5:15 PM, Lloyd Dupont wrote:

> Thinking more about it I have been able to refactor succesffully  
> the rule above in the following (working grammar):
> =============
> unary : (PLUS|MINUS)? cast ;
>
> cast : ((LPAREN identifier RPAREN) cast) => (LPAREN identifier  
> RPAREN) cast
>  | primary
>  ;
> =============
> (BTW, ANTLR Works is really helpful and really cool! I feel like  
> it's much easer to overcome grammar problem with it!!!)

ain't it ;)

> Anyway, I still wonder how to a predicate as above, that is I look  
> for a structure A B C where B verify some property to read the  
> stuff as A B C.

You'll need to have a semantic predicate and some external (=  
provided by you) method of determining whether 'identifier' is  
actually a type name.
identifier in your case is a parser rule, making it a bit hard for me  
to give you an example (what does identifier look like?).
Anyway if identifier was a token named ID you could do:

=============
unary : (PLUS|MINUS)? cast ;

cast : {isType(input.LT(2))}? (LPAREN ID RPAREN) cast
  | primary
  ;
=============

or whatever the syntax for C# is...

Basically what this does is to call your own method/function isType()  
with the symbol that appears two tokens in the future (lookahead is 2).
isType() would return true if it is a type, thus the predicate would  
be true and ANTLR would choose the case alternative. If it isn't a  
type, then that alternative would be shut off and ANTLR would try to  
match primary.
Very powerful :)

Having the parser rule identifier makes it impossible for me to tell  
you what the lookahead depth would need to be, since I don't know  
what identifier tries to match (token-wise).

HTH,
-k

-- 
Kay Röpke
http://classdump.org/






More information about the antlr-interest mailing list