Antlr 语法中的赋值表达式
我正在尝试扩展 Tiny Language 的语法< /a> 将赋值视为表达式。 是有效的
a = b = 1; // -> a = (b = 1)
a = 2 * (b = 1); // contrived but valid
a = 1 = 2; // invalid
因此,编写赋值与其他运算符在两个方面有所不同 。它是右关联的(没什么大不了的),它的左侧必须是一个变量。所以我像这样改变了语法
statement: assignmentExpr | functionCall ...;
assignmentExpr: Identifier indexes? '=' expression;
expression: assignmentExpr | condExpr;
它不起作用,因为它包含一个非 LL(*) 决策。我也尝试过这个变体:
assignmentExpr: Identifier indexes? '=' (expression | condExpr);
但我得到了同样的错误。 感兴趣
- 我对这个特定问题
- 给定一个非 LL(*) 决策的语法,如何找到导致问题的两条路径
- 如何修复它
I'm trying to extend the grammar of the Tiny Language to treat assignment as expression. Thus it would be valid to write
a = b = 1; // -> a = (b = 1)
a = 2 * (b = 1); // contrived but valid
a = 1 = 2; // invalid
Assignment differs from other operators in two aspects. It's right associative (not a big deal), and its left-hand side is has to be a variable. So I changed the grammar like this
statement: assignmentExpr | functionCall ...;
assignmentExpr: Identifier indexes? '=' expression;
expression: assignmentExpr | condExpr;
It doesn't work, because it contains a non-LL(*) decision. I also tried this variant:
assignmentExpr: Identifier indexes? '=' (expression | condExpr);
but I got the same error. I am interested in
- This specific question
- Given a grammar with a non-LL(*) decision, how to find the two paths that cause the problem
- How to fix it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你可以像这样改变你的语法来实现相同的目的,而不使用句法谓词:
我改变了巴特的例子,考虑到这个想法:
对于输入:
你得到以下解析树:
I think you can change your grammar like this to achieve the same, without using syntactic predicates:
I altered Bart's example with this idea in mind:
And for the input:
you get following parse tree:
这里的关键是,您需要向解析器“保证”表达式内部存在满足该表达式的内容。这可以使用语法谓词(
add
和mult
规则中的( ... )=>
部分)来完成。一个快速演示:
它将把输入解析
为以下 AST:
The key here is that you need to "assure" the parser that inside an expression, there is something ahead that satisfies the expression. This can be done using a syntactic predicate (the
( ... )=>
parts in theadd
andmult
rules).A quick demo:
which will parse the input:
into the following AST: