Commit 20163eb3

20163eb3663cMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 5 files · +3 added · ~2 modified

Description

feat: Fiber captures, Lambda closures, PtrArray, GC safety, benchmarks

Fiber capture (closures):

  • Fiber bodies can now capture outer-scope variables via typed pointer structs
  • Heap-promoted captures (sp_gc_alloc cells) survive scope escape
  • Nested fiber captures share the same heap cells
  • GC scan for Fiber's user_data field

Lambda closure improvements:

  • By-reference semantics via heap cell promotion (matching Ruby)
  • Lambda-in-Fiber typed capture bridging (cell pointer cast to sp_Val*)
  • Multi-statement lambda body compilation
  • Lambda call return type inference (string, bool, float, int)
  • scan_lambda_free_vars: scan RHS before adding writes to locals

Fiber API additions:

  • Fiber.current, Fiber#transfer, Fiber#alive?, FiberError on dead resume
  • Polymorphic value passing (sp_RbVal) for yield/resume
  • Transfer uses swapcontext on prev->ctx for multi-fiber switching

PtrArray (object arrays):

  • sp_PtrArray runtime (void** based, platform-safe)
  • Type inference: detect homogeneous object arrays from push() calls
  • Typed element access with cast: (sp_Planet*)sp_PtrArray_get(arr, i)

Type inference improvements:

  • Nullable object types (obj_Node?) for self-referential classes
  • update_ivar_type: nil + T → T? pattern for instance variables
  • Constructor param nullable inference from multiple call sites
  • detect_poly_params: T and T? treated as compatible (not poly)
  • compile_object_method_expr: base_type() for nullable obj dispatch
  • set_var_type: don't downgrade nullable types to nil

GC safety:

  • expr_may_gc() predicate for identifying GC-allocating expressions
  • compile_gc_safe_args: extract multi-GC args into rooted temp vars
  • Receiver rooting when both receiver and args may trigger GC

Benchmarks (all matching Ruby output):

  • bm_spectral_norm: float array math (34x faster than Ruby)
  • bm_nbody: object array + class methods (105x faster than Ruby)
  • bm_fannkuch: integer array permutations (30x faster than Ruby)

65 tests pass, bootstrap clean (gen2.c == gen3.c).

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
20163eb3663c
Parent
80ca65280a02

spinel_codegen.rbmodifiedView file

@@ -125,6 +125,7 @@
125125 @needs_system = 0
126126 @needs_int_array = 0
127127 @needs_float_array = 0
128+ @needs_ptr_array = 0
128129 @needs_str_array = 0
129130 @needs_str_int_hash = 0
130131 @needs_str_str_hash = 0
@@ -147,11 +148,20 @@
147148 @lambda_funcs = ""
148149 @lambda_params = "".split(",")
149150 @lambda_captures = "".split(",")
151+ @lambda_capture_cell_types = "".split(",")
152+ @lambda_var_ret_names = "".split(",")
153+ @lambda_var_ret_types = "".split(",")
154+ @last_lambda_ret_type = ""
150155
151156 # Fiber support
152157 @needs_fiber = 0
153158 @fiber_counter = 0
154159 @fiber_funcs = ""
160+ @in_fiber_body = 0
161+ @fiber_captures = "".split(",")
162+ @fiber_capture_types = "".split(",")
163+ @heap_promoted_names = "".split(",")
164+ @heap_promoted_cells = "".split(",")
155165
156166 # Poly tracking: functions with params called with different types
157167 @poly_funcs = "".split(",")
@@ -949,6 +959,15 @@
949959 return "int"
950960 end
951961 if t == "LambdaNode"
962+ # Record return type if inside a variable assignment context
963+ lbody = @nd_body[nid]
964+ if lbody >= 0
965+ lbs = get_stmts(lbody)
966+ if lbs.length > 0
967+ lrt = infer_type(lbs.last)
968+ @last_lambda_ret_type = lrt
969+ end
970+ end
952971 return "lambda"
953972 end
954973 "int"
@@ -1049,6 +1068,22 @@
10491068 return r
10501069 end
10511070
1071+ # Lambda call return type
1072+ if mname == "call" || mname == "[]"
1073+ if recv >= 0
1074+ rt = infer_type(recv)
1075+ if rt == "lambda"
1076+ if @nd_type[recv] == "LocalVariableReadNode"
1077+ lrt = lambda_var_ret_type(@nd_name[recv])
1078+ if lrt != ""
1079+ return lrt
1080+ end
1081+ end
1082+ return "int"
1083+ end
1084+ end
1085+ end
1086+
10521087 # Method name-based type inference
10531088 r = infer_method_name_type(nid, mname, recv)
10541089 if r != ""
@@ -1115,21 +1150,49 @@
11151150 end
11161151 end
11171152 end
1118- # fiber.resume returns int
1153+ # fiber.resume returns poly
11191154 if mname == "resume"
11201155 if recv >= 0
1121- rt = infer_type(recv)
1156+ rt = base_type(infer_type(recv))
11221157 if rt == "fiber"
1123- return "int"
1158+ return "poly"
11241159 end
11251160 end
11261161 end
1127- # Fiber.yield returns int
1162+ # Fiber.yield returns poly
11281163 if mname == "yield"
11291164 if recv >= 0
11301165 if @nd_type[recv] == "ConstantReadNode"
11311166 if @nd_name[recv] == "Fiber"
1132- return "int"
1167+ return "poly"
1168+ end
1169+ end
1170+ end
1171+ end
1172+ # fiber.alive? returns bool
1173+ if mname == "alive?"
1174+ if recv >= 0
1175+ rt = base_type(infer_type(recv))
1176+ if rt == "fiber"
1177+ return "bool"
1178+ end
1179+ end
1180+ end
1181+ # fiber.transfer returns poly
1182+ if mname == "transfer"
1183+ if recv >= 0
1184+ rt = base_type(infer_type(recv))
1185+ if rt == "fiber"
1186+ return "poly"
1187+ end
1188+ end
1189+ end
1190+ # Fiber.current returns fiber
1191+ if mname == "current"
1192+ if recv >= 0
1193+ if @nd_type[recv] == "ConstantReadNode"
1194+ if @nd_name[recv] == "Fiber"
1195+ return "fiber"
11331196 end
11341197 end
11351198 end
@@ -1669,6 +1732,9 @@
16691732 if rt == "str_array"
16701733 return "string"
16711734 end
1735+ if is_ptr_array_type(rt) == 1
1736+ return ptr_array_elem_type(rt)
1737+ end
16721738 if rt == "str_int_hash"
16731739 return "int"
16741740 end
@@ -1916,7 +1982,8 @@
19161982 end
19171983 end
19181984 if is_obj_type(rt) == 1
1919- cname = rt[4, rt.length - 4]
1985+ bt_rt = base_type(rt)
1986+ cname = bt_rt[4, bt_rt.length - 4]
19201987 ci = find_class_idx(cname)
19211988 if ci >= 0
19221989 # Check attr_reader
@@ -2041,6 +2108,24 @@
20412108 0
20422109 end
20432110
2111+ # Check if type is a ptr_array (e.g., "obj_Planet_ptr_array")
2112+ def is_ptr_array_type(t)
2113+ if t != nil && t.length > 10
2114+ if t.end_with?("_ptr_array")
2115+ return 1
2116+ end
2117+ end
2118+ 0
2119+ end
2120+
2121+ # Get element class type from ptr_array type (e.g., "obj_Planet_ptr_array" → "obj_Planet")
2122+ def ptr_array_elem_type(t)
2123+ if is_ptr_array_type(t) == 1
2124+ return t[0, t.length - 10]
2125+ end
2126+ ""
2127+ end
2128+
20442129 def type_is_pointer(t)
20452130 if is_nullable_type(t) == 1
20462131 t = base_type(t)
@@ -2051,6 +2136,9 @@
20512136 if t == "float_array"
20522137 return 1
20532138 end
2139+ if is_ptr_array_type(t) == 1
2140+ return 1
2141+ end
20542142 if t == "str_array"
20552143 return 1
20562144 end
@@ -2080,6 +2168,27 @@
20802168 0
20812169 end
20822170
2171+ # Check if evaluating an expression might trigger GC allocation
2172+ def expr_may_gc(nid)
2173+ if nid < 0
2174+ return 0
2175+ end
2176+ t = @nd_type[nid]
2177+ if t == "IntegerNode" || t == "FloatNode" || t == "StringNode"
2178+ return 0
2179+ end
2180+ if t == "SymbolNode" || t == "TrueNode" || t == "FalseNode" || t == "NilNode"
2181+ return 0
2182+ end
2183+ if t == "LocalVariableReadNode" || t == "SelfNode"
2184+ return 0
2185+ end
2186+ if t == "InstanceVariableReadNode" || t == "ConstantReadNode"
2187+ return 0
2188+ end
2189+ 1
2190+ end
2191+
20832192 def is_nullable_type(t)
20842193 if t.length > 1 && t[t.length - 1] == "?"
20852194 return 1
@@ -2109,6 +2218,9 @@
21092218 if bt == "stringio" || bt == "lambda" || bt == "poly_array"
21102219 return 1
21112220 end
2221+ if bt == "fiber"
2222+ return 1
2223+ end
21122224 if is_obj_type(bt) == 1
21132225 return 1
21142226 end
@@ -2161,6 +2273,9 @@
21612273 if t == "float_array"
21622274 return "sp_FloatArray *"
21632275 end
2276+ if is_ptr_array_type(t) == 1
2277+ return "sp_PtrArray *"
2278+ end
21642279 if t == "str_array"
21652280 return "sp_StrArray *"
21662281 end
@@ -2939,14 +3054,25 @@
29393054 while k < names.length
29403055 if names[k] == iname
29413056 if k < types.length
2942- if types[k] == "int"
3057+ old = types[k]
3058+ if old == "int" || old == "nil"
29433059 types[k] = new_type
29443060 @cls_ivar_types[ci] = types.join(";")
3061+ elsif old != new_type && old != "poly"
3062+ # Nullable pattern: nil + T → T?, T + nil → T?
3063+ if new_type == "nil" && is_nullable_pointer_type(old) == 1
3064+ if old[old.length - 1] != "?"
3065+ types[k] = old + "?"
3066+ @cls_ivar_types[ci] = types.join(";")
3067+ end
3068+ elsif old == "nil" && is_nullable_pointer_type(new_type) == 1
3069+ types[k] = new_type + "?"
3070+ @cls_ivar_types[ci] = types.join(";")
3071+ else
3072+ types[k] = "poly"
3073+ @cls_ivar_types[ci] = types.join(";")
3074+ end
29453075 end
2946- if types[k] == "nil"
2947- types[k] = new_type
2948- @cls_ivar_types[ci] = types.join(";")
2949- end
29503076 end
29513077 return
29523078 end
@@ -3643,10 +3769,21 @@
36433769 else
36443770 at = infer_type(arg_ids[k])
36453771 if k < ptypes.length
3646- if ptypes[k] == "int"
3772+ old_pt = ptypes[k]
3773+ if old_pt == "int"
36473774 if at != "int"
36483775 ptypes[k] = at
36493776 end
3777+ elsif old_pt == "nil" && at != "nil" && at != "int"
3778+ if is_nullable_pointer_type(at) == 1
3779+ ptypes[k] = at + "?"
3780+ else
3781+ ptypes[k] = at
3782+ end
3783+ elsif at == "nil" && old_pt != "nil" && is_nullable_pointer_type(old_pt) == 1
3784+ if old_pt[old_pt.length - 1] != "?"
3785+ ptypes[k] = old_pt + "?"
3786+ end
36503787 end
36513788 end
36523789 end
@@ -4187,6 +4324,16 @@
41874324 if nid < 0
41884325 return
41894326 end
4327+ # Direct ivar write: @left = expr (inside class methods)
4328+ if @nd_type[nid] == "InstanceVariableWriteNode"
4329+ if @current_class_idx >= 0
4330+ iname = @nd_name[nid]
4331+ at = infer_type(@nd_expression[nid])
4332+ if at != "int" && at != "nil"
4333+ update_ivar_type(@current_class_idx, iname, at)
4334+ end
4335+ end
4336+ end
41904337 if @nd_type[nid] == "CallNode"
41914338 mname = @nd_name[nid]
41924339 recv = @nd_receiver[nid]
@@ -4209,10 +4356,8 @@
42094356 arg_ids = get_args(args_id)
42104357 if arg_ids.length > 0
42114358 at = infer_type(arg_ids[0])
4212- if at != "int"
4213- if at != "nil"
4214- update_ivar_type(ci, iname, at)
4215- end
4359+ if at != "int" && at != "nil"
4360+ update_ivar_type(ci, iname, at)
42164361 end
42174362 end
42184363 end
@@ -5387,6 +5532,15 @@
53875532 end
53885533 end
53895534 end
5535+ if mname == "current"
5536+ if @nd_receiver[nid] >= 0
5537+ if @nd_type[@nd_receiver[nid]] == "ConstantReadNode"
5538+ if @nd_name[@nd_receiver[nid]] == "Fiber"
5539+ @needs_fiber = 1
5540+ end
5541+ end
5542+ end
5543+ end
53905544 if mname == "catch"
53915545 @needs_setjmp = 1
53925546 end
@@ -5600,9 +5754,19 @@
56005754 end
56015755 # otherwise arg is int variable, param already has a type - keep it
56025756 else
5603- # Genuinely different types - mark poly
5604- ptypes[k] = "poly"
5605- @needs_rb_value = 1
5757+ # Check nullable compatibility: T and T? are compatible
5758+ if base_type(ct) == base_type(at)
5759+ # Same base type — use nullable version
5760+ if is_nullable_type(at) == 1
5761+ ptypes[k] = at
5762+ elsif is_nullable_type(ct) == 0 && is_nullable_pointer_type(ct) == 1
5763+ ptypes[k] = ct + "?"
5764+ end
5765+ else
5766+ # Genuinely different types - mark poly
5767+ ptypes[k] = "poly"
5768+ @needs_rb_value = 1
5769+ end
56065770 end
56075771 end
56085772 end
@@ -6059,6 +6223,13 @@
60596223 end
60606224 emit_float_array_runtime
60616225 end
6226+ if @needs_ptr_array == 1
6227+ if @needs_gc == 0
6228+ @needs_gc = 1
6229+ emit_gc_runtime
6230+ end
6231+ emit_ptr_array_runtime
6232+ end
60626233 if @needs_str_array == 1
60636234 emit_str_array_runtime
60646235 end
@@ -6141,6 +6312,26 @@
61416312 @needs_gc = 1
61426313 emit_gc_runtime
61436314 end
6315+ if @needs_setjmp == 0
6316+ @needs_setjmp = 1
6317+ emit_setjmp_runtime
6318+ end
6319+ if @needs_rb_value == 0
6320+ @needs_rb_value = 1
6321+ if @needs_string_helpers == 0
6322+ @needs_string_helpers = 1
6323+ if @needs_int_array == 0
6324+ @needs_int_array = 1
6325+ emit_int_array_runtime
6326+ end
6327+ if @needs_str_array == 0
6328+ @needs_str_array = 1
6329+ emit_str_array_runtime
6330+ end
6331+ emit_string_helpers
6332+ end
6333+ emit_rb_value_runtime
6334+ end
61446335 emit_fiber_runtime
61456336 end
61466337 emit_class_structs
@@ -6248,6 +6439,19 @@
62486439 emit_raw("")
62496440 end
62506441
6442+ def emit_ptr_array_runtime
6443+ emit_raw("/* ---- PtrArray: array of void* pointers ---- */")
6444+ emit_raw("typedef struct{void**data;mrb_int len;mrb_int cap;}sp_PtrArray;")
6445+ emit_raw("static void sp_PtrArray_fin(void*p){free(((sp_PtrArray*)p)->data);}")
6446+ emit_raw("static sp_PtrArray*sp_PtrArray_new(void){sp_PtrArray*a=(sp_PtrArray*)sp_gc_alloc(sizeof(sp_PtrArray),sp_PtrArray_fin,NULL);a->cap=16;a->data=(void**)malloc(sizeof(void*)*a->cap);a->len=0;return a;}")
6447+ emit_raw("static inline void sp_PtrArray_push(sp_PtrArray*a,void*v){if(a->len>=a->cap){a->cap=a->cap*2+1;a->data=(void**)realloc(a->data,sizeof(void*)*a->cap);}a->data[a->len++]=v;}")
6448+ emit_raw("static inline void*sp_PtrArray_get(sp_PtrArray*a,mrb_int i){if(i<0)i+=a->len;return a->data[i];}")
6449+ emit_raw("static inline void sp_PtrArray_set(sp_PtrArray*a,mrb_int i,void*v){if(i<0)i+=a->len;a->data[i]=v;}")
6450+ emit_raw("static inline mrb_int sp_PtrArray_length(sp_PtrArray*a){return a->len;}")
6451+ emit_raw("static inline mrb_bool sp_PtrArray_empty(sp_PtrArray*a){return a->len==0;}")
6452+ emit_raw("")
6453+ end
6454+
62516455 def emit_float_array_runtime
62526456 emit_raw("typedef struct{mrb_float*data;mrb_int len;mrb_int cap;}sp_FloatArray;")
62536457 emit_raw("static void sp_FloatArray_fin(void*p){free(((sp_FloatArray*)p)->data);}")
@@ -6593,18 +6797,22 @@
65936797 emit_raw("#include <ucontext.h>")
65946798 emit_raw("#include <sys/mman.h>")
65956799 emit_raw("#define SP_FIBER_STACK_SIZE (64*1024)")
6596- emit_raw("typedef struct sp_Fiber{ucontext_t ctx;ucontext_t caller_ctx;char*stack;int state;mrb_int yielded_value;mrb_int resumed_value;void(*body)(struct sp_Fiber*);int saved_exc_top;int saved_catch_top;}sp_Fiber;")
6597- emit_raw("static sp_Fiber*sp_fiber_current=NULL;")
6800+ emit_raw("typedef struct sp_Fiber{ucontext_t ctx;ucontext_t caller_ctx;char*stack;int state;int transferred;sp_RbVal yielded_value;sp_RbVal resumed_value;void(*body)(struct sp_Fiber*);void*user_data;int saved_exc_top;int saved_catch_top;}sp_Fiber;")
6801+ emit_raw("static sp_Fiber sp_fiber_root;")
6802+ emit_raw("static sp_Fiber*sp_fiber_current=&sp_fiber_root;")
65986803 emit_raw("static void sp_Fiber_fin(void*p){sp_Fiber*f=(sp_Fiber*)p;if(f->stack)munmap(f->stack,SP_FIBER_STACK_SIZE);}")
6599- emit_raw("static sp_Fiber*sp_Fiber_new(void(*body)(sp_Fiber*)){sp_Fiber*f=(sp_Fiber*)sp_gc_alloc(sizeof(sp_Fiber),sp_Fiber_fin,NULL);f->stack=(char*)mmap(NULL,SP_FIBER_STACK_SIZE,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0);f->state=0;f->body=body;f->yielded_value=0;f->resumed_value=0;f->saved_exc_top=0;f->saved_catch_top=0;return f;}")
6600- emit_raw("static void sp_fiber_trampoline(void){sp_Fiber*f=sp_fiber_current;f->body(f);f->state=3;f->yielded_value=f->yielded_value;swapcontext(&f->ctx,&f->caller_ctx);}")
6601- emit_raw("static mrb_int sp_Fiber_resume(sp_Fiber*f,mrb_int val){if(f->state==3){fputs(\"dead fiber called\",stderr);exit(1);}f->resumed_value=val;sp_Fiber*prev=sp_fiber_current;sp_fiber_current=f;if(f->state==0){f->state=1;getcontext(&f->ctx);f->ctx.uc_stack.ss_sp=f->stack;f->ctx.uc_stack.ss_size=SP_FIBER_STACK_SIZE;f->ctx.uc_link=&f->caller_ctx;makecontext(&f->ctx,(void(*)(void))sp_fiber_trampoline,0);swapcontext(&f->caller_ctx,&f->ctx);}else{f->state=1;swapcontext(&f->caller_ctx,&f->ctx);}sp_fiber_current=prev;return f->yielded_value;}")
6602- emit_raw("static mrb_int sp_Fiber_yield(mrb_int val){sp_Fiber*f=sp_fiber_current;f->yielded_value=val;f->state=2;swapcontext(&f->ctx,&f->caller_ctx);return f->resumed_value;}")
6603- emit_raw("")
6604- end
6605-
6606- def emit_stringio_runtime
6607- emit_raw("/* ---- StringIO runtime ---- */")
6804+ emit_raw("static void sp_Fiber_scan(void*p){sp_Fiber*f=(sp_Fiber*)p;if(f->user_data)sp_gc_mark(f->user_data);}")
6805+ emit_raw("static sp_Fiber*sp_Fiber_new(void(*body)(sp_Fiber*)){sp_Fiber*f=(sp_Fiber*)sp_gc_alloc(sizeof(sp_Fiber),sp_Fiber_fin,sp_Fiber_scan);f->stack=(char*)mmap(NULL,SP_FIBER_STACK_SIZE,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0);f->state=0;f->transferred=0;f->body=body;f->yielded_value=sp_box_nil();f->resumed_value=sp_box_nil();f->user_data=NULL;f->saved_exc_top=0;f->saved_catch_top=0;return f;}")
6806+ emit_raw("static void sp_fiber_trampoline(void){sp_Fiber*f=sp_fiber_current;f->body(f);f->state=3;if(f->transferred){sp_fiber_current=&sp_fiber_root;setcontext(&sp_fiber_root.ctx);}else{swapcontext(&f->ctx,&f->caller_ctx);}}")
6807+ emit_raw("static sp_RbVal sp_Fiber_resume(sp_Fiber*f,sp_RbVal val){if(f->state==3){sp_raise_cls(\"FiberError\",\"attempt to resume a terminated fiber\");}f->resumed_value=val;sp_Fiber*prev=sp_fiber_current;sp_fiber_current=f;if(f->state==0){f->state=1;getcontext(&f->ctx);f->ctx.uc_stack.ss_sp=f->stack;f->ctx.uc_stack.ss_size=SP_FIBER_STACK_SIZE;f->ctx.uc_link=&f->caller_ctx;makecontext(&f->ctx,(void(*)(void))sp_fiber_trampoline,0);swapcontext(&f->caller_ctx,&f->ctx);}else{f->state=1;swapcontext(&f->caller_ctx,&f->ctx);}sp_fiber_current=prev;return f->yielded_value;}")
6808+ emit_raw("static sp_RbVal sp_Fiber_yield(sp_RbVal val){sp_Fiber*f=sp_fiber_current;f->yielded_value=val;f->state=2;swapcontext(&f->ctx,&f->caller_ctx);return f->resumed_value;}")
6809+ emit_raw("static mrb_bool sp_Fiber_alive(sp_Fiber*f){return f->state!=3;}")
6810+ emit_raw("static sp_RbVal sp_Fiber_transfer(sp_Fiber*f,sp_RbVal val){f->resumed_value=val;sp_Fiber*prev=sp_fiber_current;sp_fiber_current=f;if(f->state==0){f->state=1;f->transferred=1;getcontext(&f->ctx);f->ctx.uc_stack.ss_sp=f->stack;f->ctx.uc_stack.ss_size=SP_FIBER_STACK_SIZE;f->ctx.uc_link=&prev->ctx;makecontext(&f->ctx,(void(*)(void))sp_fiber_trampoline,0);swapcontext(&prev->ctx,&f->ctx);}else{f->state=1;swapcontext(&prev->ctx,&f->ctx);}sp_fiber_current=prev;return prev->resumed_value;}")
6811+ emit_raw("")
6812+ end
6813+
6814+ def emit_stringio_runtime
6815+ emit_raw("/* ---- StringIO runtime ---- */")
66086816 emit_raw("typedef struct { char *buf; int64_t len; int64_t cap; int64_t pos; int64_t lineno; int closed; } sp_StringIO;")
66096817 emit_raw("static void sio_grow(sp_StringIO *sio, int64_t need) { int64_t req = sio->pos + need; if (req <= sio->cap) return; int64_t nc = sio->cap ? sio->cap : 64; while (nc < req) nc *= 2; sio->buf = (char *)realloc(sio->buf, nc + 1); sio->cap = nc; }")
66106818 emit_raw("static int64_t sio_write(sp_StringIO *sio, const char *d, int64_t dl) { sio_grow(sio, dl); if (sio->pos > sio->len) memset(sio->buf + sio->len, 0, sio->pos - sio->len); memcpy(sio->buf + sio->pos, d, dl); sio->pos += dl; if (sio->pos > sio->len) sio->len = sio->pos; sio->buf[sio->len] = '" + bsl + "0'; return dl; }")
@@ -8314,6 +8522,36 @@
83148522 end
83158523 end
83168524 end
8525+ # Detect object array push: arr.push(ClassName.new(...))
8526+ if @nd_type[nid] == "CallNode"
8527+ if @nd_name[nid] == "push"
8528+ recv = @nd_receiver[nid]
8529+ if recv >= 0 && @nd_type[recv] == "LocalVariableReadNode"
8530+ arr_name = @nd_name[recv]
8531+ args_id = @nd_arguments[nid]
8532+ if args_id >= 0
8533+ aargs = get_args(args_id)
8534+ if aargs.length > 0
8535+ arg_type = infer_type(aargs[0])
8536+ if is_obj_type(arg_type) == 1
8537+ target_type = arg_type + "_ptr_array"
8538+ @needs_ptr_array = 1
8539+ @needs_gc = 1
8540+ ki = 0
8541+ while ki < names.length
8542+ if names[ki] == arr_name
8543+ if types[ki] == "int_array"
8544+ types[ki] = target_type
8545+ end
8546+ end
8547+ ki = ki + 1
8548+ end
8549+ end
8550+ end
8551+ end
8552+ end
8553+ end
8554+ end
83178555 if @nd_type[nid] == "ForNode"
83188556 tgt = @nd_target[nid]
83198557 if tgt >= 0
@@ -8670,6 +8908,9 @@
86708908
86718909 emit_raw("")
86728910
8911+ # Pre-scan: map lambda variable names to their return types
8912+ scan_lambda_ret_types(stmts)
8913+
86738914 # Compile main statements
86748915 stmts.each { |sid|
86758916 if @nd_type[sid] != "DefNode"
@@ -8745,7 +8986,7 @@
87458986 return "self"
87468987 end
87478988 if t == "LocalVariableReadNode"
8748- return "lv_" + @nd_name[nid]
8989+ return fiber_var_ref(@nd_name[nid])
87498990 end
87508991 if t == "InstanceVariableReadNode"
87518992 # Check if we're in a module class method
@@ -9223,6 +9464,164 @@
92239464 end
92249465
92259466
9467+ # --- Fiber capture helpers ---
9468+
9469+ def fiber_capture_index(name)
9470+ i = 0
9471+ while i < @fiber_captures.length
9472+ if @fiber_captures[i] == name
9473+ return i
9474+ end
9475+ i = i + 1
9476+ end
9477+ -1
9478+ end
9479+
9480+ def heap_promoted_cell(name)
9481+ i = 0
9482+ while i < @heap_promoted_names.length
9483+ if @heap_promoted_names[i] == name
9484+ return @heap_promoted_cells[i]
9485+ end
9486+ i = i + 1
9487+ end
9488+ ""
9489+ end
9490+
9491+ def fiber_var_ref(name)
9492+ if @in_fiber_body == 1
9493+ if fiber_capture_index(name) >= 0
9494+ return "(*_cap->" + name + ")"
9495+ end
9496+ end
9497+ cell = heap_promoted_cell(name)
9498+ if cell != ""
9499+ return "(*" + cell + ")"
9500+ end
9501+ "lv_" + name
9502+ end
9503+
9504+
9505+ def scan_fiber_free_vars(nid, params, locals, free_vars, free_var_types)
9506+ if nid < 0
9507+ return
9508+ end
9509+ t = @nd_type[nid]
9510+ if t == "LocalVariableReadNode" || t == "LocalVariableTargetNode"
9511+ vn = @nd_name[nid]
9512+ if not_in(vn, params) == 1 && not_in(vn, locals) == 1 && not_in(vn, free_vars) == 1
9513+ vt = find_var_type(vn)
9514+ if vt != ""
9515+ free_vars.push(vn)
9516+ free_var_types.push(vt)
9517+ end
9518+ end
9519+ return
9520+ end
9521+ if t == "LocalVariableWriteNode"
9522+ vn = @nd_name[nid]
9523+ if not_in(vn, params) == 1 && not_in(vn, locals) == 1 && not_in(vn, free_vars) == 1
9524+ vt = find_var_type(vn)
9525+ if vt != ""
9526+ free_vars.push(vn)
9527+ free_var_types.push(vt)
9528+ end
9529+ end
9530+ # Also scan the expression
9531+ scan_fiber_free_vars(@nd_expression[nid], params, locals, free_vars, free_var_types)
9532+ return
9533+ end
9534+ if t == "LocalVariableOperatorWriteNode"
9535+ vn = @nd_name[nid]
9536+ if not_in(vn, params) == 1 && not_in(vn, locals) == 1 && not_in(vn, free_vars) == 1
9537+ vt = find_var_type(vn)
9538+ if vt != ""
9539+ free_vars.push(vn)
9540+ free_var_types.push(vt)
9541+ end
9542+ end
9543+ scan_fiber_free_vars(@nd_expression[nid], params, locals, free_vars, free_var_types)
9544+ return
9545+ end
9546+ # Stop at nested lambda/fiber boundaries (they handle their own captures)
9547+ if t == "LambdaNode"
9548+ return
9549+ end
9550+ if t == "CallNode"
9551+ # Stop at nested Fiber.new block bodies
9552+ mn = @nd_name[nid]
9553+ if mn == "new"
9554+ rv = @nd_receiver[nid]
9555+ if rv >= 0 && @nd_type[rv] == "ConstantReadNode" && @nd_name[rv] == "Fiber"
9556+ return
9557+ end
9558+ end
9559+ end
9560+ # Recurse into children (follow scan_locals_children pattern)
9561+ if @nd_body[nid] >= 0
9562+ scan_fiber_free_vars(@nd_body[nid], params, locals, free_vars, free_var_types)
9563+ end
9564+ if @nd_receiver[nid] >= 0
9565+ scan_fiber_free_vars(@nd_receiver[nid], params, locals, free_vars, free_var_types)
9566+ end
9567+ if @nd_expression[nid] >= 0
9568+ scan_fiber_free_vars(@nd_expression[nid], params, locals, free_vars, free_var_types)
9569+ end
9570+ if @nd_predicate[nid] >= 0
9571+ scan_fiber_free_vars(@nd_predicate[nid], params, locals, free_vars, free_var_types)
9572+ end
9573+ if @nd_subsequent[nid] >= 0
9574+ scan_fiber_free_vars(@nd_subsequent[nid], params, locals, free_vars, free_var_types)
9575+ end
9576+ if @nd_else_clause[nid] >= 0
9577+ scan_fiber_free_vars(@nd_else_clause[nid], params, locals, free_vars, free_var_types)
9578+ end
9579+ if @nd_arguments[nid] >= 0
9580+ scan_fiber_free_vars(@nd_arguments[nid], params, locals, free_vars, free_var_types)
9581+ end
9582+ if @nd_rescue_clause[nid] >= 0
9583+ scan_fiber_free_vars(@nd_rescue_clause[nid], params, locals, free_vars, free_var_types)
9584+ end
9585+ if @nd_ensure_clause[nid] >= 0
9586+ scan_fiber_free_vars(@nd_ensure_clause[nid], params, locals, free_vars, free_var_types)
9587+ end
9588+ # Stmts list
9589+ stmts_list = parse_id_list(@nd_stmts[nid])
9590+ k = 0
9591+ while k < stmts_list.length
9592+ scan_fiber_free_vars(stmts_list[k], params, locals, free_vars, free_var_types)
9593+ k = k + 1
9594+ end
9595+ # Args list
9596+ args_list = parse_id_list(@nd_args[nid])
9597+ k = 0
9598+ while k < args_list.length
9599+ scan_fiber_free_vars(args_list[k], params, locals, free_vars, free_var_types)
9600+ k = k + 1
9601+ end
9602+ # Conditions list
9603+ conds_list = parse_id_list(@nd_conditions[nid])
9604+ k = 0
9605+ while k < conds_list.length
9606+ scan_fiber_free_vars(conds_list[k], params, locals, free_vars, free_var_types)
9607+ k = k + 1
9608+ end
9609+ # Elements list
9610+ elems_list = parse_id_list(@nd_elements[nid])
9611+ k = 0
9612+ while k < elems_list.length
9613+ scan_fiber_free_vars(elems_list[k], params, locals, free_vars, free_var_types)
9614+ k = k + 1
9615+ end
9616+ # Block body (for non-Fiber.new blocks)
9617+ blk = @nd_block[nid]
9618+ if blk >= 0
9619+ if @nd_body[blk] >= 0
9620+ scan_fiber_free_vars(@nd_body[blk], params, locals, free_vars, free_var_types)
9621+ end
9622+ end
9623+ end
9624+
92269625 def compile_fiber_new(nid)
92279626 @needs_fiber = 1
92289627 blk = @nd_block[nid]
@@ -9249,68 +9648,194 @@
92499648 end
92509649 end
92519650 end
9252- fid = @fiber_counter
9253- @fiber_counter = @fiber_counter + 1
9254- fname = "_fiber_body_" + fid.to_s
92559651
9256- # Compile fiber body function
9257- fbody = "static void " + fname + "(sp_Fiber *_fb) {" + 10.chr
9652+ body = @nd_body[blk]
9653+ # Scan all variables referenced in the body
9654+ all_names = "".split(",")
9655+ all_types = "".split(",")
9656+ all_plist = "".split(",")
92589657 if bp != ""
9259- fbody = fbody + " mrb_int lv_" + bp + " = _fb->resumed_value;" + 10.chr
9260- end
9261- # Compile body — save/restore compiler state
9262- saved_out = @out
9263- saved_indent = @indent
9264- @out = ""
9265- @indent = 1
9266-
9267- push_scope
9268- if bp != ""
9269- declare_var(bp, "int")
9658+ all_plist.push(bp)
92709659 end
9271- body = @nd_body[blk]
92729660 if body >= 0
9273- # Declare locals in fiber body
9274- lnames = "".split(",")
9275- ltypes = "".split(",")
9276- plist = "".split(",")
9277- if bp != ""
9278- plist.push(bp)
9279- end
9280- scan_locals(body, lnames, ltypes, plist)
9281- lk = 0
9282- while lk < lnames.length
9283- declare_var(lnames[lk], ltypes[lk])
9284- emit(" " + c_type(ltypes[lk]) + " lv_" + lnames[lk] + " = " + c_default_val(ltypes[lk]) + ";")
9285- lk = lk + 1
9286- end
9287-
9288- stmts = get_stmts(body)
9289- if stmts.length > 0
9290- i = 0
9291- while i < stmts.length - 1
9292- compile_stmt(stmts[i])
9293- i = i + 1
9294- end
9295- last = stmts.last
9296- last_val = compile_expr(last)
9297- emit(" _fb->yielded_value = (mrb_int)" + last_val + ";")
9298- end
9661+ scan_locals(body, all_names, all_types, all_plist)
92999662 end
9300- pop_scope
93019663
9664+ # Split into captures (exist in outer scope) vs true locals
9665+ free_vars = "".split(",")
9666+ free_var_types = "".split(",")
9667+ local_names = "".split(",")
9668+ local_types = "".split(",")
9669+ k = 0
9670+ while k < all_names.length
9671+ outer_type = find_var_type(all_names[k])
9672+ if outer_type != ""
9673+ # Variable exists in outer scope → capture
9674+ free_vars.push(all_names[k])
9675+ free_var_types.push(outer_type)
9676+ else
9677+ # True local variable
9678+ local_names.push(all_names[k])
9679+ local_types.push(all_types[k])
9680+ end
9681+ k = k + 1
9682+ end
9683+
9684+ # Also scan for read-only captures (variables read but not written in body)
9685+ if body >= 0
9686+ scan_fiber_free_vars(body, all_plist, all_names, free_vars, free_var_types)
9687+ end
9688+
9689+ fid = @fiber_counter
9690+ @fiber_counter = @fiber_counter + 1
9691+ fname = "_fiber_body_" + fid.to_s
9692+ cap_name = "_fiber_cap_" + fid.to_s
9693+
9694+ # Build capture struct typedef if needed
9695+ cap_typedef = ""
9696+ if free_vars.length > 0
9697+ cap_typedef = "typedef struct {"
9698+ k = 0
9699+ while k < free_vars.length
9700+ cap_typedef = cap_typedef + " " + c_type(free_var_types[k]) + " *" + free_vars[k] + ";"
9701+ k = k + 1
9702+ end
9703+ cap_typedef = cap_typedef + " } " + cap_name + ";" + 10.chr
9704+ end
9705+
9706+ # Compile fiber body function
9707+ fbody = "static void " + fname + "(sp_Fiber *_fb) {" + 10.chr
9708+ if free_vars.length > 0
9709+ fbody = fbody + " " + cap_name + " *_cap = (" + cap_name + "*)_fb->user_data;" + 10.chr
9710+ end
9711+ if bp != ""
9712+ fbody = fbody + " sp_RbVal lv_" + bp + " = _fb->resumed_value;" + 10.chr
9713+ end
9714+
9715+ # Save/restore compiler state
9716+ saved_out = @out
9717+ saved_indent = @indent
9718+ saved_in_fiber_body = @in_fiber_body
9719+ saved_fiber_captures = @fiber_captures
9720+ saved_fiber_capture_types = @fiber_capture_types
9721+ saved_hp_names_len = @heap_promoted_names.length
9722+ saved_hp_cells_len = @heap_promoted_cells.length
9723+ @out = ""
9724+ @indent = 1
9725+ @in_fiber_body = 1
9726+ @fiber_captures = free_vars
9727+ @fiber_capture_types = free_var_types
9728+
9729+ push_scope
9730+ if bp != ""
9731+ declare_var(bp, "poly")
9732+ end
9733+ if body >= 0
9734+ # Declare only true locals (not captured vars)
9735+ lk = 0
9736+ while lk < local_names.length
9737+ declare_var(local_names[lk], local_types[lk])
9738+ emit(" " + c_type(local_types[lk]) + " lv_" + local_names[lk] + " = " + c_default_val(local_types[lk]) + ";")
9739+ lk = lk + 1
9740+ end
9741+
9742+ stmts = get_stmts(body)
9743+ if stmts.length > 0
9744+ i = 0
9745+ while i < stmts.length - 1
9746+ compile_stmt(stmts[i])
9747+ i = i + 1
9748+ end
9749+ last = stmts.last
9750+ # Compile last as statement for side effects, then capture value
9751+ last_type = infer_type(last)
9752+ if @nd_type[last] == "LocalVariableWriteNode" || @nd_type[last] == "LocalVariableOperatorWriteNode"
9753+ compile_stmt(last)
9754+ last_val = compile_expr(last)
9755+ else
9756+ last_val = compile_expr(last)
9757+ end
9758+ emit(" _fb->yielded_value = " + box_val_to_poly(last_val, last_type) + ";")
9759+ end
9760+ end
9761+ pop_scope
9762+
93029763 fbody = fbody + @out
93039764 fbody = fbody + "}" + 10.chr
9304- @fiber_funcs = @fiber_funcs + fbody
9765+ @fiber_funcs = @fiber_funcs + cap_typedef + fbody
93059766
93069767 @out = saved_out
93079768 @indent = saved_indent
9769+ @in_fiber_body = saved_in_fiber_body
9770+ @fiber_captures = saved_fiber_captures
9771+ @fiber_capture_types = saved_fiber_capture_types
9772+ # Restore heap promoted lists to saved length
9773+ while @heap_promoted_names.length > saved_hp_names_len
9774+ @heap_promoted_names.pop
9775+ end
9776+ while @heap_promoted_cells.length > saved_hp_cells_len
9777+ @heap_promoted_cells.pop
9778+ end
9779+
9780+ # If no captures, return simple expression
9781+ if free_vars.length == 0
9782+ return "sp_Fiber_new(" + fname + ")"
9783+ end
93089784
9309- # Declare locals in body (scan for LocalVariableWriteNode)
9310- # Actually the above compile already handles this via the saved @out
9785+ # Heap-promote captured variables (allocate cells if not already promoted)
9786+ k = 0
9787+ while k < free_vars.length
9788+ vn = free_vars[k]
9789+ already_promoted = 0
9790+ # Check outer scope heap promotions
9791+ ci = 0
9792+ while ci < @heap_promoted_names.length
9793+ if @heap_promoted_names[ci] == vn
9794+ already_promoted = 1
9795+ end
9796+ ci = ci + 1
9797+ end
9798+ # Check if variable is already a heap pointer from enclosing fiber capture
9799+ if already_promoted == 0 && @in_fiber_body == 1 && fiber_capture_index(vn) >= 0
9800+ # Reuse the enclosing fiber's capture pointer (_cap->vn is already a heap cell)
9801+ cell = "_cap->" + vn
9802+ @heap_promoted_names.push(vn)
9803+ @heap_promoted_cells.push(cell)
9804+ already_promoted = 1
9805+ end
9806+ if already_promoted == 0
9807+ cell = "_hcell_" + vn + "_" + fid.to_s
9808+ ct = c_type(free_var_types[k])
9809+ emit(" " + ct + " *" + cell + " = (" + ct + "*)sp_gc_alloc(sizeof(" + ct + "), NULL, NULL);")
9810+ emit(" *" + cell + " = " + fiber_var_ref(vn) + ";")
9811+ @heap_promoted_names.push(vn)
9812+ @heap_promoted_cells.push(cell)
9813+ end
9814+ k = k + 1
9815+ end
93119816
9312- # Return fiber creation expression
9313- "sp_Fiber_new(" + fname + ")"
9817+ # Heap-allocate capture struct
9818+ tmp_fb = "_tmpfb_" + fid.to_s
9819+ cap_ptr = "_cap_ptr_" + fid.to_s
9820+ emit(" " + cap_name + " *" + cap_ptr + " = (" + cap_name + "*)sp_gc_alloc(sizeof(" + cap_name + "), NULL, NULL);")
9821+ k = 0
9822+ while k < free_vars.length
9823+ vn = free_vars[k]
9824+ # Find the cell for this variable
9825+ ci = 0
9826+ cell = ""
9827+ while ci < @heap_promoted_names.length
9828+ if @heap_promoted_names[ci] == vn
9829+ cell = @heap_promoted_cells[ci]
9830+ end
9831+ ci = ci + 1
9832+ end
9833+ emit(" " + cap_ptr + "->" + vn + " = " + cell + ";")
9834+ k = k + 1
9835+ end
9836+ emit(" sp_Fiber *" + tmp_fb + " = sp_Fiber_new(" + fname + ");")
9837+ emit(" " + tmp_fb + "->user_data = " + cap_ptr + ";")
9838+ tmp_fb
93149839 end
93159840
93169841 def compile_call_expr(nid)
@@ -9327,18 +9852,62 @@
93279852 end
93289853 # fiber.resume(val)
93299854 if mname == "resume" && recv >= 0
9330- rt2 = infer_type(recv)
9855+ rt2 = base_type(infer_type(recv))
93319856 if rt2 == "fiber"
93329857 rc = compile_expr(recv)
9333- val = compile_arg0(nid)
9334- return "sp_Fiber_resume(" + rc + ", " + val + ")"
9858+ args_id = @nd_arguments[nid]
9859+ if args_id >= 0
9860+ arg_ids = get_args(args_id)
9861+ if arg_ids.length > 0
9862+ return "sp_Fiber_resume(" + rc + ", " + box_expr_to_poly(arg_ids[0]) + ")"
9863+ end
9864+ end
9865+ return "sp_Fiber_resume(" + rc + ", sp_box_nil())"
93359866 end
93369867 end
93379868 # Fiber.yield(val)
93389869 if mname == "yield" && recv >= 0
93399870 if @nd_type[recv] == "ConstantReadNode"
93409871 if @nd_name[recv] == "Fiber"
9341- return "sp_Fiber_yield(" + compile_arg0(nid) + ")"
9872+ args_id = @nd_arguments[nid]
9873+ if args_id >= 0
9874+ arg_ids = get_args(args_id)
9875+ if arg_ids.length > 0
9876+ return "sp_Fiber_yield(" + box_expr_to_poly(arg_ids[0]) + ")"
9877+ end
9878+ end
9879+ return "sp_Fiber_yield(sp_box_nil())"
9880+ end
9881+ end
9882+ end
9883+ # fiber.alive?
9884+ if mname == "alive?" && recv >= 0
9885+ rt2 = base_type(infer_type(recv))
9886+ if rt2 == "fiber"
9887+ rc = compile_expr(recv)
9888+ return "sp_Fiber_alive(" + rc + ")"
9889+ end
9890+ end
9891+ # fiber.transfer(val)
9892+ if mname == "transfer" && recv >= 0
9893+ rt2 = base_type(infer_type(recv))
9894+ if rt2 == "fiber"
9895+ rc = compile_expr(recv)
9896+ args_id = @nd_arguments[nid]
9897+ if args_id >= 0
9898+ arg_ids = get_args(args_id)
9899+ if arg_ids.length > 0
9900+ return "sp_Fiber_transfer(" + rc + ", " + box_expr_to_poly(arg_ids[0]) + ")"
9901+ end
9902+ end
9903+ return "sp_Fiber_transfer(" + rc + ", sp_box_nil())"
9904+ end
9905+ end
9906+ # Fiber.current
9907+ if mname == "current" && recv >= 0
9908+ if @nd_type[recv] == "ConstantReadNode"
9909+ if @nd_name[recv] == "Fiber"
9910+ return "sp_fiber_current"
93429911 end
93439912 end
93449913 end
@@ -9389,6 +9958,27 @@
93899958
93909959 recv_type = infer_type(recv)
93919960 rc = compile_expr(recv)
9961+ # Root receiver if it may be collected during argument evaluation
9962+ if expr_may_gc(recv) == 1 && type_is_pointer(recv_type) == 1
9963+ args_id = @nd_arguments[nid]
9964+ if args_id >= 0
9965+ aargs = get_args(args_id)
9966+ has_gc_arg = 0
9967+ ak = 0
9968+ while ak < aargs.length
9969+ if expr_may_gc(aargs[ak]) == 1
9970+ has_gc_arg = 1
9971+ end
9972+ ak = ak + 1
9973+ end
9974+ if has_gc_arg == 1
9975+ tmp = new_temp
9976+ emit(" " + c_type(recv_type) + " " + tmp + " = " + rc + ";")
9977+ emit(" SP_GC_ROOT(" + tmp + ");")
9978+ rc = tmp
9979+ end
9980+ end
9981+ end
93929982
93939983 # StringIO methods
93949984 if recv_type == "stringio"
@@ -9765,27 +10355,25 @@
976510355
976610356 def compile_lambda_call_expr(nid, mname, recv)
976710357 rc = compile_expr(recv)
9768- if mname == "[]"
10358+ # Determine return type unboxing
10359+ ret_type = ""
10360+ if @nd_type[recv] == "LocalVariableReadNode"
10361+ ret_type = lambda_var_ret_type(@nd_name[recv])
10362+ end
10363+ if mname == "[]" || mname == "call"
10364+ call_expr = ""
976910365 args_id = @nd_arguments[nid]
977010366 if args_id >= 0
977110367 aargs = get_args(args_id)
977210368 if aargs.length > 0
977310369 ac = wrap_as_sp_val(aargs.first)
9774- return "sp_lam_call(" + rc + ", " + ac + ")"
10370+ call_expr = "sp_lam_call(" + rc + ", " + ac + ")"
977510371 end
977610372 end
9777- return "sp_lam_call(" + rc + ", &sp_lam_nil_val)"
9778- end
9779- if mname == "call"
9780- args_id = @nd_arguments[nid]
9781- if args_id >= 0
9782- aargs = get_args(args_id)
9783- if aargs.length > 0
9784- ac = wrap_as_sp_val(aargs.first)
9785- return "sp_lam_call(" + rc + ", " + ac + ")"
9786- end
10373+ if call_expr == ""
10374+ call_expr = "sp_lam_call(" + rc + ", &sp_lam_nil_val)"
978710375 end
9788- return "sp_lam_call(" + rc + ", &sp_lam_nil_val)"
10376+ return lam_unbox(call_expr, ret_type)
978910377 end
979010378 ""
979110379 end
@@ -10732,6 +11320,22 @@
1073211320 return "sp_FloatArray_length(" + rc + ")"
1073311321 end
1073411322 end
11323+ if is_ptr_array_type(recv_type) == 1
11324+ elem_type = ptr_array_elem_type(recv_type)
11325+ ct = c_type(elem_type)
11326+ if mname == "length" || mname == "size"
11327+ return "sp_PtrArray_length(" + rc + ")"
11328+ end
11329+ if mname == "[]"
11330+ return "(" + ct + ")sp_PtrArray_get(" + rc + ", " + compile_arg0(nid) + ")"
11331+ end
11332+ if mname == "push"
11333+ return "(sp_PtrArray_push(" + rc + ", " + compile_arg0(nid) + "), 0)"
11334+ end
11335+ if mname == "empty?"
11336+ return "sp_PtrArray_empty(" + rc + ")"
11337+ end
11338+ end
1073511339 if recv_type == "str_array"
1073611340 if mname == "length"
1073711341 return "sp_StrArray_length(" + rc + ")"
@@ -11174,7 +11778,8 @@
1117411778 def compile_object_method_expr(nid, mname, rc, recv_type)
1117511779 # Object method calls
1117611780 if is_obj_type(recv_type) == 1
11177- cname = recv_type[4, recv_type.length - 4]
11781+ bt = base_type(recv_type)
11782+ cname = bt[4, bt.length - 4]
1117811783 ci = find_class_idx(cname)
1117911784 if ci >= 0
1118011785 arrow = "->"
@@ -11409,6 +12014,28 @@
1140912014 "sp_box_int(" + val + ")"
1141012015 end
1141112016
12017+ def box_val_to_poly(val, at)
12018+ if at == "poly"
12019+ return val
12020+ end
12021+ if at == "int"
12022+ return "sp_box_int(" + val + ")"
12023+ end
12024+ if at == "string"
12025+ return "sp_box_str(" + val + ")"
12026+ end
12027+ if at == "float"
12028+ return "sp_box_float(" + val + ")"
12029+ end
12030+ if at == "bool"
12031+ return "sp_box_bool(" + val + ")"
12032+ end
12033+ if at == "nil"
12034+ return "sp_box_nil()"
12035+ end
12036+ "sp_box_int(" + val + ")"
12037+ end
12038+
1141212039 def compile_call_args_with_defaults(nid, mi)
1141312040 args_id = @nd_arguments[nid]
1141412041 arg_ids = []
@@ -11610,6 +12237,18 @@
1161012237 return ""
1161112238 end
1161212239 arg_ids = get_args(args_id)
12240+ # Check if multiple args may trigger GC
12241+ gc_count = 0
12242+ k = 0
12243+ while k < arg_ids.length
12244+ if expr_may_gc(arg_ids[k]) == 1
12245+ gc_count = gc_count + 1
12246+ end
12247+ k = k + 1
12248+ end
12249+ if gc_count >= 2
12250+ return compile_gc_safe_args(arg_ids)
12251+ end
1161312252 result = ""
1161412253 k = 0
1161512254 while k < arg_ids.length
@@ -11622,6 +12261,36 @@
1162212261 result
1162312262 end
1162412263
12264+ def compile_gc_safe_args(arg_ids)
12265+ temps = "".split(",")
12266+ k = 0
12267+ while k < arg_ids.length
12268+ if expr_may_gc(arg_ids[k]) == 1
12269+ tmp = new_temp
12270+ at = infer_type(arg_ids[k])
12271+ ct = c_type(at)
12272+ emit(" " + ct + " " + tmp + " = " + compile_expr(arg_ids[k]) + ";")
12273+ if type_is_pointer(at) == 1
12274+ emit(" SP_GC_ROOT(" + tmp + ");")
12275+ end
12276+ temps.push(tmp)
12277+ else
12278+ temps.push(compile_expr(arg_ids[k]))
12279+ end
12280+ k = k + 1
12281+ end
12282+ result = ""
12283+ k = 0
12284+ while k < temps.length
12285+ if k > 0
12286+ result = result + ", "
12287+ end
12288+ result = result + temps[k]
12289+ k = k + 1
12290+ end
12291+ result
12292+ end
12293+
1162512294 def compile_typed_call_args(nid, target_ci, target_midx)
1162612295 # Like compile_call_args but casts arguments to match target method param types
1162712296 args_id = @nd_arguments[nid]
@@ -11864,64 +12533,81 @@
1186412533 end
1186512534 end
1186612535 end
12536+ vref = fiber_var_ref(lname)
1186712537 vt = find_var_type(lname)
12538+ # ptr_array: empty array literal should create PtrArray
12539+ if is_ptr_array_type(vt) == 1
12540+ expr_id = @nd_expression[nid]
12541+ if expr_id >= 0 && @nd_type[expr_id] == "ArrayNode"
12542+ elems = parse_id_list(@nd_elements[expr_id])
12543+ if elems.length == 0
12544+ @needs_ptr_array = 1
12545+ @needs_gc = 1
12546+ emit(" " + vref + " = sp_PtrArray_new();")
12547+ return
12548+ end
12549+ end
12550+ end
1186812551 if vt == "poly"
1186912552 # Box the value
11870- emit(" lv_" + lname + " = " + box_expr_to_poly(@nd_expression[nid]) + ";")
12553+ emit(" " + vref + " = " + box_expr_to_poly(@nd_expression[nid]) + ";")
1187112554 return
1187212555 end
1187312556 if vt == "mutable_str"
1187412557 rhs_type = infer_type(@nd_expression[nid])
1187512558 val = compile_expr(@nd_expression[nid])
1187612559 if rhs_type == "string" || rhs_type == "int"
11877- emit(" lv_" + lname + " = sp_String_new(" + val + ");")
12560+ emit(" " + vref + " = sp_String_new(" + val + ");")
1187812561 else
11879- emit(" lv_" + lname + " = " + val + ";")
12562+ emit(" " + vref + " = " + val + ";")
1188012563 end
1188112564 return
1188212565 end
1188312566 rhs_t = infer_type(@nd_expression[nid])
1188412567 if rhs_t == "nil" && is_nullable_type(vt) == 1
11885- emit(" lv_" + lname + " = NULL;")
12568+ emit(" " + vref + " = NULL;")
1188612569 else
1188712570 val = compile_expr(@nd_expression[nid])
11888- emit(" lv_" + lname + " = " + val + ";")
12571+ emit(" " + vref + " = " + val + ";")
12572+ end
12573+ if rhs_t != "nil" || is_nullable_type(vt) == 0
12574+ set_var_type(lname, rhs_t)
1188912575 end
11890- set_var_type(lname, rhs_t)
1189112576 return
1189212577 end
1189312578 if t == "LocalVariableOperatorWriteNode"
1189412579 op = @nd_binop[nid]
1189512580 val = compile_expr(@nd_expression[nid])
12581+ vref = fiber_var_ref(@nd_name[nid])
1189612582 if op == "+"
11897- emit(" lv_" + @nd_name[nid] + " += " + val + ";")
12583+ emit(" " + vref + " += " + val + ";")
1189812584 end
1189912585 if op == "-"
11900- emit(" lv_" + @nd_name[nid] + " -= " + val + ";")
12586+ emit(" " + vref + " -= " + val + ";")
1190112587 end
1190212588 if op == "*"
11903- emit(" lv_" + @nd_name[nid] + " *= " + val + ";")
12589+ emit(" " + vref + " *= " + val + ";")
1190412590 end
1190512591 if op == "/"
11906- emit(" lv_" + @nd_name[nid] + " /= " + val + ";")
12592+ emit(" " + vref + " /= " + val + ";")
1190712593 end
1190812594 if op == "%"
11909- emit(" lv_" + @nd_name[nid] + " = sp_imod(lv_" + @nd_name[nid] + ", " + val + ");")
12595+ emit(" " + vref + " = sp_imod(" + vref + ", " + val + ");")
1191012596 end
1191112597 if op == "<<"
11912- emit(" lv_" + @nd_name[nid] + " <<= " + val + ";")
12598+ emit(" " + vref + " <<= " + val + ";")
1191312599 end
1191412600 if op == ">>"
11915- emit(" lv_" + @nd_name[nid] + " >>= " + val + ";")
12601+ emit(" " + vref + " >>= " + val + ";")
1191612602 end
1191712603 if op == "&"
11918- emit(" lv_" + @nd_name[nid] + " &= " + val + ";")
12604+ emit(" " + vref + " &= " + val + ";")
1191912605 end
1192012606 if op == "|"
11921- emit(" lv_" + @nd_name[nid] + " |= " + val + ";")
12607+ emit(" " + vref + " |= " + val + ";")
1192212608 end
1192312609 if op == "^"
11924- emit(" lv_" + @nd_name[nid] + " ^= " + val + ";")
12610+ emit(" " + vref + " ^= " + val + ";")
1192512611 end
1192612612 return
1192712613 end
@@ -12059,7 +12745,7 @@
1205912745 if k < tmps.length
1206012746 tid = targets[k]
1206112747 if @nd_type[tid] == "LocalVariableTargetNode"
12062- emit(" lv_" + @nd_name[tid] + " = " + tmps[k] + ";")
12748+ emit(" " + fiber_var_ref(@nd_name[tid]) + " = " + tmps[k] + ";")
1206312749 end
1206412750 if @nd_type[tid] == "InstanceVariableTargetNode"
1206512751 iname = @nd_name[tid]
@@ -12098,7 +12784,7 @@
1209812784 while k < targets.length
1209912785 tid = targets[k]
1210012786 if @nd_type[tid] == "LocalVariableTargetNode"
12101- emit(" lv_" + @nd_name[tid] + " = sp_IntArray_get(" + tmp + ", " + k.to_s + ");")
12787+ emit(" " + fiber_var_ref(@nd_name[tid]) + " = sp_IntArray_get(" + tmp + ", " + k.to_s + ");")
1210212788 end
1210312789 k = k + 1
1210412790 end
@@ -13195,14 +13881,27 @@
1319513881 end
1319613882 return
1319713883 end
13198- # Collect local writes as locals
13884+ # Collect local writes — scan expression first to detect reads before the write
1319913885 if t == "LocalVariableWriteNode"
1320013886 vn = @nd_name[nid]
13887+ # Scan the RHS expression first (may contain reads of the same var)
13888+ if @nd_expression[nid] >= 0
13889+ scan_lambda_free_vars(@nd_expression[nid], params, locals, free_vars)
13890+ end
1320113891 if not_in(vn, locals) == 1
1320213892 if not_in(vn, params) == 1
13203- locals.push(vn)
13893+ if not_in(vn, free_vars) == 1
13894+ # Check if variable exists in outer scope — if so, it's a free var
13895+ outer_t = find_var_type(vn)
13896+ if outer_t != ""
13897+ free_vars.push(vn)
13898+ else
13899+ locals.push(vn)
13900+ end
13901+ end
1320413902 end
1320513903 end
13904+ return
1320613905 end
1320713906 # Recurse
1320813907 if @nd_body[nid] >= 0
@@ -13258,45 +13957,195 @@
1325813957 end
1325913958 end
1326013959
13261- def compile_lambda_body_expr(nid, params, captures)
13262- # Compile an expression inside a lambda body, replacing:
13263- # - param refs with lv_param (local)
13264- # - captured var refs with self->captures[i]
13960+ def scan_lambda_ret_types(stmts)
13961+ stmts.each { |sid|
13962+ scan_lambda_ret_types_node(sid)
13963+ }
13964+ # Also check: h = method_call() where method returns lambda
13965+ stmts.each { |sid|
13966+ if @nd_type[sid] == "LocalVariableWriteNode"
13967+ vn = @nd_name[sid]
13968+ expr = @nd_expression[sid]
13969+ if expr >= 0 && @nd_type[expr] == "CallNode"
13970+ call_ret = infer_type(expr)
13971+ if call_ret == "lambda"
13972+ # Find the method and its lambda return
13973+ mn = @nd_name[expr]
13974+ mi = find_method_idx(mn)
13975+ if mi >= 0
13976+ bid = @meth_body_ids[mi]
13977+ if bid >= 0
13978+ mbs = get_stmts(bid)
13979+ if mbs.length > 0
13980+ last = mbs.last
13981+ if @nd_type[last] == "LambdaNode"
13982+ lbody = @nd_body[last]
13983+ if lbody >= 0
13984+ lbs = get_stmts(lbody)
13985+ if lbs.length > 0
13986+ lrt = infer_type(lbs.last)
13987+ if not_in(vn, @lambda_var_ret_names) == 1
13988+ @lambda_var_ret_names.push(vn)
13989+ @lambda_var_ret_types.push(lrt)
13990+ end
13991+ end
13992+ end
13993+ end
13994+ end
13995+ end
13996+ end
13997+ end
13998+ end
13999+ end
14000+ }
14001+ end
14002+
14003+ def scan_lambda_ret_types_node(nid)
1326514004 if nid < 0
13266- return "&sp_lam_nil_val"
14005+ return
1326714006 end
1326814007 t = @nd_type[nid]
13269- if t == "LocalVariableReadNode"
13270- vn = @nd_name[nid]
13271- # Check param
13272- if not_in(vn, params) == 0
13273- return "lv_" + vn
13274- end
13275- # Check captures
13276- ci = 0
13277- while ci < captures.length
13278- if captures[ci] == vn
13279- return "self->captures[" + ci.to_s + "]"
13280- end
13281- ci = ci + 1
13282- end
13283- return "lv_" + vn
13284- end
1328514008 if t == "LocalVariableWriteNode"
1328614009 vn = @nd_name[nid]
13287- val = compile_lambda_body_expr(@nd_expression[nid], params, captures)
13288- # Check if capture
13289- ci = 0
13290- while ci < captures.length
13291- if captures[ci] == vn
13292- return "(self->captures[" + ci.to_s + "] = " + val + ")"
14010+ expr = @nd_expression[nid]
14011+ if expr >= 0 && @nd_type[expr] == "LambdaNode"
14012+ lbody = @nd_body[expr]
14013+ if lbody >= 0
14014+ lbs = get_stmts(lbody)
14015+ if lbs.length > 0
14016+ lrt = infer_type(lbs.last)
14017+ if not_in(vn, @lambda_var_ret_names) == 1
14018+ @lambda_var_ret_names.push(vn)
14019+ @lambda_var_ret_types.push(lrt)
14020+ end
14021+ end
1329314022 end
13294- ci = ci + 1
1329514023 end
13296- emit(" sp_Val *lv_" + vn + " = " + val + ";")
13297- return "lv_" + vn
14024+ scan_lambda_ret_types_node(expr)
1329814025 end
13299- if t == "IntegerNode"
14026+ # Scan into method bodies to find lambdas returned from methods
14027+ if t == "DefNode"
14028+ if @nd_body[nid] >= 0
14029+ scan_lambda_ret_types_node(@nd_body[nid])
14030+ end
14031+ return
14032+ end
14033+ if @nd_body[nid] >= 0
14034+ scan_lambda_ret_types_node(@nd_body[nid])
14035+ end
14036+ if @nd_expression[nid] >= 0
14037+ scan_lambda_ret_types_node(@nd_expression[nid])
14038+ end
14039+ ss = parse_id_list(@nd_stmts[nid])
14040+ k = 0
14041+ while k < ss.length
14042+ scan_lambda_ret_types_node(ss[k])
14043+ k = k + 1
14044+ end
14045+ end
14046+
14047+ def lambda_var_ret_type(vname)
14048+ i = 0
14049+ while i < @lambda_var_ret_names.length
14050+ if @lambda_var_ret_names[i] == vname
14051+ return @lambda_var_ret_types[i]
14052+ end
14053+ i = i + 1
14054+ end
14055+ ""
14056+ end
14057+
14058+ def lam_box(expr, vtype)
14059+ bt = base_type(vtype)
14060+ if bt == "string"
14061+ return "sp_lam_int((mrb_int)" + expr + ")"
14062+ end
14063+ if bt == "float"
14064+ return "sp_lam_int(*(mrb_int*)&(mrb_float){" + expr + "})"
14065+ end
14066+ if bt == "bool"
14067+ return "sp_lam_bool(" + expr + ")"
14068+ end
14069+ if bt == "nil" || bt == "void"
14070+ return "&sp_lam_nil_val"
14071+ end
14072+ "sp_lam_int(" + expr + ")"
14073+ end
14074+
14075+ def lam_unbox(expr, vtype)
14076+ bt = base_type(vtype)
14077+ if bt == "string"
14078+ return "(const char*)sp_lam_to_int(" + expr + ")"
14079+ end
14080+ if bt == "float"
14081+ return "*(mrb_float*)&(mrb_int){sp_lam_to_int(" + expr + ")}"
14082+ end
14083+ if bt == "bool"
14084+ return "(" + expr + ")->u.bval"
14085+ end
14086+ if bt == "nil" || bt == "void"
14087+ return "(sp_lam_to_int(" + expr + "), 0)"
14088+ end
14089+ "sp_lam_to_int(" + expr + ")"
14090+ end
14091+
14092+ def compile_lambda_body_expr(nid, params, captures)
14093+ # Compile an expression inside a lambda body, replacing:
14094+ # - param refs with lv_param (local)
14095+ # - captured var refs with self->captures[i]
14096+ if nid < 0
14097+ return "&sp_lam_nil_val"
14098+ end
14099+ t = @nd_type[nid]
14100+ if t == "LocalVariableReadNode"
14101+ vn = @nd_name[nid]
14102+ # Check param
14103+ if not_in(vn, params) == 0
14104+ return "lv_" + vn
14105+ end
14106+ # Check captures
14107+ ci = 0
14108+ while ci < captures.length
14109+ if captures[ci] == vn
14110+ ct = ""
14111+ if ci < @lambda_capture_cell_types.length
14112+ ct = @lambda_capture_cell_types[ci]
14113+ end
14114+ if ct != ""
14115+ # Typed cell capture: dereference and box
14116+ deref = "*(" + c_type(ct) + "*)self->captures[" + ci.to_s + "]"
14117+ return lam_box(deref, ct)
14118+ end
14119+ return "self->captures[" + ci.to_s + "]"
14120+ end
14121+ ci = ci + 1
14122+ end
14123+ return "lv_" + vn
14124+ end
14125+ if t == "LocalVariableWriteNode"
14126+ vn = @nd_name[nid]
14127+ val = compile_lambda_body_expr(@nd_expression[nid], params, captures)
14128+ # Check if capture
14129+ ci = 0
14130+ while ci < captures.length
14131+ if captures[ci] == vn
14132+ ct = ""
14133+ if ci < @lambda_capture_cell_types.length
14134+ ct = @lambda_capture_cell_types[ci]
14135+ end
14136+ if ct != ""
14137+ # Typed cell capture: unbox and store
14138+ cptr = "*(" + c_type(ct) + "*)self->captures[" + ci.to_s + "]"
14139+ return "(" + cptr + " = " + lam_unbox(val, ct) + ", " + val + ")"
14140+ end
14141+ return "(self->captures[" + ci.to_s + "] = " + val + ")"
14142+ end
14143+ ci = ci + 1
14144+ end
14145+ emit(" sp_Val *lv_" + vn + " = " + val + ";")
14146+ return "lv_" + vn
14147+ end
14148+ if t == "IntegerNode"
1330014149 return "sp_lam_int(" + @nd_value[nid].to_s + ")"
1330114150 end
1330214151 if t == "TrueNode"
@@ -13458,23 +14307,160 @@
1345814307 @lambda_counter = @lambda_counter + 1
1345914308 fname = "_lam_" + lam_id.to_s
1346014309
14310+ # Compute capture cell types (before body compilation)
14311+ cap_cell_types = "".split(",")
14312+ k = 0
14313+ while k < free_vars.length
14314+ fv = free_vars[k]
14315+ cell = heap_promoted_cell(fv)
14316+ if cell == "" && @in_fiber_body == 1 && fiber_capture_index(fv) >= 0
14317+ cell = "_cap->" + fv
14318+ end
14319+ # Regular locals will be heap-promoted (not lambda params/captures)
14320+ if cell == "" && not_in(fv, @lambda_params) == 1
14321+ is_enclosing_cap = 0
14322+ ci = 0
14323+ while ci < @lambda_captures.length
14324+ if @lambda_captures[ci] == fv
14325+ is_enclosing_cap = 1
14326+ end
14327+ ci = ci + 1
14328+ end
14329+ if is_enclosing_cap == 0
14330+ vt = find_var_type(fv)
14331+ if vt != "" && vt != "lambda"
14332+ cell = "will_promote"
14333+ end
14334+ end
14335+ end
14336+ if cell != ""
14337+ cap_cell_types.push(find_var_type(fv))
14338+ else
14339+ cap_cell_types.push("")
14340+ end
14341+ k = k + 1
14342+ end
14343+
14344+ # Check if we have typed cell captures (need regular compiler path)
14345+ has_typed_caps = 0
14346+ k = 0
14347+ while k < cap_cell_types.length
14348+ if cap_cell_types[k] != ""
14349+ has_typed_caps = 1
14350+ end
14351+ k = k + 1
14352+ end
14353+
1346114354 # Get body expression
1346214355 bexpr = "&sp_lam_nil_val"
1346314356 if body >= 0
1346414357 bs = get_stmts(body)
13465- if bs.length > 0
13466- # Save current output and context, compile body into lambda function
14358+ if bs.length > 0 && has_typed_caps == 1
14359+ # Typed captures: compile body using regular compiler
14360+ save_out = @out
14361+ save_indent = @indent
14362+ save_hp_names_len = @heap_promoted_names.length
14363+ save_hp_cells_len = @heap_promoted_cells.length
14364+ @out = ""
14365+ @indent = 1
14366+
14367+ push_scope
14368+ # Declare parameter with proper type
14369+ if pname != ""
14370+ ptype = infer_type(bs.last)
14371+ if ptype == ""
14372+ ptype = "int"
14373+ end
14374+ declare_var(pname, "int")
14375+ end
14376+ # Set up cell pointer locals for typed captures
14377+ k = 0
14378+ while k < free_vars.length
14379+ if cap_cell_types[k] != ""
14380+ ct = c_type(cap_cell_types[k])
14381+ cell_local = "_lc_" + free_vars[k]
14382+ emit(" " + ct + " *" + cell_local + " = (" + ct + "*)self->captures[" + k.to_s + "];")
14383+ @heap_promoted_names.push(free_vars[k])
14384+ @heap_promoted_cells.push(cell_local)
14385+ declare_var(free_vars[k], cap_cell_types[k])
14386+ end
14387+ k = k + 1
14388+ end
14389+ # Declare body-local variables
14390+ lnames = "".split(",")
14391+ ltypes = "".split(",")
14392+ excl = "".split(",")
14393+ if pname != ""
14394+ excl.push(pname)
14395+ end
14396+ k = 0
14397+ while k < free_vars.length
14398+ excl.push(free_vars[k])
14399+ k = k + 1
14400+ end
14401+ scan_locals(body, lnames, ltypes, excl)
14402+ lk = 0
14403+ while lk < lnames.length
14404+ declare_var(lnames[lk], ltypes[lk])
14405+ emit(" " + c_type(ltypes[lk]) + " lv_" + lnames[lk] + " = " + c_default_val(ltypes[lk]) + ";")
14406+ lk = lk + 1
14407+ end
14408+ # Compile body statements
14409+ i = 0
14410+ while i < bs.length - 1
14411+ compile_stmt(bs[i])
14412+ i = i + 1
14413+ end
14414+ last = bs.last
14415+ last_type = infer_type(last)
14416+ if @nd_type[last] == "LocalVariableWriteNode" || @nd_type[last] == "LocalVariableOperatorWriteNode"
14417+ compile_stmt(last)
14418+ end
14419+ last_val = compile_expr(last)
14420+
14421+ pop_scope
14422+ body_stmts = @out
14423+ @out = save_out
14424+ @indent = save_indent
14425+ # Restore heap promoted
14426+ while @heap_promoted_names.length > save_hp_names_len
14427+ @heap_promoted_names.pop
14428+ end
14429+ while @heap_promoted_cells.length > save_hp_cells_len
14430+ @heap_promoted_cells.pop
14431+ end
14432+
14433+ # Build lambda function with typed body
14434+ @lambda_funcs = @lambda_funcs + "static sp_Val *" + fname + "(sp_Val *self, sp_Val *arg) {\n"
14435+ if pname != ""
14436+ @lambda_funcs = @lambda_funcs + " mrb_int lv_" + pname + " = sp_lam_to_int(arg);\n"
14437+ end
14438+ @lambda_funcs = @lambda_funcs + body_stmts + 10.chr
14439+ bexpr = lam_box(last_val, last_type)
14440+ @lambda_funcs = @lambda_funcs + " return " + bexpr + ";\n"
14441+ @lambda_funcs = @lambda_funcs + "}\n\n"
14442+ elsif bs.length > 0
14443+ # No typed captures: use sp_Val* lambda body compiler
1346714444 save_out = @out
1346814445 save_params = @lambda_params
1346914446 save_captures = @lambda_captures
14447+ save_cell_types = @lambda_capture_cell_types
1347014448 @out = ""
1347114449 @lambda_params = param_arr
1347214450 @lambda_captures = free_vars
14451+ @lambda_capture_cell_types = cap_cell_types
14452+ si = 0
14453+ while si < bs.length - 1
14454+ side_expr = compile_lambda_body_expr(bs[si], param_arr, free_vars)
14455+ emit(" " + side_expr + ";")
14456+ si = si + 1
14457+ end
1347314458 bexpr = compile_lambda_body_expr(bs.last, param_arr, free_vars)
1347414459 body_stmts = @out
1347514460 @out = save_out
1347614461 @lambda_params = save_params
1347714462 @lambda_captures = save_captures
14463+ @lambda_capture_cell_types = save_cell_types
1347814464
1347914465 if body_stmts != ""
1348014466 @lambda_funcs = @lambda_funcs + "static sp_Val *" + fname + "(sp_Val *self, sp_Val *arg) {\n"
@@ -13503,27 +14489,63 @@
1350314489
1350414490 # Build the closure creation expression
1350514491 if free_vars.length > 0
14492+ # Heap-promote regular locals that need cell captures
14493+ k = 0
14494+ while k < free_vars.length
14495+ if cap_cell_types[k] != "" && heap_promoted_cell(free_vars[k]) == ""
14496+ fv = free_vars[k]
14497+ # Skip if it's a fiber capture (already has cell) or lambda context
14498+ if @in_fiber_body == 0 || fiber_capture_index(fv) < 0
14499+ if not_in(fv, @heap_promoted_names) == 1
14500+ ct = c_type(cap_cell_types[k])
14501+ cell = "_hcell_" + fv + "_l" + lam_id.to_s
14502+ emit(" " + ct + " *" + cell + " = (" + ct + "*)sp_gc_alloc(sizeof(" + ct + "), NULL, NULL);")
14503+ emit(" *" + cell + " = " + fiber_var_ref(fv) + ";")
14504+ @heap_promoted_names.push(fv)
14505+ @heap_promoted_cells.push(cell)
14506+ end
14507+ end
14508+ end
14509+ k = k + 1
14510+ end
1350614511 tmp = new_temp
1350714512 emit(" sp_Val *" + tmp + " = sp_lam_proc(" + fname + ", " + free_vars.length.to_s + ");")
1350814513 k = 0
1350914514 while k < free_vars.length
13510- # Resolve the free variable reference in the enclosing context
1351114515 fv = free_vars[k]
13512- fv_ref = "lv_" + fv
13513- # Check if it's a param of enclosing lambda
13514- if not_in(fv, @lambda_params) == 0
13515- fv_ref = "lv_" + fv
14516+ if cap_cell_types[k] != ""
14517+ # Heap-promoted or fiber-captured: store cell pointer cast to sp_Val*
14518+ cell = heap_promoted_cell(fv)
14519+ if cell == "" && @in_fiber_body == 1 && fiber_capture_index(fv) >= 0
14520+ cell = "_cap->" + fv
14521+ end
14522+ emit(" " + tmp + "->captures[" + k.to_s + "] = (sp_Val*)" + cell + ";")
1351614523 else
13517- # Check if it's a capture of enclosing lambda
13518- ci = 0
13519- while ci < @lambda_captures.length
13520- if @lambda_captures[ci] == fv
13521- fv_ref = "self->captures[" + ci.to_s + "]"
14524+ # Check if it's a param or capture of enclosing lambda (sp_Val* world)
14525+ is_lam_ctx = 0
14526+ if not_in(fv, @lambda_params) == 0
14527+ is_lam_ctx = 1
14528+ emit(" " + tmp + "->captures[" + k.to_s + "] = lv_" + fv + ";")
14529+ else
14530+ ci = 0
14531+ while ci < @lambda_captures.length
14532+ if @lambda_captures[ci] == fv
14533+ is_lam_ctx = 1
14534+ emit(" " + tmp + "->captures[" + k.to_s + "] = self->captures[" + ci.to_s + "];")
14535+ end
14536+ ci = ci + 1
14537+ end
14538+ end
14539+ if is_lam_ctx == 0
14540+ # Regular local: should have been heap-promoted already
14541+ cell = heap_promoted_cell(fv)
14542+ if cell != ""
14543+ emit(" " + tmp + "->captures[" + k.to_s + "] = (sp_Val*)" + cell + ";")
14544+ else
14545+ emit(" " + tmp + "->captures[" + k.to_s + "] = " + fiber_var_ref(fv) + ";")
1352214546 end
13523- ci = ci + 1
1352414547 end
1352514548 end
13526- emit(" " + tmp + "->captures[" + k.to_s + "] = " + fv_ref + ";")
1352714549 k = k + 1
1352814550 end
1352914551 return tmp