Question

I'm trying to build a grammar but am getting stuck on this error and can't see where I've gone wrong.

If I enter the phrase:

if(hello = "test", 1, 0)

into the antlr4 testrig I get *"mismatched input '=' expecting COMPARE_OP"*. What am I doing wrong?

Here's my full grammar:

prog: (expr|stats);
val_expr: (rename|rex);
cond_expr: (match|xif|compare_op);
expr: (val_expr|cond_expr|var|math_expr|eval);
rename : 'rename' var 'as' LITERAL;   // match keyword hello followed by an 
count : 'count' ('as' LITERAL)* ('by' var (',' var)* )*;  // 
match : 'match' '(' cond_expr ',' expr ')'; // match(x, y)
xif : 'if' '(' cond_expr ',' expr ',' expr ')'; // if(x, y, z)
var: (VARNAME|LITERAL|BLANK);
stats: 'stats' count;
eval: 'eval' VARNAME '=' expr; 
rex: 'rex' ('field' '=' var)* LITERAL;
compare_op: math_term COMPARE_OP math_term;
math_expr: math_term (MATH_OP math_term)*;
math_term: (var|DIGITS);

VARNAME : [a-zA-Z_]([a-zA-Z0-9_])*;
DIGITS: [0-9]+;
WS : [ \t\r\n]+ -> skip ;
BLANK: '""';
LITERAL : '"' ( '\\"' | . )*? '"' ;
COMPARE_OP: ([=><]|'>='|'<=');
MATH_OP: ('+'|'/'|'%'|'*'|'-');
Was it helpful?

Solution

It is because you ask it to match '=' in two ways: one as a literal in the grammar and one as part of the COMPARE_OP. It uses the most specific, which is plain '='. I suggest that you split '=' out from COMPARE_OP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top