compiler-constructionantlr4grammar

How to resolve the mistmatched input 'token' expecting 'LEXER_RULE'


I have the following grammar defined in ANTLR4 (g4):

grammar SimpleExpr2;

expr: entityName '(' paramList ')' SEMICOLON;

entityName: ENTITY_NAME;

paramList: param (SEPARATOR param)*;

param: PARAM_NAME ':' DATA_TYPE
     | PARAM_NAME;

ENTITY_NAME: [a-zA-Z_][a-zA-Z0-9_]*;

PARAM_NAME: [a-zA-Z_][a-zA-Z0-9_]*;

DATA_TYPE: 'int'
         | 'string'
         | 'float'
         | 'date'
         | 'text'
         ;

SEPARATOR: ',';

SEMICOLON: ';';

WS: [ \t\n\r]+ -> skip;

Using the following input

entity( parametros:int, parametro:int, paramtrico:float, paramtri);

Apparently it works but the result shows the following errors:

line 1:4 mismatched input 'parametros' expecting PARAM_NAME

line 1:20 mismatched input 'parametro' expecting PARAM_NAME

line 1:35 mismatched input 'paramtrico' expecting PARAM_NAME

line 1:53 mismatched input 'paramtri' expecting PARAM_NAME

The result tree shows the RED color over these tokens

enter image description here

How can I resolve this issue?

The grammar originally had a different order in the rules definition, it was reordered to try to resolve it. For example, initially the same error was with the ENTITY_NAME, but now is with the parameters.


Solution

  • Do it like this:

    param
     : param_name ':' DATA_TYPE
     | param_name
     ;
    
    entity_name : ID;
    param_name : ID;
    
    DATA_TYPE
     : 'int'
     | 'string'
     | 'float'
     | 'date'
     | 'text'
     ;
    
    ID : [a-zA-Z_][a-zA-Z0-9_]*;
    

    Also note that DATA_TYPE has to come before ID.