[antlr-interest] to recognise interger and real in one rule

John B. Brodie jbb at acm.org
Fri Jun 2 14:36:31 PDT 2006


>In lexer grammar, I try to recognise interger and real in one rule, 
>
>BasicValue: ( Sign)? (Digit)+ {$setType(IntDenot);} ( '.' (Digit)+ (Exponent)?
>{$setType(RealDenot);})? ;
>
>protected Exponent : 'E' (Sign)? (Digit)+ ;
>
>
>In parser grammar, put
>
>basicValue :BaiscValue EOF;
>
>when parsing  "78.9", produces error message: 
>
>line 1:2: expecting "BaiscValue", found '78.9'.
>
>Further more I wish, with action {$setType(IntDenot);} and {$setType(RealDenot);} in lexical
>grammar, the token type BasicValue is redundant. 

Using the $setType(...) action changes the kind of token returned by the
lexer.  Thus your parser rule should be:

basicValue : ( IntDenot | RealDenot ) EOF ;


And yes, the token BasicValue is redundant (unless you have other lexing
rules that match that token type).

You could simply have this lexer rule:

IntDenot : ( Sign )? ( Digit )+
      ( '.' ( Digit )+ ( Exponent )? { $setType(RealDenot); } )?
    ;

Thus numbers are assumed to be integers unless a fractional part is present,
no need for BasicValue.

Hope this helps...
   -jbb


More information about the antlr-interest mailing list