how symboltable track functions defined later?

44 Views Asked by At

I am trying to write a compiler and get stuck on one step: How to make symboltable to support track functions defined later: here is a golang code example:

func first(){
  second()
}

func second(){
}

I have got an ast of the code. and I want to build nested symboltable for scopes. I am traveling the ast and when I come across the first calling of "second()", as the symbol 'second' is still not in the symboltable (not travelled yet), so I can't decide whether 'second()' is legal or not. I know I can travel the tree twice to solve this problem. But it seems make the code more complicated. Just want to know how normal compiler solve this issue? if they travelled the tree twice, how did it save the symboltable to support that when travelling second time, the node can find the symboltable? I know I can use a list to linke the symboltable together, but I don't know how to tackle this issue.

1

There are 1 best solutions below

0
Michael Dyck On

if they travelled the tree twice, how did it save the symboltable to support that when travelling second time, the node can find the symboltable?

It sounds like you're thinking of one complete pass over the AST, followed by another complete pass over the AST. Instead, consider partial passes over portions of the AST. E.g., when you encounter a scope-defining construct, you can do a quick pass over just that construct to get the symbols defined in it, followed by another pass over that construct to check whether references are valid.