Whenever 2 (or more) rules correspond to the same number of characters, the first one will βwinβ. So, if you define RESERVED_WORD before the ID , for example:
RESERVED_WORD : 'class' | 'public' | 'static' | 'extends' | 'void' | 'int' | 'boolean' | 'if' | 'else' | 'while' | 'return' | 'null' | 'true' | 'false' | 'this' | 'new' | 'String' ; ID : LETTER (LETTER | DIGIT)* ; fragment DIGIT : '0'..'9' ; fragment LETTER : 'a'..'z' | 'A'..'Z' ;
The input "class" will be indicated as RESERVED_WORD .
Note that creating a simple marker that matches any reserved word does not make much sense: this is usually done as follows:
// ... NULL : 'null'; TRUE : 'true'; FALSE : 'false; // ... ID : LETTER (LETTER | DIGIT)* ; fragment DIGIT : '0'..'9' ; fragment LETTER : 'a'..'z' | 'A'..'Z' ;
Now "false" will become the FALSE token and "falser" a ID .
source share