Flex/Bison 多遍类解析

发布于 2024-11-01 03:39:02 字数 420 浏览 4 评论 0原文

我正在为一种玩具 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 技术交流群。

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

发布评论

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

评论(1

双马尾 2024-11-08 03:39:02

我最近为面向对象语言编写了一个编译器,我们进行了多次传递(当然取决于语言的复杂性):

  1. 收集所有类
  2. 构建超类层次结构
  3. 所有方法和字段
  4. 收集方法内的变量等。

收集 将整个过程分为 4 个阶段:

  1. 当尚未处理所有类时,您无法构建超类层次结构(导致第 2 阶段)
  2. 当以下情况时,您无法验证继承的方法(返回值、参数等)超类未知(导致 2. pass)
  3. 当尚未收集所有字段时,您无法处理变量(导致 4. pass)

如果您的语言没有继承,则可以省略第二遍课程。

当我现在看它时,应该可以合并第 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):

  1. Collect all Classes
  2. Build up superclass hierarchy
  3. Collect all methods and fields
  4. Collect variables inside methods etc.

There are reasons why we had to split up the whole process into 4 passes:

  1. You can't build up the superclass hierarchy when not all classes have been processed yet (led to 2. pass)
  2. You can't validate inherited methods (return value, parameters etc.) when the superclass is unknown (led to 2. pass)
  3. You can't process variables when not all fields have been collected yet (led to 4. pass)

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.

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