Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Antlr4, mismatched input error: the token is not recognized

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

The rule MODIFIER will never match because all the rules a MODIFIER is made from is 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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading