简体   繁体   English

为什么括号会创建左递归?

[英]Why do parentheses create a left-recursion?

The following grammar works fine:以下语法可以正常工作:

grammar DBParser;
statement: expr EOF;
expr: expr '+' expr | Atom;
Atom: [a-z]+ | [0-9]+ ;

在此处输入图像描述

However, neither of the following do:但是,以下任何一项都不会:

grammar DBParser;
statement: expr EOF;
expr: (expr '+' expr) | Atom;
Atom: [a-z]+ | [0-9]+ ;
grammar DBParser;
statement: expr EOF;
expr: (expr '+' expr | Atom);
Atom: [a-z]+ | [0-9]+ ;

在此处输入图像描述

Why does antlr4 raise an error when adding in parentheticals, does that somehow change the meaning of the production that is being parsed?为什么 antlr4 在添加括号时会引发错误,这是否会以某种方式改变正在解析的产品的含义?

Parentheses create a subrule, and subrules are handled internally by treating them as though they were new productions (in effect anonymous, which is why the mutual recursion error message only lists one non-terminal).括号创建一个子规则,子规则在内部处理,将它们视为新产生式(实际上是匿名的,这就是相互递归错误消息仅列出一个非终结符的原因)。

In these particular examples, the subrule is pointless;在这些特定示例中,子规则毫无意义; the parentheses could simply be removed without altering the grammar.括号可以简单地删除而不改变语法。 But apparently Antlr doesn't attempt to decide which subrules are actually serving a purpose.但显然 Antlr 并没有试图决定哪些子规则实际上是为某个目的服务的。 (I suppose it could, but I wonder if it's a common enough usage to make justify the additional code complexity. But it's certainly not up to me to decide.) (我想它可以,但我想知道它是否是一种足够普遍的用法来证明额外的代码复杂性是合理的。但这当然不是由我来决定的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM