How can my ANTLR lexer match a token from characters that are subsets of another kind of token?

I have what I consider to be a simple ANTLR question. I have two types of tokens: identand special_ident. I want mine to special_identmatch one letter followed by one number. I want the common identone to correspond to one letter, not necessarily followed by any number of letters or numbers. My (incorrect) grammar is below:

expr 
    : special_ident
    | ident
    ;

special_ident : LETTER DIGIT;
ident         : LETTER (LETTER | DIGIT)*;

LETTER : 'A'..'Z';
DIGIT  : '0'..'9';

When I try to check this grammar, I get this warning:

The solution may correspond to the input, for example, “LITTER DIGIT”, using several alternatives: 1, 2. As a result, alternative 2 was disabled for this input

, , , A1, ident, special_ident. , special_ident .

, :

A      : ident
A1     : special_ident
A1A    : ident
A12    : ident
AA1    : ident

, ?

+5
2

, , :

  • AN
  • AA (A | N) *
  • ( | ) +

2 special_ident, ident. . , ANTLRWorks, , , . , , 99% , .

prog 
    :    (expr WS)+ EOF;

expr 
    : special_ident {System.out.println("Found special_ident:" + $special_ident.text + "\n");}
    | ident {System.out.println("Found ident:" + $ident.text + "\n");}
    ;

special_ident : LETTER DIGIT;

ident         : LETTER 
    |LETTER DIGIT (LETTER|DIGIT)+
    |LETTER LETTER (LETTER|DIGIT)*;

LETTER : 'A'..'Z';
DIGIT  : '0'..'9';
WS 
    :   (' '|'\t'|'\n'|'\r')+;
+2

, 3 :

  • A
  • AN
  • A(A|N)(A|N)+

special_ident, - ident; , .

ANTLR, , . , :

long_ident    : LETTER (LETTER | DIGIT) (LETTER | DIGIT)+
special_ident : LETTER DIGIT;
ident         : LETTER | long_ident;
+3

All Articles