Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a simple grammar that keeps giving me mismatched input on seemingly right inputs. My grammar is as follows

root: expression;

expression
  : METRIC comparator RHS
  | expression AND expression
  | expression OR expression
  | LPAREN expression RPAREN
  ;

comparator
  : EQ | GT | GE | LT | LE;

EQ: [eE][qQ];
GE: [gG][eE];
GT: [gG][tT];
LE: [lL][eE];
LT: [lL][tT];

LPAREN: '(';
RPAREN: ')';

AND: [aA][nN][dD];
OR: [oO][rR];

WS: [ 

]+;

METRIC: 'latency' | 'qps';
RHS: 'foobar' | 'foobaz';

Why does this grammar give a mismatched input 'latency' error when the input is latency eq foobar. Surely this follows the first production METRIC comparator RHS

question from:https://stackoverflow.com/questions/65852640/antlr4-mismatched-input-on-simple-grammar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
682 views
Welcome To Ask or Share your Answers For Others

1 Answer

The grammar you posted does not produce the error/warning "mismatched input 'latency'". You probably didn't regenerate the lexer- and parser classes if this is the case.

The only problem with the grammar from you question is the fact that for the input latency eq foobar, the lexer produces WS tokens which your parser does not accept.

You probably want to skip these WS tokens in the lexer:

WS: [ 

]+ -> skip;

With that change, your parser will produce the following parse tree for the input latency eq foobar:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...