Antlr 4.5 parser error during runtime

The error message means that the expected token type containing the value ‘void’ does not match the actual token type produced by consuming the string ‘void’ from the input. Looking at your lexer rules suggests that the input string ‘void’ is being consumed by the IDENTIFIER rule, producing a token of type IDENTIFIER, not VOID.

In general, the lexer rule that matches longest input string wins. For two (or more) rules with the same match length, the first listed wins. Move all of your keyword rules above the IDENTIFIER rule.

A helpful unit test form will dump the lex’d tokens and show the actual token types matched. Something like:

CommonTokenStream tokens = ...
tokens.fill();
StringBuilder sb = new StringBuilder();
for (Token token : tokens.getTokens()) {
    sb.append(((YourCustomTokenType) token).toString());
}
System.out.print(sb.toString());

The Token.toString() method is usually good enough. Override in your token subclass to fit your own needs.

Leave a Comment