ANTLR4中可以匹配空字符串的替代方案具有简单的语法。

huangapple go评论85阅读模式
英文:

Alternative that can match an empty string with simple grammar in ANTLR4

问题

我正在使用ANTLR4构建一个小型解析器,但我对遇到的错误感到困惑。词法分析器的定义如下:
词法分析器规则;

INT             :   'Int';
FLOAT           :   'Float';
STRING          :   'String';
BOOL            :   'Bool';
CHAR            :   'Character';
LIT_INT         :   '0' | DIGIT DIGIT*;
LIT_FLOAT       :   DIGIT+ '.' DIGIT+;
LIT_STRING      :   '"'' (ESCAPE|.)*? '"';
LIT_CHAR        :   '\'' (CHARACTER | ESCAPE) '\''';
LIT_NIL         :   'nil';
WS              :   [ \t]+ -> skip;
ID              :   [a-zA-Z_][a-zA-Z0-9_]+;
LINE_COMMENT    :   '//' .*? '\r'? '\n' -> skip;
COMMENT         :   '/*' .*? '*/' -> skip;

fragment
DIGIT           :   [0-9];
fragment
CHARACTER       :   [a-zA-Z];
fragment
ESCAPE          :   '\\'' | '\\\\' || '\\n';

然而,在LIT_STRING规则中出现了以下错误:规则LIT_STRING包含至少一个可以匹配空字符串的替代项。 我不太明白哪个替代项可以匹配空字符串。我是否漏掉了什么?

英文:

I'm building a small parser with ANTLR4, but I'm confused by an error I've come across. The definition of the lexer is as follows:
lexer grammar LexerRules;

INT             :   'Int';
FLOAT           :   'Float';
STRING          :   'String';
BOOL            :   'Bool';
CHAR            :   'Character';
LIT_INT         :   '0' | DIGIT DIGIT*;
LIT_FLOAT       :   DIGIT+ '.' DIGIT+;
LIT_STRING      :   '"' (ESCAPE|.)*? '"';
LIT_CHAR        :   '\'' (CHARACTER | ESCAPE) '\'';
LIT_NIL         :   'nil';
WS              :   [ \t]+ -> skip;
ID              :   [a-zA-Z_][a-zA-Z0-9_]+;
LINE_COMMENT    :   '//' .*? '\r'? '\n' -> skip;
COMMNET         :   '/*' .*? '*/' -> skip;

fragment
DIGIT           :   [0-9];
fragment
CHARACTER       :   [a-zA-Z];
fragment
ESCAPE          :   '\\"' | '\\\\' || '\\n';

However in the rule for LIT_STRING the following error appears: rule LIT_STRING contains a closure with at least one alternative that can match an empty string.
I don't really understand what is the alternative that can match the empty string. Is there something I am missing?

答案1

得分: 1

我在片段中放了一个|多余的部分。始终检查表达式的书写。

英文:

I had placed a | extra in the fragment. Always check the writing of expressions.

huangapple
  • 本文由 发表于 2023年8月4日 02:58:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定