I have a simple grammar like this:
grammar mygrammar;
the_rule : 'abc' 'xyz' ;
WS : [ \t\r\n\u000C]+ -> channel(HIDDEN) ;
When I parse the text "abc xyz" with the_rule(), I get the expected string tree representation:
(the_rule abc xyz)
However, then I add the following lexer rule, which I think means "anything except for a w":
TEXT : ~[w]+ ;
Now when I parse the text "abc xyz" with the_rule(), I get an error:
line 1:0 mismatched input 'abc xyz' expecting 'abc'
Why would the TEXT lexer rule affect this? I think I'm misunderstanding something simple. :-(
ANTLR lexer rules are greedy: the rule that matches the most wins. So, in your case, the entire input, abc xyz, is matched by TEXT. It doesn't matter if your parser is trying to match abc, the lexer operates independently from the parser.
来源:https://stackoverflow.com/questions/31254455/antlr-mismatched-input