写 BNF 时,{ 和 } 之间加什么?
我在 BNF 方面遇到了一些麻烦。我不知道什么似乎是做事的标准方式(如果有的话),以及是否有像 char 或 int 或任何已经内置的类型。
但是,我的主要问题是不了解该部分如何大括号中的 BNF 有效。
给出类似的内容:(
exp : term {$$ = $1;}
| exp '+' term {$$ = $1 + $3;}
| exp '-' term {$$ = $1 - $3;}
;
这是从某个地方轻易窃取的,适用于 yacc / C)
花括号中的内容实际上在说什么?我也看过类似的快乐解析器生成器,并且同样感到困惑。
I'm having some trouble with BNF. I can't tell what seems to be the standard way of doing things (if there is one), and whether or not there are types like char or int or whatever already built in.
However, my main problem is not understand how the part of the BNF in curly braces works.
Given something like:
exp : term {$ = $1;}
| exp '+' term {$ = $1 + $3;}
| exp '-' term {$ = $1 - $3;}
;
(This was handily stolen from somewhere, and is for yacc / C)
What are the things in the curly braces actually saying? I've looked at a similar thing for the happy parser generator too, and been similarly confused.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要区分一般的 BNF(和 EBNF)和 Yacc 语法。 BNF 中大括号的含义因方言而异;它通常意味着“选择其中一个选项”,或者它可以与重复相关,或者两者兼而有之。在 EBNF (ISO 14977:1996) 中,“{ ... }”表示重复零次或多次,“{ ... }-”表示重复一次或多次(以及为什么这是“-”而不是“+”是神秘的)。 IETF 使用 RFC-5234 并且其 BNF 方言根本不使用“{}” 。
然而,在 Yacc 语法中,大括号括起规则匹配时要执行的操作(用行话来说是简化的)。因此,“
{$$ = $1;}
”操作的意思是“将与“term”匹配的值分配给约简“exp ::= term”的结果(使用 BNF 的另一种变体)。You need to distinguish between BNF in general (and EBNF) and the Yacc syntax. What the braces mean in BNF varies with dialect; it often means 'choose one of the alternatives', or it can be associated with repetition, or both. In EBNF (ISO 14977:1996), '{ ... }' means repeat zero or more times, and '{ ... }-' means repeat one or more times (and why that is a '-' and not a '+' is mysterious). The IETF uses RFC-5234 and its dialect of BNF does not use '{}' at all.
In a Yacc grammar, though, the braces enclose the actions to be performed when the rule is matched (reduced in the jargon). So, the '
{$$ = $1;}
' action means 'assign the value matched by 'term' to the result of reducing 'exp ::= term' (using another variant of BNF).大括号内的内容实际上是解析相应规则时执行的 C 代码。
$
符号是占位符,将替换为 yacc 解析的实际值:$$
是您希望计算的结果,而$1
是$n
表示规则右侧符号的值。例如,规则
exp '+' term { $$ = $1 + $3; }
,$1
指的是exp
,$3
是term
,所以这表示当解析此规则,添加exp
和term
即可得到结果。The stuff within curly braces is actually C code that is executed when the corresponding rule is parsed. The
$
symbols are placeholders that are replaced with the actual values parsed by yacc:$$
is the result you wish to compute, while$1
to$n
represent the values of the symbols on the right-hand side of the rule.For example, the rule
exp '+' term { $$ = $1 + $3; }
,$1
refers to theexp
and$3
is theterm
, so this says that when this rule is parsed, addexp
andterm
to get the result.