Flex/Bison 多遍类解析
我正在为一种玩具 OO 语言编写一个编译器。我使用 Flex 和 Bison 用 C 语言编写它。
考虑以下语法:
class MyClass {
int m_n;
void MyFunc(int b) {
m_n = 5;
m_p = b;
}
int m_p;
}
我当前的代码会抱怨在 MyFunc 中,m_p 尚未声明(有充分的理由)。因此,我得出的结论是,我需要一种多遍解析技术 - 大致如下:
第一遍 - 处理变量声明
第二遍 - 首先处理函数定义
- 这是解决问题的最佳方法吗?我还应该研究其他方法吗?其次 - 如果这是一个有利的解决方案,我会用可重入的词法分析器/解析器来实现它吗?
谢谢
I am writing a compiler for a toy OO language. I am writing it in C, using Flex and Bison.
Consider the following syntax:
class MyClass {
int m_n;
void MyFunc(int b) {
m_n = 5;
m_p = b;
}
int m_p;
}
My current code will complain that in MyFunc, m_p has not yet been declared (with good reason). So, I came to the conclusion that I need a multi-pass parsing technique - something along the lines of:
1st pass - process variable declarations
2nd pass - process function definitions
First - is this the best way to solve the issue? Are there other methods that I should look into? Second - if this is a favorable solution, would I go about implementing it with a re-entrant lexer/parser?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最近为面向对象语言编写了一个编译器,我们进行了多次传递(当然取决于语言的复杂性):
收集 将整个过程分为 4 个阶段:
如果您的语言没有继承,则可以省略第二遍课程。
当我现在看它时,应该可以合并第 2 遍和第 3 遍,因为所有数据都应可用于第 3 遍。
我们实现它的方式只是遍历 AST 并使用所需的符号表对其进行注释。
I recently wrote a compiler for an OO language, we had multiple passes (depending on the complexity of the language of course):
There are reasons why we had to split up the whole process into 4 passes:
You can leave out the second pass if you don't have inheritance in your language of course.
When I look at it now, it should've been possible to merge pass 2 and 3 as all data should be available for pass 3.
The way we implemented it was just by walking through the AST and annotating it with the required symbol tables.