gpt4 book ai didi

c++ - 使用 BNF 在 Bison 中实现循环

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:10 25 4
gpt4 key购买 nike

所以,我得到了这段代码:

calclist: /* nothing */   matches at beginning of input
| calclist exp EOL { printf("= %d\n", $1); } EOL is end of an expression
;

解释说:

the first two rules, which define the symbol calcset, implement a loop that reads an expression terminated by a newline and prints its value. The definition of calclist uses a common two-rule recursive idiom to implement a sequence or list: the first rule is empty and matches nothing; the second adds an item to the list. The action in the second rule prints the value of the exp in $2.

摘自《Flex and Bison》一书。有人可以告诉我这种语法如何暗示循环吗? exp中的递归我能看懂(后面会写,但我不包括因为它在这里无关紧要)。但是,看看这样的语法,我只能想到第一个规则不匹配任何内容以保持解析器不处理任何内容,因此具有无限循环,直到从标准输入流给出第一个符号并启动第二个规则。但是,我不明白第二条规则。它怎么能到达 exp 部分呢?遇到calclist不是一直递归吗?

最佳答案

第二条规则意味着一个循环,就好像你有这样一行:

exp EOL exp EOL exp EOL exp EOL

每个“exp EOL”都是一个计算列表,包含在另一个计算列表中。因此,规则将减少该行:

exp EOL exp EOL exp EOL exp EOL
calclist1 exp EOL exp EOL exp EOL exp EOL < - Rule 1. calclist1 is [ ], the empty string.
calclist2 exp EOL exp EOL exp EOL < - Rule 2. calclist2 is calclist1 exp EOL
calclist3 exp EOL exp EOL < - Rule 2. calclist3 is calclist2 exp EOL
calclist4 exp EOL < - Rule 2. calclist4 is calclist3 exp EOL
calclist5 < - Rule 2. calclist5 is calclist4 exp EOL

这就是它创建循环的意思。与您引用的部分一样,这是定义语法以创建任意长度的表达式列表时的常见“习惯用法”。

我希望这能回答您的问题。

谢谢!

关于c++ - 使用 BNF 在 Bison 中实现循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8812954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com