Note: This is a self-answered question that aims to provide a reference about one of the most common mistakes made by ANTLR users.
When I test this very simple grammar:
grammar KeyValues;
keyValueList: keyValue*;
keyValue: key=IDENTIFIER '=' value=INTEGER ';';
IDENTIFIER: [A-Za-z0-9]+;
INTEGER: [0-9]+;
WS: [ \t\r\n]+ -> skip;
With the following input:
foo = 42;
I end up with the following run-time error:
line 1:6 mismatched input '42' expecting INTEGER
line 1:8 mismatched input ';' expecting '='
Why doesn't ANTLR recognize 42 as an INTEGER in this case?
It should match the pattern [0-9]+ just fine.
If I invert the order in which INTEGER and IDENTIFIER are defined it seems to work, but why does the order matter in the first place?