Home > Enterprise >  Antlr4, mismatched input error: the token is not recognized
Antlr4, mismatched input error: the token is not recognized

Time:12-09

I have the following ANTLR grammar:

declareField : MODIFIER* typeVar nameType ASSIGN value ';';
nameType : NAME(('.')NAME)*;
typeVar : nameType | nameType'<'typeVar'>' | typeVar'['']';
value : PRIMITIVE_VALUE;

And such a set of tokens:

ASSIGN : '=';

NULL : 'null';
INT : [0-9] ;
FLOAT : [0-9] .[0-9] ;
STRING : '"'[a-zA-Z_0-9.]*'"';
CHAR : '\''[a-zA-Z_0-9]'\'';
BOOLEAN : TRUE | FALSE;
TRUE : 'true';
FALSE : 'false';

PRIMITIVE_VALUE : INT | FLOAT | STRING | CHAR | BOOLEAN | NULL;

PUBLIC : 'public';
PRIVATE : 'private';
FINAL : 'final';
STATIC : 'static';
VOLATILE : 'volatile';
TRANSIENT : 'transient';
SYNCHRONIZED : 'synchronized';
NATIVE : 'native';
ABSTRACT : 'abstract';
PROTECTED : 'protected';

MODIFIER : PUBLIC | PRIVATE | FINAL | STATIC | VOLATILE | TRANSIENT | SYNCHRONIZED | NATIVE | ABSTRACT | PROTECTED;

NAME : [a-zA-Z_][a-zA-Z_0-9]*;
WS: [ \t\r\n]  -> channel(HIDDEN);

I expected such input data will be accepted by my grammar:

protected static final int test = 10;

But I get the following error.

line 1:0 mismatched input 'protected' expecting {MODIFIER, NAME}

Although the token 'protected' should definitely be accepted by the rule MODIFIER

CodePudding user response:

The rule MODIFIER will never match because all the rules a MODIFIER is made from are matched before MODIFIER.

Change it to be a parser rule instead:

declareField : modifier* typeVar nameType ASSIGN value ';';

...

modifier : PUBLIC | PRIVATE | FINAL | STATIC | VOLATILE | TRANSIENT | SYNCHRONIZED | NATIVE | ABSTRACT | PROTECTED;

PUBLIC : 'public';
PRIVATE : 'private';
FINAL : 'final';
STATIC : 'static';
VOLATILE : 'volatile';
TRANSIENT : 'transient';
SYNCHRONIZED : 'synchronized';
NATIVE : 'native';
ABSTRACT : 'abstract';
PROTECTED : 'protected';
  • Related