从语义分析阶段重用符号表以生成代码 [英] Reusing symbol table from semantic analysis phase for code generation

查看:220
本文介绍了从语义分析阶段重用符号表以生成代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为具有全局变量和嵌套子例程功能的语言构建编译器.以前,我只为语言创建过一个编译器,该语言只具有局部变量而没有嵌套的子例程.

I'm currently building a compiler for a language which has global variable and nested subroutine feature. Previously, I've only ever built a compiler for languages which only has local variable without nested subroutine.

在代码生成阶段,如何重用在语义分析阶段填充的符号表,我遇到了一个问题.我将符号表做成一堆链表,其中每个链表代表在特定作用域中声明的标识符.每次进入作用域时,都会创建一个新列表并将其推入堆栈,并成为当前作用域.同样,每次离开示波器时,都会弹出堆栈顶部的列表.最后,在语义分析完成之后,实际上我有一个空的符号表,就像它开始时一样.但是,代码生成器需要一个完全填充的符号表才能正确生成代码.如何在不重新进行语义分析期间(即在符号表中输入标识符)的情况下完成此操作?

I have a problem on how to reuse symbol table filled during semantic analysis phase in code generation phase. I make the symbol table as a stack of linked list, where each linked list represents identifiers declared in a particular scope. Every time it enters a scope, a new list is created and pushed to the stack and it becomes current scope. Likewise, every time it leaves a scope, the list on top of stack is popped. In the end, after the semantic analysis finishes, I practically have empty symbol table, just like when it starts. However, the code generator needs a completely filled symbol table to correctly generate code. How can this be done without re-doing what has been done during semantic analysis (i.e. entering identifiers to the symbol table)?

推荐答案

由于您的问题,这将有点抽象-因为我对编译器的内部数据结构一无所知.

This is going to be a bit abstract - as your question - since I don't know anything concrete about your compiler's internal data structures.

当您弹出范围时,而不是像现在假设的那样删除范围,请将指向范围数据的指针分配给该范围代码生成所基于的数据成员,以便代码生成器可以到达它.

When you pop your scope, instead of deleting it, as I assume you do now, assign the pointer to the scope data to a member of the data that you base code generation on for that scope, so that the code generator can get to it.

这篇关于从语义分析阶段重用符号表以生成代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆