关于编译器符号表的简单问题

发布于 2024-11-04 19:21:38 字数 572 浏览 7 评论 0原文

我正在开发一种小型的基于对象的编程语言。

不过,我对一件简单的事情有点迷失。我已经实现了几个访问者,它们收集 AST 中类的名称、类型和参数、方法头和字段。

我的问题是现在如何处理我的方法主体。我应该将局部变量添加到符号表中吗?

一开始这看起来像是一个好主意,直​​到有人想到这样的情况:

void myMethod() {
    int i;

    while (something) {
        int y;
    }

    while (something) {
        int y;
    }   
}

我是否只是将 iy 变量添加到符号表中,并且我会发现 y 是一个重复的变量。

请记住,我了解符号表范围。我无法理解的是,是否应该在方法内部动态添加和删除符号表上的信息,或者是否应该在访问方法时将数据永久添加到符号表中(就像我对类+字段+所做的那样)方法标题)。

重申一下问题:访问方法体时,我应该让符号表在访问结束时与访问前一样吗?

谢谢!

I am developing a small object-based programming language.

I am a bit lost on a simple thing, though. I have implemented a couple of visitors that collect the names, types and parameters of classes, method headers and fields off the AST.

My problem is on what to do now with the body of my methods. Should I add the local variables to the Symbol Table?

It could look like a nice idea at first, until one thinks of a case such as:

void myMethod() {
    int i;

    while (something) {
        int y;
    }

    while (something) {
        int y;
    }   
}

Were I just to add the i and y variables to the Symbol Table, and I'd get that y is a duplicated variable.

Keep in mind I know about Symbol Table Scopes. What I fail to grasp is whether one should add and delete info on the fly on the Symbols Table while inside a method, or if I should add data permanently to the Symbol Table when visiting a method (like I did with the class+fields+methodsheader).

Restating the question: when visiting a method body, should I let the Symbol Table, at the end of the visit, just as it was before the visit?

Thanks!

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

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

发布评论

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

评论(2

始终不够爱げ你 2024-11-11 19:21:38

您有一个表示程序结构的 AST。 AST 中的某些节点代表新的范围(方法入口、块体……)。

您可以构建一个与 AST 形状相同的符号表:无论您在哪里有表示范围介绍的 AST 节点,都可以构建从符号到其声明的关联映射。

您必须按照语言语义确定的顺序搜索范围,但至少您会知道在哪里查找每个范围。

You have an AST representing the program structure. Certain nodes in the AST represent new scopes (method entry, block bodies, ...).

You could build a symbol table that has the same shape as your AST: whereever you have an AST node that represents a scope introduction, build an associated map from symbols to their declarations.

You'll have to search the scopes in an order determined by your language semantics, but at least you'll know where to look for each scope.

阳光下慵懒的猫 2024-11-11 19:21:38

为什么不对程序的块进行建模,这样就可以让块拥有符号表。在这种情况下,y 可能存在于两个不同的块中,因为这两个实例将被放置在两个不同的符号表中。

Why don't you model the blocks of the program, that way you could let a block own a symbol table. In that scenario y could be alive in two different blocks, as the two instances would be placed in two different symbol tables.

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