为什么 Antlr 认为缺少括号?
我创建了一个语法来解析简单的 LDAP 查询语法。语法是:
expression : LEFT_PAREN! ('&' | '||' | '!')^ (atom | expression)* RIGHT_PAREN! EOF ;
atom : LEFT_PAREN! left '='^ right RIGHT_PAREN! ;
left : ITEM;
right : ITEM;
ITEM : ALPHANUMERIC+;
LEFT_PAREN : '(';
RIGHT_PAREN : ')';
fragment ALPHANUMERIC
: ('a'..'z' | 'A'..'Z' | '0'..'9');
WHITESPACE : (' ' | '\t' | '\r' | '\n') { skip(); };
现在这个语法适用于:
(!(attr=hello2))
(&(attr=hello2)(attr2=12))
(||(attr=hello2)(attr2=12))
但是,当我尝试运行时:
(||(attr=hello2)(!(attr2=12)))
它失败了: line 1:29 extraneous input ')' Expected EOF
如果我从表达式语法中删除 EOF,一切都会通过,但随后出错括号的数量不会被视为语法错误。 (这被解析成一棵树,因此标记后面有 ^ 和 !)我错过了什么?
I've created a grammar to parse simple ldap query syntax. The grammer is:
expression : LEFT_PAREN! ('&' | '||' | '!')^ (atom | expression)* RIGHT_PAREN! EOF ;
atom : LEFT_PAREN! left '='^ right RIGHT_PAREN! ;
left : ITEM;
right : ITEM;
ITEM : ALPHANUMERIC+;
LEFT_PAREN : '(';
RIGHT_PAREN : ')';
fragment ALPHANUMERIC
: ('a'..'z' | 'A'..'Z' | '0'..'9');
WHITESPACE : (' ' | '\t' | '\r' | '\n') { skip(); };
Now this grammar works fine for:
(!(attr=hello2))
(&(attr=hello2)(attr2=12))
(||(attr=hello2)(attr2=12))
However, when I try and run:
(||(attr=hello2)(!(attr2=12)))
It fails with: line 1:29 extraneous input ')' expecting EOF
If I remove the EOF off the expression grammar, everything passes, but then wrong numbers of brackets are not caught as being a syntax error. (This is being parsed into a tree, hence the ^ and ! after tokens) What have I missed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如其他人已经提到的,您的表达式必须以 EOF 结尾,但嵌套表达式当然不能以 EOF 结尾。
从
表达式
中删除EOF
,并为解析器创建一个以EOF
结尾的正确“入口点”。file: Tg
file: Main.java
要运行演示,请执行:
*nix/MacOS:
Windows:
生成表示以下 AST 的 DOT 代码:
使用 graphviz-dev.appspot.com
As already mentioned by others, your expression has to end with a
EOF
, but a nested expression cannot end with anEOF
, of course.Remove the
EOF
fromexpression
, and create a proper "entry point" for your parser that ends with theEOF
.file: T.g
file: Main.java
To run the demo, do:
*nix/MacOS:
Windows:
which produces the DOT code representing the following AST:
image created using graphviz-dev.appspot.com
在表达式的定义中,可以有包含嵌套表达式的括号,但嵌套表达式必须以 EOF 结尾。在示例输入中,嵌套表达式不以 EOF 结尾。
In your definition of expression, there can be parentheses containing a nested expression, but the nested expression has to end in EOF. In your sample input, the nested expression doesn't end in EOF.