1515rt .init ()
1616
1717class Context (object ):
18- def __init__ (self , name , argc , parent_locals ):
19- locals = parent_locals .copy ()
20- for x in locals :
21- locals [x ] = Closure (locals [x ])
18+ def __init__ (self , name , argc , parent_ctx ):
19+ if parent_ctx is not None :
20+ assert isinstance (parent_ctx , Context )
21+ locals = parent_ctx .locals [- 1 ].copy ()
22+ for x in locals :
23+ locals [x ] = Closure (locals [x ], parent_ctx )
24+ else :
25+ locals = {}
2226
2327 self .bytecode = []
2428 self .consts = []
@@ -75,7 +79,10 @@ def get_local(self, s_name):
7579 if x is local :
7680 break
7781 idx += 1
78- self .closed_overs .append (local .local )
82+ if isinstance (local .local , Closure ):
83+ self .closed_overs .append (local .ctx .get_local (s_name ))
84+ else :
85+ self .closed_overs .append (local .local )
7986
8087 return ClosureCell (idx )
8188 return local
@@ -170,8 +177,9 @@ def emit(self, ctx):
170177 ctx .add_sp (1 )
171178
172179class Closure (LocalType ):
173- def __init__ (self , local ):
180+ def __init__ (self , local , ctx ):
174181 self .local = local
182+ self .ctx = ctx
175183
176184class ClosureCell (LocalType ):
177185 def __init__ (self , idx ):
@@ -300,7 +308,7 @@ def compile_fn(form, ctx):
300308
301309def compile_fn_body (name , args , body , ctx ):
302310 print args
303- new_ctx = Context (name ._str , rt .count (args ).int_val (), ctx . locals [ - 1 ] )
311+ new_ctx = Context (name ._str , rt .count (args ).int_val (), ctx )
304312 add_args (args , new_ctx )
305313 bc = 0
306314
@@ -520,7 +528,7 @@ def compile_cons(form, ctx):
520528
521529
522530def compile (form ):
523- ctx = Context (u"main" , 0 , {} )
531+ ctx = Context (u"main" , 0 , None )
524532 compile_form (form , ctx )
525533 ctx .bytecode .append (code .RETURN )
526534 return ctx .to_code ()
0 commit comments