如何使用运算符优先级来实现解析?

发布于 2024-10-01 19:00:40 字数 88 浏览 0 评论 0原文

我想使用运算符优先级来实现解析。我已经实现了 +、-、* 和 /。我如何在不使用任何语法的情况下实现休息?这是一个大学项目,不允许使用 yacc 或 bison。

I want to implement parsing using operator precedence. I have implemented +, -, *, and /. How would I implement rest with out using any grammar? This is a college project and yacc or bison are not allowed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ぺ禁宫浮华殁 2024-10-08 19:00:40

您需要的是一个递归下降解析器(因为这是唯一可以轻松手工编写的解析器)。详细信息请参阅维基百科,这很简单。

因此,要获得正确的运算符优先级,您可以执行以下操作:

term = number
unary = ('-' | '+')* term
multiplication = unary ('*' | '/' unary)*
addition = multiplication ('+' | '-' multiplication)*
expression = addition

其中“表达式”是您的起始规则。

What you need is a recursive descent parser (because that's the only parser that can easily be written by hand). See Wikipedia for details, it's pretty easy.

So, to get operator precedence right you can do something like this:

term = number
unary = ('-' | '+')* term
multiplication = unary ('*' | '/' unary)*
addition = multiplication ('+' | '-' multiplication)*
expression = addition

Where 'expression' is your starting rule.

失退 2024-10-08 19:00:40

由于您不允许使用解析器生成器,因此我建议阅读有关 递归下降解析器

龙之书中有非常好的介绍

Since you're not allowed to use a parser generator, I would recommend reading about the Recursive descent parser
.
A very good introduction is included in the Dragon Book

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文