解析器规则不会产生无效输入的错误

发布于 2025-01-23 13:57:47 字数 772 浏览 0 评论 0原文

我发现了一种奇怪的解析器行为,无法向我解释。如果我做错了什么,也许你们中的人可以给我一个提示。

我有关注的语法文件:

grammar test;

/*
 * Parser Rules
 */
unary_expr
  : unary_operator IDENTIFIER;

unary_operator
  : PLUS PLUS;

/*
 * Lexer Rules
 */
IDENTIFIER: [a-zA-Z]+;
PLUS: '+';

NEWLINE
  : ( '\r'? '\n' | '\r' )+ -> skip;

测试此语法时,

++abc++def

当我用Lexer

Tokens:
[@0,0:0='+',<2>,1:0]
[@1,1:1='+',<2>,1:1]
[@2,2:4='abc',<1>,1:2]
[@3,5:5='+',<2>,1:5]
[@4,6:6='+',<2>,1:6]
[@5,7:9='def',<1>,1:7]
[@6,12:11='<EOF>',<-1>,2:0]

将正确检测到所有令牌,但是解析树绝对不能覆盖所有检测到的令牌!

Parse Tree:
unary_expr (
  unary_operator (
    "+"
    "+"
  )
  "abc"
)

我在做什么错?

I have discovered a strange parser behavior and cannot explain it to me. Maybe someone of you can give me a hint if I am doing something wrong.

I have following grammer file:

grammar test;

/*
 * Parser Rules
 */
unary_expr
  : unary_operator IDENTIFIER;

unary_operator
  : PLUS PLUS;

/*
 * Lexer Rules
 */
IDENTIFIER: [a-zA-Z]+;
PLUS: '+';

NEWLINE
  : ( '\r'? '\n' | '\r' )+ -> skip;

When I test this grammar with

++abc++def

the lexer will detect all tokens properly

Tokens:
[@0,0:0='+',<2>,1:0]
[@1,1:1='+',<2>,1:1]
[@2,2:4='abc',<1>,1:2]
[@3,5:5='+',<2>,1:5]
[@4,6:6='+',<2>,1:6]
[@5,7:9='def',<1>,1:7]
[@6,12:11='<EOF>',<-1>,2:0]

But the parse tree definitely does not cover all detected tokens!

Parse Tree:
unary_expr (
  unary_operator (
    "+"
    "+"
  )
  "abc"
)

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖心男生 2025-01-30 13:57:47

如果您告诉Antlr匹配Parser Rule unary_expr消耗的任何代币,那么这正是Antlr所做的。

如果要强制ANTLR消耗 all 令牌,请在解析器规则结束时添加eof令牌:

unary_expr
 : unary_operator IDENTIFIER EOF
 ;

现在您会看到您的预期错误:

If you tell ANTLR to match whatever tokens are consumed by parser rule unary_expr, then that is exactly what ANTLR does.

If you want to force ANTLR to consume all tokens, add the EOF token at the end of your parser rule:

unary_expr
 : unary_operator IDENTIFIER EOF
 ;

Now you will see your expected error:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文