compiler-constructioncode-generationcode-reusesemantic-analysissymbol-table

Reusing symbol table from semantic analysis phase for code generation


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)?


Solution

  • 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.