Ply:定义“c”层规则时出现的问题语言
我正在尝试为 C 语言编写一个解析器,它将能够处理表达式、赋值、if-else 和 while 循环。
这是我的规则:
表达式 ->表达式操作表达式
表达式->身份证号
表达式->数量
声明-> ID ASSIGN 表达式
声明-> IF 表达式 THEN 语句
声明-> WHILE 表达式 THEN 语句
大写的所有内容都是一个标记(终结符)
在解析字符串“while h<=0 then t=1”时,似乎将“h”视为一个表达式(使用规则表达式->ID) 。因此,“WHILE 表达式 THEN 语句”中的表达式变为“h”。显然,我希望它将“h<=0”视为表达式(使用规则表达式 -> 表达式 op 表达式)。我如何确保这种情况发生?
I'm trying to write a parser for the c language which will be able to take care of expressions, assignments, if-else and while loops.
here are my rules :
expression -> expression op expression
expression -> ID
expression -> NUMBER
statement -> ID ASSIGN expression
statement -> IF expression THEN statement
statement -> WHILE expression THEN statement
Everything in caps is a token(terminal symbol)
When parsing the string "while h<=0 then t=1", it seems to consider "h" as an expression (using the rule expression->ID). So, the expression in "WHILE expression THEN statement" becomes "h". Obviously, I would want it to consider "h<=0" as the expression (using the rules expression -> expression op expression). How do I make sure that this happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基于您询问 ply.lex 模块的上一篇文章,下面的代码片段似乎就像类 C 语法的部分实现。我没有太多使用 ply,但技巧之一似乎是您需要以正确的顺序定义语法规则。
代码片段的输出是:
Building on the previous post where you were asking about the ply.lex module, the snippet below seems like a partial implementation of a c-like grammar. I haven't used ply much, but one of the tricks seems to be that you need to define the grammar rules in the correct order.
Output from the snippet is: