11from syntree import *
22from symtable import *
33
4+ class LabelFactory : # this is a suffix to add to all function names
5+ counter = 0 # in particular, it is useful for function overloading
6+ @staticmethod # it is also useful for different goto labels (loops, conditional statements etc) in assembly code
7+ def new_label ():
8+ LabelFactory .counter += 1
9+ return "uniqstr%d" % LabelFactory .counter
10+
411def build_symtable (ast ):
512 if not isinstance (ast , Function ) or ast .name != 'main' or ast .deco ['type' ] != Type .VOID or len (ast .args )> 0 :
613 raise Exception ('Cannot find a valid entry point' )
714 symtable = SymbolTable ()
815 symtable .add_fun (ast .name , [], ast .deco )
16+ ast .deco ['label' ] = ast .name + '_' + LabelFactory .new_label () # unique label
917 process_scope (ast , symtable )
1018
1119def process_scope (fun , symtable ):
@@ -17,6 +25,7 @@ def process_scope(fun, symtable):
1725 symtable .add_var (* v )
1826 for f in fun .fun : # process nested functions: first add function symbols to the table
1927 symtable .add_fun (f .name , [d ['type' ] for v ,d in f .args ], f .deco )
28+ f .deco ['label' ] = f .name + '_' + LabelFactory .new_label () # still need unique labels
2029 for f in fun .fun : # then process nested function bodies
2130 process_scope (f , symtable )
2231 for s in fun .body : # process the list of statements
@@ -82,6 +91,7 @@ def process_expr(n, symtable): # process "expression" syntax tree nodes
8291 for s in n .args :
8392 process_expr (s , symtable )
8493 deco = symtable .find_fun (n .name , [a .deco ['type' ] for a in n .args ])
94+ n .deco ['fundeco' ] = deco # save the function symbol, useful for overloading and for stack preparation
8595 n .deco ['type' ] = deco ['type' ]
8696 elif isinstance (n , String ): # no type checking is necessary
8797 n .deco ['type' ] = Type .STRING
0 commit comments