如何构建不同词汇级别的符号表?

发布于 2024-10-14 23:50:12 字数 321 浏览 7 评论 0原文

我正在为类似 C 的语言构建编译器。我已经完成了词法分析器和解析器。现在,我正在尝试进行语义分析并尝试构建符号表。 现在,根据规范,同一词法级别不允许重复声明。这需要为每个词汇级别构建不同的符号表,对吧?我该怎么做呢? 到目前为止,我拥有的一个符号表采用二叉树的形式,其中每个节点如下所示:

struct tree_el
{
    char *identifier;
    char *type;
    struct tree_el *right, *left;
}

如何将特定节点指向另一棵树的“根”节点?

任何帮助都会很棒!非常感谢。

I'm in the middle of building a compiler for a C-like language. I'm somewhat done with the lexer and parser. Right now, I'm trying to do semantic analysis and am trying to build symbol tables.
Now, according to the specifications, duplicate declarations are not allowed in the same lexical level. This necessitates building a different symbol table for each lexical level, right? How do I go about doing this?
As of now, the one symbol table I have is in the form of a binary tree where each node looks like this:

struct tree_el
{
    char *identifier;
    char *type;
    struct tree_el *right, *left;
}

How do I point a particular node to the "root" node of another tree?

Any help will be great! Thanks much.

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

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

发布评论

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

评论(2

溺孤伤于心 2024-10-21 23:50:12

通常,这是通过类似堆栈的结构来完成的:每个“词汇级别”在启动时在堆栈上打开,并且在遇到其他级别时将其推送。

例如:

int i,j,k;

while (i) {
   int q, r, s;

   ...
}

当您解析此内容时,您首先需要定义 i jk 并添加它们。然后,您将点击 while 语句,并“推送”q rs 的定义。当 while 语句作用域退出时,您将“弹出” q rs 等。

Typically this is done with a stack-like structure: each "lexical level" is opened on the stack when started, and additional levels are pushed on as they're encountered.

For example:

int i,j,k;

while (i) {
   int q, r, s;

   ...
}

As you were parsing this, you'd first definitions for i j and k and you'd add those. Then you'd hit the while statement, and "push" definitions for q r and s. When the while statement scope exited, you'd "pop" off q r and s, etc.

遇见了你 2024-10-21 23:50:12

您需要为每个词法范围建立一个单独的符号树,其中仅包含直接在该范围内定义的符号。查找符号时,首先查找最深的包含范围,然后查找父范围,依此类推,直到到达文件范围。

You need a separate tree of symbols for each lexical scope, that contains just the symbols directly defined within that scope. When looking up a symbol, look first in the deepest containing scope, then then parent scope, and so on until you reach file scope.

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