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 = 0126126
@needs_int_array = 0127127
@needs_float_array = 0128+
@needs_ptr_array = 0128129
@needs_str_array = 0129130
@needs_str_int_hash = 0130131
@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 support152157
@needs_fiber = 0153158
@fiber_counter = 0154159
@fiber_funcs = ""160+
@in_fiber_body = 0161+
@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 types157167
@poly_funcs = "".split(",")@@ -949,6 +959,15 @@
949959
return "int"950960
end951961
if t == "LambdaNode"962+
# Record return type if inside a variable assignment context963+
lbody = @nd_body[nid]964+
if lbody >= 0965+
lbs = get_stmts(lbody)966+
if lbs.length > 0967+
lrt = infer_type(lbs.last)968+
@last_lambda_ret_type = lrt969+
end970+
end952971
return "lambda"953972
end954973
"int"@@ -1049,6 +1068,22 @@
10491068
return r10501069
end10511070
1071+
# Lambda call return type1072+
if mname == "call" || mname == "[]"1073+
if recv >= 01074+
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 lrt1080+
end1081+
end1082+
return "int"1083+
end1084+
end1085+
end1086+
10521087
# Method name-based type inference10531088
r = infer_method_name_type(nid, mname, recv)10541089
if r != ""@@ -1115,21 +1150,49 @@
11151150
end11161151
end11171152
end1118-
# fiber.resume returns int1153+
# fiber.resume returns poly11191154
if mname == "resume"11201155
if recv >= 01121-
rt = infer_type(recv)1156+
rt = base_type(infer_type(recv))11221157
if rt == "fiber"1123-
return "int"1158+
return "poly"11241159
end11251160
end11261161
end1127-
# Fiber.yield returns int1162+
# Fiber.yield returns poly11281163
if mname == "yield"11291164
if recv >= 011301165
if @nd_type[recv] == "ConstantReadNode"11311166
if @nd_name[recv] == "Fiber"1132-
return "int"1167+
return "poly"1168+
end1169+
end1170+
end1171+
end1172+
# fiber.alive? returns bool1173+
if mname == "alive?"1174+
if recv >= 01175+
rt = base_type(infer_type(recv))1176+
if rt == "fiber"1177+
return "bool"1178+
end1179+
end1180+
end1181+
# fiber.transfer returns poly1182+
if mname == "transfer"1183+
if recv >= 01184+
rt = base_type(infer_type(recv))1185+
if rt == "fiber"1186+
return "poly"1187+
end1188+
end1189+
end1190+
# Fiber.current returns fiber1191+
if mname == "current"1192+
if recv >= 01193+
if @nd_type[recv] == "ConstantReadNode"1194+
if @nd_name[recv] == "Fiber"1195+
return "fiber"11331196
end11341197
end11351198
end@@ -1669,6 +1732,9 @@
16691732
if rt == "str_array"16701733
return "string"16711734
end1735+
if is_ptr_array_type(rt) == 11736+
return ptr_array_elem_type(rt)1737+
end16721738
if rt == "str_int_hash"16731739
return "int"16741740
end@@ -1916,7 +1982,8 @@
19161982
end19171983
end19181984
if is_obj_type(rt) == 11919-
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 >= 019221989
# Check attr_reader@@ -2041,6 +2108,24 @@
20412108
020422109
end20432110
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 > 102114+
if t.end_with?("_ptr_array")2115+
return 12116+
end2117+
end2118+
02119+
end2120+
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) == 12124+
return t[0, t.length - 10]2125+
end2126+
""2127+
end2128+
20442129
def type_is_pointer(t)20452130
if is_nullable_type(t) == 120462131
t = base_type(t)@@ -2051,6 +2136,9 @@
20512136
if t == "float_array"20522137
return 120532138
end2139+
if is_ptr_array_type(t) == 12140+
return 12141+
end20542142
if t == "str_array"20552143
return 120562144
end@@ -2080,6 +2168,27 @@
20802168
020812169
end20822170
2171+
# Check if evaluating an expression might trigger GC allocation2172+
def expr_may_gc(nid)2173+
if nid < 02174+
return 02175+
end2176+
t = @nd_type[nid]2177+
if t == "IntegerNode" || t == "FloatNode" || t == "StringNode"2178+
return 02179+
end2180+
if t == "SymbolNode" || t == "TrueNode" || t == "FalseNode" || t == "NilNode"2181+
return 02182+
end2183+
if t == "LocalVariableReadNode" || t == "SelfNode"2184+
return 02185+
end2186+
if t == "InstanceVariableReadNode" || t == "ConstantReadNode"2187+
return 02188+
end2189+
12190+
end2191+
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 121112220
end2221+
if bt == "fiber"2222+
return 12223+
end21122224
if is_obj_type(bt) == 121132225
return 121142226
end@@ -2161,6 +2273,9 @@
21612273
if t == "float_array"21622274
return "sp_FloatArray *"21632275
end2276+
if is_ptr_array_type(t) == 12277+
return "sp_PtrArray *"2278+
end21642279
if t == "str_array"21652280
return "sp_StrArray *"21662281
end@@ -2939,14 +3054,25 @@
29393054
while k < names.length29403055
if names[k] == iname29413056
if k < types.length2942-
if types[k] == "int"3057+
old = types[k]3058+
if old == "int" || old == "nil"29433059
types[k] = new_type29443060
@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) == 13064+
if old[old.length - 1] != "?"3065+
types[k] = old + "?"3066+
@cls_ivar_types[ci] = types.join(";")3067+
end3068+
elsif old == "nil" && is_nullable_pointer_type(new_type) == 13069+
types[k] = new_type + "?"3070+
@cls_ivar_types[ci] = types.join(";")3071+
else3072+
types[k] = "poly"3073+
@cls_ivar_types[ci] = types.join(";")3074+
end29453075
end2946-
if types[k] == "nil"2947-
types[k] = new_type2948-
@cls_ivar_types[ci] = types.join(";")2949-
end29503076
end29513077
return29523078
end@@ -3643,10 +3769,21 @@
36433769
else36443770
at = infer_type(arg_ids[k])36453771
if k < ptypes.length3646-
if ptypes[k] == "int"3772+
old_pt = ptypes[k]3773+
if old_pt == "int"36473774
if at != "int"36483775
ptypes[k] = at36493776
end3777+
elsif old_pt == "nil" && at != "nil" && at != "int"3778+
if is_nullable_pointer_type(at) == 13779+
ptypes[k] = at + "?"3780+
else3781+
ptypes[k] = at3782+
end3783+
elsif at == "nil" && old_pt != "nil" && is_nullable_pointer_type(old_pt) == 13784+
if old_pt[old_pt.length - 1] != "?"3785+
ptypes[k] = old_pt + "?"3786+
end36503787
end36513788
end36523789
end@@ -4187,6 +4324,16 @@
41874324
if nid < 041884325
return41894326
end4327+
# Direct ivar write: @left = expr (inside class methods)4328+
if @nd_type[nid] == "InstanceVariableWriteNode"4329+
if @current_class_idx >= 04330+
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+
end4335+
end4336+
end41904337
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 > 042114358
at = infer_type(arg_ids[0])4212-
if at != "int"4213-
if at != "nil"4214-
update_ivar_type(ci, iname, at)4215-
end4359+
if at != "int" && at != "nil"4360+
update_ivar_type(ci, iname, at)42164361
end42174362
end42184363
end@@ -5387,6 +5532,15 @@
53875532
end53885533
end53895534
end5535+
if mname == "current"5536+
if @nd_receiver[nid] >= 05537+
if @nd_type[@nd_receiver[nid]] == "ConstantReadNode"5538+
if @nd_name[@nd_receiver[nid]] == "Fiber"5539+
@needs_fiber = 15540+
end5541+
end5542+
end5543+
end53905544
if mname == "catch"53915545
@needs_setjmp = 153925546
end@@ -5600,9 +5754,19 @@
56005754
end56015755
# otherwise arg is int variable, param already has a type - keep it56025756
else5603-
# Genuinely different types - mark poly5604-
ptypes[k] = "poly"5605-
@needs_rb_value = 15757+
# Check nullable compatibility: T and T? are compatible5758+
if base_type(ct) == base_type(at)5759+
# Same base type — use nullable version5760+
if is_nullable_type(at) == 15761+
ptypes[k] = at5762+
elsif is_nullable_type(ct) == 0 && is_nullable_pointer_type(ct) == 15763+
ptypes[k] = ct + "?"5764+
end5765+
else5766+
# Genuinely different types - mark poly5767+
ptypes[k] = "poly"5768+
@needs_rb_value = 15769+
end56065770
end56075771
end56085772
end@@ -6059,6 +6223,13 @@
60596223
end60606224
emit_float_array_runtime60616225
end6226+
if @needs_ptr_array == 16227+
if @needs_gc == 06228+
@needs_gc = 16229+
emit_gc_runtime6230+
end6231+
emit_ptr_array_runtime6232+
end60626233
if @needs_str_array == 160636234
emit_str_array_runtime60646235
end@@ -6141,6 +6312,26 @@
61416312
@needs_gc = 161426313
emit_gc_runtime61436314
end6315+
if @needs_setjmp == 06316+
@needs_setjmp = 16317+
emit_setjmp_runtime6318+
end6319+
if @needs_rb_value == 06320+
@needs_rb_value = 16321+
if @needs_string_helpers == 06322+
@needs_string_helpers = 16323+
if @needs_int_array == 06324+
@needs_int_array = 16325+
emit_int_array_runtime6326+
end6327+
if @needs_str_array == 06328+
@needs_str_array = 16329+
emit_str_array_runtime6330+
end6331+
emit_string_helpers6332+
end6333+
emit_rb_value_runtime6334+
end61446335
emit_fiber_runtime61456336
end61466337
emit_class_structs@@ -6248,6 +6439,19 @@
62486439
emit_raw("")62496440
end62506441
6442+
def emit_ptr_array_runtime6443+
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+
end6454+
62516455
def emit_float_array_runtime62526456
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-
end6605-
6606-
def emit_stringio_runtime6607-
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+
end6813+
6814+
def emit_stringio_runtime6815+
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
end83158523
end83168524
end8525+
# 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 >= 08533+
aargs = get_args(args_id)8534+
if aargs.length > 08535+
arg_type = infer_type(aargs[0])8536+
if is_obj_type(arg_type) == 18537+
target_type = arg_type + "_ptr_array"8538+
@needs_ptr_array = 18539+
@needs_gc = 18540+
ki = 08541+
while ki < names.length8542+
if names[ki] == arr_name8543+
if types[ki] == "int_array"8544+
types[ki] = target_type8545+
end8546+
end8547+
ki = ki + 18548+
end8549+
end8550+
end8551+
end8552+
end8553+
end8554+
end83178555
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 types8912+
scan_lambda_ret_types(stmts)8913+
86738914
# Compile main statements86748915
stmts.each { |sid|86758916
if @nd_type[sid] != "DefNode"@@ -8745,7 +8986,7 @@
87458986
return "self"87468987
end87478988
if t == "LocalVariableReadNode"8748-
return "lv_" + @nd_name[nid]8989+
return fiber_var_ref(@nd_name[nid])87498990
end87508991
if t == "InstanceVariableReadNode"87518992
# Check if we're in a module class method@@ -9223,6 +9464,164 @@
92239464
end92249465
92259466
9467+
# --- Fiber capture helpers ---9468+
9469+
def fiber_capture_index(name)9470+
i = 09471+
while i < @fiber_captures.length9472+
if @fiber_captures[i] == name9473+
return i9474+
end9475+
i = i + 19476+
end9477+
-19478+
end9479+
9480+
def heap_promoted_cell(name)9481+
i = 09482+
while i < @heap_promoted_names.length9483+
if @heap_promoted_names[i] == name9484+
return @heap_promoted_cells[i]9485+
end9486+
i = i + 19487+
end9488+
""9489+
end9490+
9491+
def fiber_var_ref(name)9492+
if @in_fiber_body == 19493+
if fiber_capture_index(name) >= 09494+
return "(*_cap->" + name + ")"9495+
end9496+
end9497+
cell = heap_promoted_cell(name)9498+
if cell != ""9499+
return "(*" + cell + ")"9500+
end9501+
"lv_" + name9502+
end9503+
9504+
9505+
def scan_fiber_free_vars(nid, params, locals, free_vars, free_var_types)9506+
if nid < 09507+
return9508+
end9509+
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) == 19513+
vt = find_var_type(vn)9514+
if vt != ""9515+
free_vars.push(vn)9516+
free_var_types.push(vt)9517+
end9518+
end9519+
return9520+
end9521+
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) == 19524+
vt = find_var_type(vn)9525+
if vt != ""9526+
free_vars.push(vn)9527+
free_var_types.push(vt)9528+
end9529+
end9530+
# Also scan the expression9531+
scan_fiber_free_vars(@nd_expression[nid], params, locals, free_vars, free_var_types)9532+
return9533+
end9534+
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) == 19537+
vt = find_var_type(vn)9538+
if vt != ""9539+
free_vars.push(vn)9540+
free_var_types.push(vt)9541+
end9542+
end9543+
scan_fiber_free_vars(@nd_expression[nid], params, locals, free_vars, free_var_types)9544+
return9545+
end9546+
# Stop at nested lambda/fiber boundaries (they handle their own captures)9547+
if t == "LambdaNode"9548+
return9549+
end9550+
if t == "CallNode"9551+
# Stop at nested Fiber.new block bodies9552+
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+
return9557+
end9558+
end9559+
end9560+
# Recurse into children (follow scan_locals_children pattern)9561+
if @nd_body[nid] >= 09562+
scan_fiber_free_vars(@nd_body[nid], params, locals, free_vars, free_var_types)9563+
end9564+
if @nd_receiver[nid] >= 09565+
scan_fiber_free_vars(@nd_receiver[nid], params, locals, free_vars, free_var_types)9566+
end9567+
if @nd_expression[nid] >= 09568+
scan_fiber_free_vars(@nd_expression[nid], params, locals, free_vars, free_var_types)9569+
end9570+
if @nd_predicate[nid] >= 09571+
scan_fiber_free_vars(@nd_predicate[nid], params, locals, free_vars, free_var_types)9572+
end9573+
if @nd_subsequent[nid] >= 09574+
scan_fiber_free_vars(@nd_subsequent[nid], params, locals, free_vars, free_var_types)9575+
end9576+
if @nd_else_clause[nid] >= 09577+
scan_fiber_free_vars(@nd_else_clause[nid], params, locals, free_vars, free_var_types)9578+
end9579+
if @nd_arguments[nid] >= 09580+
scan_fiber_free_vars(@nd_arguments[nid], params, locals, free_vars, free_var_types)9581+
end9582+
if @nd_rescue_clause[nid] >= 09583+
scan_fiber_free_vars(@nd_rescue_clause[nid], params, locals, free_vars, free_var_types)9584+
end9585+
if @nd_ensure_clause[nid] >= 09586+
scan_fiber_free_vars(@nd_ensure_clause[nid], params, locals, free_vars, free_var_types)9587+
end9588+
# Stmts list9589+
stmts_list = parse_id_list(@nd_stmts[nid])9590+
k = 09591+
while k < stmts_list.length9592+
scan_fiber_free_vars(stmts_list[k], params, locals, free_vars, free_var_types)9593+
k = k + 19594+
end9595+
# Args list9596+
args_list = parse_id_list(@nd_args[nid])9597+
k = 09598+
while k < args_list.length9599+
scan_fiber_free_vars(args_list[k], params, locals, free_vars, free_var_types)9600+
k = k + 19601+
end9602+
# Conditions list9603+
conds_list = parse_id_list(@nd_conditions[nid])9604+
k = 09605+
while k < conds_list.length9606+
scan_fiber_free_vars(conds_list[k], params, locals, free_vars, free_var_types)9607+
k = k + 19608+
end9609+
# Elements list9610+
elems_list = parse_id_list(@nd_elements[nid])9611+
k = 09612+
while k < elems_list.length9613+
scan_fiber_free_vars(elems_list[k], params, locals, free_vars, free_var_types)9614+
k = k + 19615+
end9616+
# Block body (for non-Fiber.new blocks)9617+
blk = @nd_block[nid]9618+
if blk >= 09619+
if @nd_body[blk] >= 09620+
scan_fiber_free_vars(@nd_body[blk], params, locals, free_vars, free_var_types)9621+
end9622+
end9623+
end9624+
92269625
def compile_fiber_new(nid)92279626
@needs_fiber = 192289627
blk = @nd_block[nid]@@ -9249,68 +9648,194 @@
92499648
end92509649
end92519650
end9252-
fid = @fiber_counter9253-
@fiber_counter = @fiber_counter + 19254-
fname = "_fiber_body_" + fid.to_s92559651
9256-
# Compile fiber body function9257-
fbody = "static void " + fname + "(sp_Fiber *_fb) {" + 10.chr9652+
body = @nd_body[blk]9653+
# Scan all variables referenced in the body9654+
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.chr9260-
end9261-
# Compile body — save/restore compiler state9262-
saved_out = @out9263-
saved_indent = @indent9264-
@out = ""9265-
@indent = 19266-
9267-
push_scope9268-
if bp != ""9269-
declare_var(bp, "int")9658+
all_plist.push(bp)92709659
end9271-
body = @nd_body[blk]92729660
if body >= 09273-
# Declare locals in fiber body9274-
lnames = "".split(",")9275-
ltypes = "".split(",")9276-
plist = "".split(",")9277-
if bp != ""9278-
plist.push(bp)9279-
end9280-
scan_locals(body, lnames, ltypes, plist)9281-
lk = 09282-
while lk < lnames.length9283-
declare_var(lnames[lk], ltypes[lk])9284-
emit(" " + c_type(ltypes[lk]) + " lv_" + lnames[lk] + " = " + c_default_val(ltypes[lk]) + ";")9285-
lk = lk + 19286-
end9287-
9288-
stmts = get_stmts(body)9289-
if stmts.length > 09290-
i = 09291-
while i < stmts.length - 19292-
compile_stmt(stmts[i])9293-
i = i + 19294-
end9295-
last = stmts.last9296-
last_val = compile_expr(last)9297-
emit(" _fb->yielded_value = (mrb_int)" + last_val + ";")9298-
end9661+
scan_locals(body, all_names, all_types, all_plist)92999662
end9300-
pop_scope93019663
9664+
# Split into captures (exist in outer scope) vs true locals9665+
free_vars = "".split(",")9666+
free_var_types = "".split(",")9667+
local_names = "".split(",")9668+
local_types = "".split(",")9669+
k = 09670+
while k < all_names.length9671+
outer_type = find_var_type(all_names[k])9672+
if outer_type != ""9673+
# Variable exists in outer scope → capture9674+
free_vars.push(all_names[k])9675+
free_var_types.push(outer_type)9676+
else9677+
# True local variable9678+
local_names.push(all_names[k])9679+
local_types.push(all_types[k])9680+
end9681+
k = k + 19682+
end9683+
9684+
# Also scan for read-only captures (variables read but not written in body)9685+
if body >= 09686+
scan_fiber_free_vars(body, all_plist, all_names, free_vars, free_var_types)9687+
end9688+
9689+
fid = @fiber_counter9690+
@fiber_counter = @fiber_counter + 19691+
fname = "_fiber_body_" + fid.to_s9692+
cap_name = "_fiber_cap_" + fid.to_s9693+
9694+
# Build capture struct typedef if needed9695+
cap_typedef = ""9696+
if free_vars.length > 09697+
cap_typedef = "typedef struct {"9698+
k = 09699+
while k < free_vars.length9700+
cap_typedef = cap_typedef + " " + c_type(free_var_types[k]) + " *" + free_vars[k] + ";"9701+
k = k + 19702+
end9703+
cap_typedef = cap_typedef + " } " + cap_name + ";" + 10.chr9704+
end9705+
9706+
# Compile fiber body function9707+
fbody = "static void " + fname + "(sp_Fiber *_fb) {" + 10.chr9708+
if free_vars.length > 09709+
fbody = fbody + " " + cap_name + " *_cap = (" + cap_name + "*)_fb->user_data;" + 10.chr9710+
end9711+
if bp != ""9712+
fbody = fbody + " sp_RbVal lv_" + bp + " = _fb->resumed_value;" + 10.chr9713+
end9714+
9715+
# Save/restore compiler state9716+
saved_out = @out9717+
saved_indent = @indent9718+
saved_in_fiber_body = @in_fiber_body9719+
saved_fiber_captures = @fiber_captures9720+
saved_fiber_capture_types = @fiber_capture_types9721+
saved_hp_names_len = @heap_promoted_names.length9722+
saved_hp_cells_len = @heap_promoted_cells.length9723+
@out = ""9724+
@indent = 19725+
@in_fiber_body = 19726+
@fiber_captures = free_vars9727+
@fiber_capture_types = free_var_types9728+
9729+
push_scope9730+
if bp != ""9731+
declare_var(bp, "poly")9732+
end9733+
if body >= 09734+
# Declare only true locals (not captured vars)9735+
lk = 09736+
while lk < local_names.length9737+
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 + 19740+
end9741+
9742+
stmts = get_stmts(body)9743+
if stmts.length > 09744+
i = 09745+
while i < stmts.length - 19746+
compile_stmt(stmts[i])9747+
i = i + 19748+
end9749+
last = stmts.last9750+
# Compile last as statement for side effects, then capture value9751+
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+
else9756+
last_val = compile_expr(last)9757+
end9758+
emit(" _fb->yielded_value = " + box_val_to_poly(last_val, last_type) + ";")9759+
end9760+
end9761+
pop_scope9762+
93029763
fbody = fbody + @out93039764
fbody = fbody + "}" + 10.chr9304-
@fiber_funcs = @fiber_funcs + fbody9765+
@fiber_funcs = @fiber_funcs + cap_typedef + fbody93059766
93069767
@out = saved_out93079768
@indent = saved_indent9769+
@in_fiber_body = saved_in_fiber_body9770+
@fiber_captures = saved_fiber_captures9771+
@fiber_capture_types = saved_fiber_capture_types9772+
# Restore heap promoted lists to saved length9773+
while @heap_promoted_names.length > saved_hp_names_len9774+
@heap_promoted_names.pop9775+
end9776+
while @heap_promoted_cells.length > saved_hp_cells_len9777+
@heap_promoted_cells.pop9778+
end9779+
9780+
# If no captures, return simple expression9781+
if free_vars.length == 09782+
return "sp_Fiber_new(" + fname + ")"9783+
end93089784
9309-
# Declare locals in body (scan for LocalVariableWriteNode)9310-
# Actually the above compile already handles this via the saved @out9785+
# Heap-promote captured variables (allocate cells if not already promoted)9786+
k = 09787+
while k < free_vars.length9788+
vn = free_vars[k]9789+
already_promoted = 09790+
# Check outer scope heap promotions9791+
ci = 09792+
while ci < @heap_promoted_names.length9793+
if @heap_promoted_names[ci] == vn9794+
already_promoted = 19795+
end9796+
ci = ci + 19797+
end9798+
# Check if variable is already a heap pointer from enclosing fiber capture9799+
if already_promoted == 0 && @in_fiber_body == 1 && fiber_capture_index(vn) >= 09800+
# Reuse the enclosing fiber's capture pointer (_cap->vn is already a heap cell)9801+
cell = "_cap->" + vn9802+
@heap_promoted_names.push(vn)9803+
@heap_promoted_cells.push(cell)9804+
already_promoted = 19805+
end9806+
if already_promoted == 09807+
cell = "_hcell_" + vn + "_" + fid.to_s9808+
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+
end9814+
k = k + 19815+
end93119816
9312-
# Return fiber creation expression9313-
"sp_Fiber_new(" + fname + ")"9817+
# Heap-allocate capture struct9818+
tmp_fb = "_tmpfb_" + fid.to_s9819+
cap_ptr = "_cap_ptr_" + fid.to_s9820+
emit(" " + cap_name + " *" + cap_ptr + " = (" + cap_name + "*)sp_gc_alloc(sizeof(" + cap_name + "), NULL, NULL);")9821+
k = 09822+
while k < free_vars.length9823+
vn = free_vars[k]9824+
# Find the cell for this variable9825+
ci = 09826+
cell = ""9827+
while ci < @heap_promoted_names.length9828+
if @heap_promoted_names[ci] == vn9829+
cell = @heap_promoted_cells[ci]9830+
end9831+
ci = ci + 19832+
end9833+
emit(" " + cap_ptr + "->" + vn + " = " + cell + ";")9834+
k = k + 19835+
end9836+
emit(" sp_Fiber *" + tmp_fb + " = sp_Fiber_new(" + fname + ");")9837+
emit(" " + tmp_fb + "->user_data = " + cap_ptr + ";")9838+
tmp_fb93149839
end93159840
93169841
def compile_call_expr(nid)@@ -9327,18 +9852,62 @@
93279852
end93289853
# fiber.resume(val)93299854
if mname == "resume" && recv >= 09330-
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 >= 09860+
arg_ids = get_args(args_id)9861+
if arg_ids.length > 09862+
return "sp_Fiber_resume(" + rc + ", " + box_expr_to_poly(arg_ids[0]) + ")"9863+
end9864+
end9865+
return "sp_Fiber_resume(" + rc + ", sp_box_nil())"93359866
end93369867
end93379868
# Fiber.yield(val)93389869
if mname == "yield" && recv >= 093399870
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 >= 09874+
arg_ids = get_args(args_id)9875+
if arg_ids.length > 09876+
return "sp_Fiber_yield(" + box_expr_to_poly(arg_ids[0]) + ")"9877+
end9878+
end9879+
return "sp_Fiber_yield(sp_box_nil())"9880+
end9881+
end9882+
end9883+
# fiber.alive?9884+
if mname == "alive?" && recv >= 09885+
rt2 = base_type(infer_type(recv))9886+
if rt2 == "fiber"9887+
rc = compile_expr(recv)9888+
return "sp_Fiber_alive(" + rc + ")"9889+
end9890+
end9891+
# fiber.transfer(val)9892+
if mname == "transfer" && recv >= 09893+
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 >= 09898+
arg_ids = get_args(args_id)9899+
if arg_ids.length > 09900+
return "sp_Fiber_transfer(" + rc + ", " + box_expr_to_poly(arg_ids[0]) + ")"9901+
end9902+
end9903+
return "sp_Fiber_transfer(" + rc + ", sp_box_nil())"9904+
end9905+
end9906+
# Fiber.current9907+
if mname == "current" && recv >= 09908+
if @nd_type[recv] == "ConstantReadNode"9909+
if @nd_name[recv] == "Fiber"9910+
return "sp_fiber_current"93429911
end93439912
end93449913
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 evaluation9962+
if expr_may_gc(recv) == 1 && type_is_pointer(recv_type) == 19963+
args_id = @nd_arguments[nid]9964+
if args_id >= 09965+
aargs = get_args(args_id)9966+
has_gc_arg = 09967+
ak = 09968+
while ak < aargs.length9969+
if expr_may_gc(aargs[ak]) == 19970+
has_gc_arg = 19971+
end9972+
ak = ak + 19973+
end9974+
if has_gc_arg == 19975+
tmp = new_temp9976+
emit(" " + c_type(recv_type) + " " + tmp + " = " + rc + ";")9977+
emit(" SP_GC_ROOT(" + tmp + ");")9978+
rc = tmp9979+
end9980+
end9981+
end93929982
93939983
# StringIO methods93949984
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 unboxing10359+
ret_type = ""10360+
if @nd_type[recv] == "LocalVariableReadNode"10361+
ret_type = lambda_var_ret_type(@nd_name[recv])10362+
end10363+
if mname == "[]" || mname == "call"10364+
call_expr = ""976910365
args_id = @nd_arguments[nid]977010366
if args_id >= 0977110367
aargs = get_args(args_id)977210368
if aargs.length > 0977310369
ac = wrap_as_sp_val(aargs.first)9774-
return "sp_lam_call(" + rc + ", " + ac + ")"10370+
call_expr = "sp_lam_call(" + rc + ", " + ac + ")"977510371
end977610372
end9777-
return "sp_lam_call(" + rc + ", &sp_lam_nil_val)"9778-
end9779-
if mname == "call"9780-
args_id = @nd_arguments[nid]9781-
if args_id >= 09782-
aargs = get_args(args_id)9783-
if aargs.length > 09784-
ac = wrap_as_sp_val(aargs.first)9785-
return "sp_lam_call(" + rc + ", " + ac + ")"9786-
end10373+
if call_expr == ""10374+
call_expr = "sp_lam_call(" + rc + ", &sp_lam_nil_val)"978710375
end9788-
return "sp_lam_call(" + rc + ", &sp_lam_nil_val)"10376+
return lam_unbox(call_expr, ret_type)978910377
end979010378
""979110379
end@@ -10732,6 +11320,22 @@
1073211320
return "sp_FloatArray_length(" + rc + ")"1073311321
end1073411322
end11323+
if is_ptr_array_type(recv_type) == 111324+
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+
end11329+
if mname == "[]"11330+
return "(" + ct + ")sp_PtrArray_get(" + rc + ", " + compile_arg0(nid) + ")"11331+
end11332+
if mname == "push"11333+
return "(sp_PtrArray_push(" + rc + ", " + compile_arg0(nid) + "), 0)"11334+
end11335+
if mname == "empty?"11336+
return "sp_PtrArray_empty(" + rc + ")"11337+
end11338+
end1073511339
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 calls1117611780
if is_obj_type(recv_type) == 111177-
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 >= 01118011785
arrow = "->"@@ -11409,6 +12014,28 @@
1140912014
"sp_box_int(" + val + ")"1141012015
end1141112016
12017+
def box_val_to_poly(val, at)12018+
if at == "poly"12019+
return val12020+
end12021+
if at == "int"12022+
return "sp_box_int(" + val + ")"12023+
end12024+
if at == "string"12025+
return "sp_box_str(" + val + ")"12026+
end12027+
if at == "float"12028+
return "sp_box_float(" + val + ")"12029+
end12030+
if at == "bool"12031+
return "sp_box_bool(" + val + ")"12032+
end12033+
if at == "nil"12034+
return "sp_box_nil()"12035+
end12036+
"sp_box_int(" + val + ")"12037+
end12038+
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
end1161212239
arg_ids = get_args(args_id)12240+
# Check if multiple args may trigger GC12241+
gc_count = 012242+
k = 012243+
while k < arg_ids.length12244+
if expr_may_gc(arg_ids[k]) == 112245+
gc_count = gc_count + 112246+
end12247+
k = k + 112248+
end12249+
if gc_count >= 212250+
return compile_gc_safe_args(arg_ids)12251+
end1161312252
result = ""1161412253
k = 01161512254
while k < arg_ids.length@@ -11622,6 +12261,36 @@
1162212261
result1162312262
end1162412263
12264+
def compile_gc_safe_args(arg_ids)12265+
temps = "".split(",")12266+
k = 012267+
while k < arg_ids.length12268+
if expr_may_gc(arg_ids[k]) == 112269+
tmp = new_temp12270+
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) == 112274+
emit(" SP_GC_ROOT(" + tmp + ");")12275+
end12276+
temps.push(tmp)12277+
else12278+
temps.push(compile_expr(arg_ids[k]))12279+
end12280+
k = k + 112281+
end12282+
result = ""12283+
k = 012284+
while k < temps.length12285+
if k > 012286+
result = result + ", "12287+
end12288+
result = result + temps[k]12289+
k = k + 112290+
end12291+
result12292+
end12293+
1162512294
def compile_typed_call_args(nid, target_ci, target_midx)1162612295
# Like compile_call_args but casts arguments to match target method param types1162712296
args_id = @nd_arguments[nid]@@ -11864,64 +12533,81 @@
1186412533
end1186512534
end1186612535
end12536+
vref = fiber_var_ref(lname)1186712537
vt = find_var_type(lname)12538+
# ptr_array: empty array literal should create PtrArray12539+
if is_ptr_array_type(vt) == 112540+
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 == 012544+
@needs_ptr_array = 112545+
@needs_gc = 112546+
emit(" " + vref + " = sp_PtrArray_new();")12547+
return12548+
end12549+
end12550+
end1186812551
if vt == "poly"1186912552
# Box the value11870-
emit(" lv_" + lname + " = " + box_expr_to_poly(@nd_expression[nid]) + ";")12553+
emit(" " + vref + " = " + box_expr_to_poly(@nd_expression[nid]) + ";")1187112554
return1187212555
end1187312556
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
else11879-
emit(" lv_" + lname + " = " + val + ";")12562+
emit(" " + vref + " = " + val + ";")1188012563
end1188112564
return1188212565
end1188312566
rhs_t = infer_type(@nd_expression[nid])1188412567
if rhs_t == "nil" && is_nullable_type(vt) == 111885-
emit(" lv_" + lname + " = NULL;")12568+
emit(" " + vref + " = NULL;")1188612569
else1188712570
val = compile_expr(@nd_expression[nid])11888-
emit(" lv_" + lname + " = " + val + ";")12571+
emit(" " + vref + " = " + val + ";")12572+
end12573+
if rhs_t != "nil" || is_nullable_type(vt) == 012574+
set_var_type(lname, rhs_t)1188912575
end11890-
set_var_type(lname, rhs_t)1189112576
return1189212577
end1189312578
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
end1189912585
if op == "-"11900-
emit(" lv_" + @nd_name[nid] + " -= " + val + ";")12586+
emit(" " + vref + " -= " + val + ";")1190112587
end1190212588
if op == "*"11903-
emit(" lv_" + @nd_name[nid] + " *= " + val + ";")12589+
emit(" " + vref + " *= " + val + ";")1190412590
end1190512591
if op == "/"11906-
emit(" lv_" + @nd_name[nid] + " /= " + val + ";")12592+
emit(" " + vref + " /= " + val + ";")1190712593
end1190812594
if op == "%"11909-
emit(" lv_" + @nd_name[nid] + " = sp_imod(lv_" + @nd_name[nid] + ", " + val + ");")12595+
emit(" " + vref + " = sp_imod(" + vref + ", " + val + ");")1191012596
end1191112597
if op == "<<"11912-
emit(" lv_" + @nd_name[nid] + " <<= " + val + ";")12598+
emit(" " + vref + " <<= " + val + ";")1191312599
end1191412600
if op == ">>"11915-
emit(" lv_" + @nd_name[nid] + " >>= " + val + ";")12601+
emit(" " + vref + " >>= " + val + ";")1191612602
end1191712603
if op == "&"11918-
emit(" lv_" + @nd_name[nid] + " &= " + val + ";")12604+
emit(" " + vref + " &= " + val + ";")1191912605
end1192012606
if op == "|"11921-
emit(" lv_" + @nd_name[nid] + " |= " + val + ";")12607+
emit(" " + vref + " |= " + val + ";")1192212608
end1192312609
if op == "^"11924-
emit(" lv_" + @nd_name[nid] + " ^= " + val + ";")12610+
emit(" " + vref + " ^= " + val + ";")1192512611
end1192612612
return1192712613
end@@ -12059,7 +12745,7 @@
1205912745
if k < tmps.length1206012746
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
end1206412750
if @nd_type[tid] == "InstanceVariableTargetNode"1206512751
iname = @nd_name[tid]@@ -12098,7 +12784,7 @@
1209812784
while k < targets.length1209912785
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
end1210312789
k = k + 11210412790
end@@ -13195,14 +13881,27 @@
1319513881
end1319613882
return1319713883
end13198-
# Collect local writes as locals13884+
# Collect local writes — scan expression first to detect reads before the write1319913885
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] >= 013889+
scan_lambda_free_vars(@nd_expression[nid], params, locals, free_vars)13890+
end1320113891
if not_in(vn, locals) == 11320213892
if not_in(vn, params) == 113203-
locals.push(vn)13893+
if not_in(vn, free_vars) == 113894+
# Check if variable exists in outer scope — if so, it's a free var13895+
outer_t = find_var_type(vn)13896+
if outer_t != ""13897+
free_vars.push(vn)13898+
else13899+
locals.push(vn)13900+
end13901+
end1320413902
end1320513903
end13904+
return1320613905
end1320713906
# Recurse1320813907
if @nd_body[nid] >= 0@@ -13258,45 +13957,195 @@
1325813957
end1325913958
end1326013959
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 lambda13965+
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 return13973+
mn = @nd_name[expr]13974+
mi = find_method_idx(mn)13975+
if mi >= 013976+
bid = @meth_body_ids[mi]13977+
if bid >= 013978+
mbs = get_stmts(bid)13979+
if mbs.length > 013980+
last = mbs.last13981+
if @nd_type[last] == "LambdaNode"13982+
lbody = @nd_body[last]13983+
if lbody >= 013984+
lbs = get_stmts(lbody)13985+
if lbs.length > 013986+
lrt = infer_type(lbs.last)13987+
if not_in(vn, @lambda_var_ret_names) == 113988+
@lambda_var_ret_names.push(vn)13989+
@lambda_var_ret_types.push(lrt)13990+
end13991+
end13992+
end13993+
end13994+
end13995+
end13996+
end13997+
end13998+
end13999+
end14000+
}14001+
end14002+
14003+
def scan_lambda_ret_types_node(nid)1326514004
if nid < 013266-
return "&sp_lam_nil_val"14005+
return1326714006
end1326814007
t = @nd_type[nid]13269-
if t == "LocalVariableReadNode"13270-
vn = @nd_name[nid]13271-
# Check param13272-
if not_in(vn, params) == 013273-
return "lv_" + vn13274-
end13275-
# Check captures13276-
ci = 013277-
while ci < captures.length13278-
if captures[ci] == vn13279-
return "self->captures[" + ci.to_s + "]"13280-
end13281-
ci = ci + 113282-
end13283-
return "lv_" + vn13284-
end1328514008
if t == "LocalVariableWriteNode"1328614009
vn = @nd_name[nid]13287-
val = compile_lambda_body_expr(@nd_expression[nid], params, captures)13288-
# Check if capture13289-
ci = 013290-
while ci < captures.length13291-
if captures[ci] == vn13292-
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 >= 014014+
lbs = get_stmts(lbody)14015+
if lbs.length > 014016+
lrt = infer_type(lbs.last)14017+
if not_in(vn, @lambda_var_ret_names) == 114018+
@lambda_var_ret_names.push(vn)14019+
@lambda_var_ret_types.push(lrt)14020+
end14021+
end1329314022
end13294-
ci = ci + 11329514023
end13296-
emit(" sp_Val *lv_" + vn + " = " + val + ";")13297-
return "lv_" + vn14024+
scan_lambda_ret_types_node(expr)1329814025
end13299-
if t == "IntegerNode"14026+
# Scan into method bodies to find lambdas returned from methods14027+
if t == "DefNode"14028+
if @nd_body[nid] >= 014029+
scan_lambda_ret_types_node(@nd_body[nid])14030+
end14031+
return14032+
end14033+
if @nd_body[nid] >= 014034+
scan_lambda_ret_types_node(@nd_body[nid])14035+
end14036+
if @nd_expression[nid] >= 014037+
scan_lambda_ret_types_node(@nd_expression[nid])14038+
end14039+
ss = parse_id_list(@nd_stmts[nid])14040+
k = 014041+
while k < ss.length14042+
scan_lambda_ret_types_node(ss[k])14043+
k = k + 114044+
end14045+
end14046+
14047+
def lambda_var_ret_type(vname)14048+
i = 014049+
while i < @lambda_var_ret_names.length14050+
if @lambda_var_ret_names[i] == vname14051+
return @lambda_var_ret_types[i]14052+
end14053+
i = i + 114054+
end14055+
""14056+
end14057+
14058+
def lam_box(expr, vtype)14059+
bt = base_type(vtype)14060+
if bt == "string"14061+
return "sp_lam_int((mrb_int)" + expr + ")"14062+
end14063+
if bt == "float"14064+
return "sp_lam_int(*(mrb_int*)&(mrb_float){" + expr + "})"14065+
end14066+
if bt == "bool"14067+
return "sp_lam_bool(" + expr + ")"14068+
end14069+
if bt == "nil" || bt == "void"14070+
return "&sp_lam_nil_val"14071+
end14072+
"sp_lam_int(" + expr + ")"14073+
end14074+
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+
end14080+
if bt == "float"14081+
return "*(mrb_float*)&(mrb_int){sp_lam_to_int(" + expr + ")}"14082+
end14083+
if bt == "bool"14084+
return "(" + expr + ")->u.bval"14085+
end14086+
if bt == "nil" || bt == "void"14087+
return "(sp_lam_to_int(" + expr + "), 0)"14088+
end14089+
"sp_lam_to_int(" + expr + ")"14090+
end14091+
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 < 014097+
return "&sp_lam_nil_val"14098+
end14099+
t = @nd_type[nid]14100+
if t == "LocalVariableReadNode"14101+
vn = @nd_name[nid]14102+
# Check param14103+
if not_in(vn, params) == 014104+
return "lv_" + vn14105+
end14106+
# Check captures14107+
ci = 014108+
while ci < captures.length14109+
if captures[ci] == vn14110+
ct = ""14111+
if ci < @lambda_capture_cell_types.length14112+
ct = @lambda_capture_cell_types[ci]14113+
end14114+
if ct != ""14115+
# Typed cell capture: dereference and box14116+
deref = "*(" + c_type(ct) + "*)self->captures[" + ci.to_s + "]"14117+
return lam_box(deref, ct)14118+
end14119+
return "self->captures[" + ci.to_s + "]"14120+
end14121+
ci = ci + 114122+
end14123+
return "lv_" + vn14124+
end14125+
if t == "LocalVariableWriteNode"14126+
vn = @nd_name[nid]14127+
val = compile_lambda_body_expr(@nd_expression[nid], params, captures)14128+
# Check if capture14129+
ci = 014130+
while ci < captures.length14131+
if captures[ci] == vn14132+
ct = ""14133+
if ci < @lambda_capture_cell_types.length14134+
ct = @lambda_capture_cell_types[ci]14135+
end14136+
if ct != ""14137+
# Typed cell capture: unbox and store14138+
cptr = "*(" + c_type(ct) + "*)self->captures[" + ci.to_s + "]"14139+
return "(" + cptr + " = " + lam_unbox(val, ct) + ", " + val + ")"14140+
end14141+
return "(self->captures[" + ci.to_s + "] = " + val + ")"14142+
end14143+
ci = ci + 114144+
end14145+
emit(" sp_Val *lv_" + vn + " = " + val + ";")14146+
return "lv_" + vn14147+
end14148+
if t == "IntegerNode"1330014149
return "sp_lam_int(" + @nd_value[nid].to_s + ")"1330114150
end1330214151
if t == "TrueNode"@@ -13458,23 +14307,160 @@
1345814307
@lambda_counter = @lambda_counter + 11345914308
fname = "_lam_" + lam_id.to_s1346014309
14310+
# Compute capture cell types (before body compilation)14311+
cap_cell_types = "".split(",")14312+
k = 014313+
while k < free_vars.length14314+
fv = free_vars[k]14315+
cell = heap_promoted_cell(fv)14316+
if cell == "" && @in_fiber_body == 1 && fiber_capture_index(fv) >= 014317+
cell = "_cap->" + fv14318+
end14319+
# Regular locals will be heap-promoted (not lambda params/captures)14320+
if cell == "" && not_in(fv, @lambda_params) == 114321+
is_enclosing_cap = 014322+
ci = 014323+
while ci < @lambda_captures.length14324+
if @lambda_captures[ci] == fv14325+
is_enclosing_cap = 114326+
end14327+
ci = ci + 114328+
end14329+
if is_enclosing_cap == 014330+
vt = find_var_type(fv)14331+
if vt != "" && vt != "lambda"14332+
cell = "will_promote"14333+
end14334+
end14335+
end14336+
if cell != ""14337+
cap_cell_types.push(find_var_type(fv))14338+
else14339+
cap_cell_types.push("")14340+
end14341+
k = k + 114342+
end14343+
14344+
# Check if we have typed cell captures (need regular compiler path)14345+
has_typed_caps = 014346+
k = 014347+
while k < cap_cell_types.length14348+
if cap_cell_types[k] != ""14349+
has_typed_caps = 114350+
end14351+
k = k + 114352+
end14353+
1346114354
# Get body expression1346214355
bexpr = "&sp_lam_nil_val"1346314356
if body >= 01346414357
bs = get_stmts(body)13465-
if bs.length > 013466-
# Save current output and context, compile body into lambda function14358+
if bs.length > 0 && has_typed_caps == 114359+
# Typed captures: compile body using regular compiler14360+
save_out = @out14361+
save_indent = @indent14362+
save_hp_names_len = @heap_promoted_names.length14363+
save_hp_cells_len = @heap_promoted_cells.length14364+
@out = ""14365+
@indent = 114366+
14367+
push_scope14368+
# Declare parameter with proper type14369+
if pname != ""14370+
ptype = infer_type(bs.last)14371+
if ptype == ""14372+
ptype = "int"14373+
end14374+
declare_var(pname, "int")14375+
end14376+
# Set up cell pointer locals for typed captures14377+
k = 014378+
while k < free_vars.length14379+
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+
end14387+
k = k + 114388+
end14389+
# Declare body-local variables14390+
lnames = "".split(",")14391+
ltypes = "".split(",")14392+
excl = "".split(",")14393+
if pname != ""14394+
excl.push(pname)14395+
end14396+
k = 014397+
while k < free_vars.length14398+
excl.push(free_vars[k])14399+
k = k + 114400+
end14401+
scan_locals(body, lnames, ltypes, excl)14402+
lk = 014403+
while lk < lnames.length14404+
declare_var(lnames[lk], ltypes[lk])14405+
emit(" " + c_type(ltypes[lk]) + " lv_" + lnames[lk] + " = " + c_default_val(ltypes[lk]) + ";")14406+
lk = lk + 114407+
end14408+
# Compile body statements14409+
i = 014410+
while i < bs.length - 114411+
compile_stmt(bs[i])14412+
i = i + 114413+
end14414+
last = bs.last14415+
last_type = infer_type(last)14416+
if @nd_type[last] == "LocalVariableWriteNode" || @nd_type[last] == "LocalVariableOperatorWriteNode"14417+
compile_stmt(last)14418+
end14419+
last_val = compile_expr(last)14420+
14421+
pop_scope14422+
body_stmts = @out14423+
@out = save_out14424+
@indent = save_indent14425+
# Restore heap promoted14426+
while @heap_promoted_names.length > save_hp_names_len14427+
@heap_promoted_names.pop14428+
end14429+
while @heap_promoted_cells.length > save_hp_cells_len14430+
@heap_promoted_cells.pop14431+
end14432+
14433+
# Build lambda function with typed body14434+
@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+
end14438+
@lambda_funcs = @lambda_funcs + body_stmts + 10.chr14439+
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 > 014443+
# No typed captures: use sp_Val* lambda body compiler1346714444
save_out = @out1346814445
save_params = @lambda_params1346914446
save_captures = @lambda_captures14447+
save_cell_types = @lambda_capture_cell_types1347014448
@out = ""1347114449
@lambda_params = param_arr1347214450
@lambda_captures = free_vars14451+
@lambda_capture_cell_types = cap_cell_types14452+
si = 014453+
while si < bs.length - 114454+
side_expr = compile_lambda_body_expr(bs[si], param_arr, free_vars)14455+
emit(" " + side_expr + ";")14456+
si = si + 114457+
end1347314458
bexpr = compile_lambda_body_expr(bs.last, param_arr, free_vars)1347414459
body_stmts = @out1347514460
@out = save_out1347614461
@lambda_params = save_params1347714462
@lambda_captures = save_captures14463+
@lambda_capture_cell_types = save_cell_types1347814464
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 expression1350514491
if free_vars.length > 014492+
# Heap-promote regular locals that need cell captures14493+
k = 014494+
while k < free_vars.length14495+
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 context14498+
if @in_fiber_body == 0 || fiber_capture_index(fv) < 014499+
if not_in(fv, @heap_promoted_names) == 114500+
ct = c_type(cap_cell_types[k])14501+
cell = "_hcell_" + fv + "_l" + lam_id.to_s14502+
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+
end14507+
end14508+
end14509+
k = k + 114510+
end1350614511
tmp = new_temp1350714512
emit(" sp_Val *" + tmp + " = sp_lam_proc(" + fname + ", " + free_vars.length.to_s + ");")1350814513
k = 01350914514
while k < free_vars.length13510-
# Resolve the free variable reference in the enclosing context1351114515
fv = free_vars[k]13512-
fv_ref = "lv_" + fv13513-
# Check if it's a param of enclosing lambda13514-
if not_in(fv, @lambda_params) == 013515-
fv_ref = "lv_" + fv14516+
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) >= 014520+
cell = "_cap->" + fv14521+
end14522+
emit(" " + tmp + "->captures[" + k.to_s + "] = (sp_Val*)" + cell + ";")1351614523
else13517-
# Check if it's a capture of enclosing lambda13518-
ci = 013519-
while ci < @lambda_captures.length13520-
if @lambda_captures[ci] == fv13521-
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 = 014526+
if not_in(fv, @lambda_params) == 014527+
is_lam_ctx = 114528+
emit(" " + tmp + "->captures[" + k.to_s + "] = lv_" + fv + ";")14529+
else14530+
ci = 014531+
while ci < @lambda_captures.length14532+
if @lambda_captures[ci] == fv14533+
is_lam_ctx = 114534+
emit(" " + tmp + "->captures[" + k.to_s + "] = self->captures[" + ci.to_s + "];")14535+
end14536+
ci = ci + 114537+
end14538+
end14539+
if is_lam_ctx == 014540+
# Regular local: should have been heap-promoted already14541+
cell = heap_promoted_cell(fv)14542+
if cell != ""14543+
emit(" " + tmp + "->captures[" + k.to_s + "] = (sp_Val*)" + cell + ";")14544+
else14545+
emit(" " + tmp + "->captures[" + k.to_s + "] = " + fiber_var_ref(fv) + ";")1352214546
end13523-
ci = ci + 11352414547
end1352514548
end13526-
emit(" " + tmp + "->captures[" + k.to_s + "] = " + fv_ref + ";")1352714549
k = k + 11352814550
end1352914551
return tmptest/bm_fannkuch.rbaddedView file
Loading diff…
test/bm_fiber.rbmodifiedView file
Loading diff…
test/bm_nbody.rbaddedView file
Loading diff…
test/bm_spectral_norm.rbaddedView file
Loading diff…