如何构建不同词汇级别的符号表?
我正在为类似 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,这是通过类似堆栈的结构来完成的:每个“词汇级别”在启动时在堆栈上打开,并且在遇到其他级别时将其推送。
例如:
当您解析此内容时,您首先需要定义
i
j
和k
并添加它们。然后,您将点击 while 语句,并“推送”q
r
和s
的定义。当 while 语句作用域退出时,您将“弹出”q
r
和s
等。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:
As you were parsing this, you'd first definitions for
i
j
andk
and you'd add those. Then you'd hit the while statement, and "push" definitions forq
r
ands
. When the while statement scope exited, you'd "pop" offq
r
ands
, etc.您需要为每个词法范围建立一个单独的符号树,其中仅包含直接在该范围内定义的符号。查找符号时,首先查找最深的包含范围,然后查找父范围,依此类推,直到到达文件范围。
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.