[antlr-interest] how to parse a fraction
Gavin Lambert
antlr at mirality.co.nz
Fri Sep 26 00:42:52 PDT 2008
At 18:46 26/09/2008, Sven Prevrhal wrote:
>One like 1/2 ?
>INT / INT does not work as it requires spaces
>between the numbers and the slash
If you've defined your grammar in the standard
way (and if the above is in a parser rule), it
won't actually require spaces (but it won't
object if they're there).
INT : ('0'..'9')+;
SLASH : '/';
WS : (' ' | '\t' | '\r' | '\n')+ { $channel = HIDDEN; };
fraction : INT SLASH INT;
The above should match "1/2", "1 /2", "1/ 2",
and "1 / 2" (among other combinations).
Now, if you explicitly want to *forbid*
whitespace to appear in there, you'll have to
match it entirely as a lexer rule:
fragment INT : ('0'..'9')+;
SLASH : '/';
FRACTION
: INT
( (SLASH) => SLASH INT
| { $type = INT; }
)
;
WS : (' ' | '\t' | '\r' | '\n')+ { $channel = HIDDEN; };
value : INT | FRACTION;
Of course, if you have a division operator then
all of the above is probably redundant, since the
fraction one-half is the result of treating "1/2"
as a division expression (unless you're doing
integer division, of course).
More information about the antlr-interest
mailing list