[antlr-interest] Beginner question: rule preference?

Mark Volkmann r.mark.volkmann at gmail.com
Sat Feb 9 14:41:24 PST 2008


On Feb 9, 2008 3:49 PM, Micke Hovmöller <micke.hovmoller at gmail.com> wrote:
> I'm trying to parse this small text:
> -----
> ** Dealing down cards **
> Dealt to Player [ Td , 3c ]
> -----
>
> With this grammar in ANTLRWorks 1.1.7
>
> -----
> grammar Mini;
>
> dealingdown
>         :       '** Dealing down cards **' NEWLINE 'Dealt to ' ID ' [ ' card ','
> card ']' NEWLINE;
>
> card    :       RANK SUIT;
>
> RANK    :       ('2'..'9'|'T'|'J'|'Q'|'K'|'A') ;
>
> SUIT    :       ('d'|'c'|'h'|'s');
>
> ID  :   ('a'..'z'|'A'..'Z'|'_'|'0'..'9')+ ;
>
> NEWLINE:'\r'? '\n' ;
> -----
>
> This gives a MismatchedTokenException when I get to the "Td" input. I
> suppose this is because that matches with ID as well. What do I do to
> tell the grammar to use the card part only here?

There are a few problems with your grammar.

1) Your grammar says the input has to end with a NEWLINE. You probably
want it to end with the special token EOF.

2) I think you want card to be a token and you don't want rank and
suit to be tokens. You'll learn more about fragment rules in the book.

3) You should handle whitespace differently.

Here's my solution. It works with your example input. Note that you
had several unnecessary parentheses in your grammar.

grammar Mini;

dealingdown
  : '** Dealing down cards **' NEWLINE
    'Dealt to' ID '[' CARD ',' CARD ']' EOF;

CARD: RANK SUIT;
fragment RANK: '2'..'9'|'T'|'J'|'Q'|'K'|'A';
fragment SUIT: 'd'|'c'|'h'|'s';

ID: ('a'..'z'|'A'..'Z'|'_'|'0'..'9')+ ;

NEWLINE: '\r'? '\n';
WS: ' '+ { $channel = HIDDEN; };

> (I have ordered the ANTLR book from Amazon, but it hasn't arrived yet,
> and I can't wait to get my project started.)

It really helped me!

-- 
R. Mark Volkmann
Object Computing, Inc.


More information about the antlr-interest mailing list