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

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

antlr - antlr4: Mismatched input on simple grammar

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...