Antlr grammar with single quotes doubling as operators
I am working o开发者_如何学JAVAn an Antlr grammar in which single quotes are used both as operators and in string literals, something like:
operand: DIGIT | STRINGLIT | reference;
expression: operand SQUOTE;
STRINGLIT: '\'' ~('\\'|'\'')* '\'';
Expressions like 1'
parse correctly, but when there is input that matches ~('\\'|'\'')*
after the quote, such as 1'+2
, the lexer attempts to match STRINGLIT
and fails. I'd like to be able to recover and emit SQUOTE
. Any ideas how to accomplish it?
Thanks.
After testing this grammar a bit in Antlrworks, I think that your problem is that you are being too restrictive here. Antlr would be able to parse 1'+2
if you had a rule that accepted something after it has seen operand SQUOTE
. Since ANTLR doesn't know what to do with the +2
, it throws an exception.
精彩评论