Question

I'd like to build my own compiler for tiny C language: I've already make my grammar, build an AST (abstract syntax tree) using ANTLR, and implement my symbol table (following GRosemberg code)

I have to fill my symbol table with my symbols, but I don't really know how..

  • Do I have to run through y AST and depending on which token I find I put an new symbol in my symbol table or create a new Scope...?
  • Do I have to use semantic functions in my grammar, I've heard of a tree Walker...?

I'm a little bit lost for this step, is anyone has an example, or can tell me how to do please?

Was it helpful?

Solution

For ANTLR 3 & 2 you could easily do it in your parser actions. You do have to push and pop scopes when you cross scope boundaries and add entries where appropriate. You can see how to do it in a real C parser at http://www.antlr3.org/grammar/cgram/grammars/StdCParser.g. It's possible to do it in a tree parser too, if you prefer.

In ANTLR 4 you would instead be writing a listener that does the push/pop and adds entries. If your grammar supported typedefs like C does you would need to handle it in the grammar actions because the symbol table affects the parse. Tiny C shouldn't need to do that though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top