Commit 80ca6528

80ca65280a02Merged

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

Description

feat: Fiber support (cooperative concurrency via ucontext)

Implements Ruby's Fiber API:

  • Fiber.new { block } — create fiber with block
  • fiber.resume(val) — resume fiber, pass value
  • Fiber.yield(val) — suspend fiber, return value

Uses POSIX ucontext_t (makecontext/swapcontext) for stack switching. Each fiber gets a 64KB mmap'd stack. Fibers are GC-allocated with finalizer to unmap stack.

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

Details

Commit
80ca65280a02
Parent
690abf0987cc

spinel_codegen.rbmodifiedView file

@@ -148,6 +148,11 @@
148148 @lambda_params = "".split(",")
149149 @lambda_captures = "".split(",")
150150
151+ # Fiber support
152+ @needs_fiber = 0
153+ @fiber_counter = 0
154+ @fiber_funcs = ""
155+
151156 # Poly tracking: functions with params called with different types
152157 @poly_funcs = "".split(",")
153158 @poly_param_types = "".split(",")
@@ -1104,6 +1109,28 @@
11041109 if @nd_name[recv] == "Proc"
11051110 return "proc"
11061111 end
1112+ if @nd_name[recv] == "Fiber"
1113+ return "fiber"
1114+ end
1115+ end
1116+ end
1117+ end
1118+ # fiber.resume returns int
1119+ if mname == "resume"
1120+ if recv >= 0
1121+ rt = infer_type(recv)
1122+ if rt == "fiber"
1123+ return "int"
1124+ end
1125+ end
1126+ end
1127+ # Fiber.yield returns int
1128+ if mname == "yield"
1129+ if recv >= 0
1130+ if @nd_type[recv] == "ConstantReadNode"
1131+ if @nd_name[recv] == "Fiber"
1132+ return "int"
1133+ end
11071134 end
11081135 end
11091136 end
@@ -1688,6 +1715,9 @@
16881715 if rn == "StringIO"
16891716 return "stringio"
16901717 end
1718+ if rn == "Fiber"
1719+ return "fiber"
1720+ end
16911721 return "obj_" + rn
16921722 end
16931723 end
@@ -1730,6 +1760,11 @@
17301760 if recv >= 0
17311761 if @nd_type[recv] == "ConstantReadNode"
17321762 rcname = @nd_name[recv]
1763+ if rcname == "Fiber"
1764+ if mname == "new"
1765+ return "fiber"
1766+ end
1767+ end
17331768 ci2 = find_class_idx(rcname)
17341769 if ci2 >= 0
17351770 if mname == "new"
@@ -2031,6 +2066,9 @@
20312066 if t == "mutable_str"
20322067 return 1
20332068 end
2069+ if t == "fiber"
2070+ return 1
2071+ end
20342072 if is_obj_type(t) == 1
20352073 cname = t[4, t.length - 4]
20362074 ci = find_class_idx(cname)
@@ -2132,6 +2170,9 @@
21322170 if t == "str_str_hash"
21332171 return "sp_StrStrHash *"
21342172 end
2173+ if t == "fiber"
2174+ return "sp_Fiber *"
2175+ end
21352176 if t == "poly"
21362177 return "sp_RbVal"
21372178 end
@@ -5328,6 +5369,24 @@
53285369 if mname == "raise"
53295370 @needs_setjmp = 1
53305371 end
5372+ if mname == "new"
5373+ if @nd_receiver[nid] >= 0
5374+ if @nd_type[@nd_receiver[nid]] == "ConstantReadNode"
5375+ if @nd_name[@nd_receiver[nid]] == "Fiber"
5376+ @needs_fiber = 1
5377+ end
5378+ end
5379+ end
5380+ end
5381+ if mname == "yield"
5382+ if @nd_receiver[nid] >= 0
5383+ if @nd_type[@nd_receiver[nid]] == "ConstantReadNode"
5384+ if @nd_name[@nd_receiver[nid]] == "Fiber"
5385+ @needs_fiber = 1
5386+ end
5387+ end
5388+ end
5389+ end
53315390 if mname == "catch"
53325391 @needs_setjmp = 1
53335392 end
@@ -6077,6 +6136,13 @@
60776136 if @needs_lambda == 1
60786137 emit_lambda_runtime
60796138 end
6139+ if @needs_fiber == 1
6140+ if @needs_gc == 0
6141+ @needs_gc = 1
6142+ emit_gc_runtime
6143+ end
6144+ emit_fiber_runtime
6145+ end
60806146 emit_class_structs
60816147 emit_gc_scan_functions
60826148 emit_forward_decls
@@ -6522,6 +6588,21 @@
65226588 emit_raw("")
65236589 end
65246590
6591+ def emit_fiber_runtime
6592+ emit_raw("/* ---- Fiber runtime (ucontext) ---- */")
6593+ emit_raw("#include <ucontext.h>")
6594+ emit_raw("#include <sys/mman.h>")
6595+ 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;")
6598+ 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+
65256606 def emit_stringio_runtime
65266607 emit_raw("/* ---- StringIO runtime ---- */")
65276608 emit_raw("typedef struct { char *buf; int64_t len; int64_t cap; int64_t pos; int64_t lineno; int closed; } sp_StringIO;")
@@ -6997,7 +7078,7 @@
69977078 if @needs_mutable_str == 1 || @needs_stringio == 1
69987079 @needs_gc = 1
69997080 end
7000- if @needs_rb_value == 1 || @needs_lambda == 1
7081+ if @needs_rb_value == 1 || @needs_lambda == 1 || @needs_fiber == 1
70017082 @needs_gc = 1
70027083 end
70037084 end
@@ -8606,9 +8687,16 @@
86068687 pop_scope
86078688 @in_main = 0
86088689
8609- # Insert lambda functions before main
8690+ # Insert lambda and fiber functions before main
8691+ inserted = ""
86108692 if @lambda_funcs != ""
8611- @out = @out[0, @lambda_insert_pos] + @lambda_funcs + @out[@lambda_insert_pos, @out.length - @lambda_insert_pos]
8693+ inserted = inserted + @lambda_funcs
8694+ end
8695+ if @fiber_funcs != ""
8696+ inserted = inserted + @fiber_funcs
8697+ end
8698+ if inserted != ""
8699+ @out = @out[0, @lambda_insert_pos] + inserted + @out[@lambda_insert_pos, @out.length - @lambda_insert_pos]
86128700 end
86138701 end
86148702
@@ -9135,10 +9223,126 @@
91359223 end
91369224
91379225
9226+ def compile_fiber_new(nid)
9227+ @needs_fiber = 1
9228+ blk = @nd_block[nid]
9229+ if blk < 0
9230+ return "NULL"
9231+ end
9232+ # Get block parameter name
9233+ bp = ""
9234+ bparams = @nd_parameters[blk]
9235+ if bparams >= 0
9236+ # BlockParametersNode → inner ParametersNode
9237+ inner = @nd_parameters[bparams]
9238+ if inner >= 0
9239+ reqs = parse_id_list(@nd_requireds[inner])
9240+ if reqs.length > 0
9241+ bp = @nd_name[reqs[0]]
9242+ end
9243+ end
9244+ if bp == ""
9245+ # Try direct requireds (in case it's ParametersNode directly)
9246+ reqs = parse_id_list(@nd_requireds[bparams])
9247+ if reqs.length > 0
9248+ bp = @nd_name[reqs[0]]
9249+ end
9250+ end
9251+ end
9252+ fid = @fiber_counter
9253+ @fiber_counter = @fiber_counter + 1
9254+ fname = "_fiber_body_" + fid.to_s
9255+
9256+ # Compile fiber body function
9257+ fbody = "static void " + fname + "(sp_Fiber *_fb) {" + 10.chr
9258+ 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")
9270+ end
9271+ body = @nd_body[blk]
9272+ 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
9299+ end
9300+ pop_scope
9301+
9302+ fbody = fbody + @out
9303+ fbody = fbody + "}" + 10.chr
9304+ @fiber_funcs = @fiber_funcs + fbody
9305+
9306+ @out = saved_out
9307+ @indent = saved_indent
9308+
9309+ # Declare locals in body (scan for LocalVariableWriteNode)
9310+ # Actually the above compile already handles this via the saved @out
9311+
9312+ # Return fiber creation expression
9313+ "sp_Fiber_new(" + fname + ")"
9314+ end
9315+
91389316 def compile_call_expr(nid)
91399317 mname = @nd_name[nid]
91409318 recv = @nd_receiver[nid]
91419319
9320+ # Fiber.new { block }
9321+ if mname == "new" && recv >= 0
9322+ if @nd_type[recv] == "ConstantReadNode"
9323+ if @nd_name[recv] == "Fiber"
9324+ return compile_fiber_new(nid)
9325+ end
9326+ end
9327+ end
9328+ # fiber.resume(val)
9329+ if mname == "resume" && recv >= 0
9330+ rt2 = infer_type(recv)
9331+ if rt2 == "fiber"
9332+ rc = compile_expr(recv)
9333+ val = compile_arg0(nid)
9334+ return "sp_Fiber_resume(" + rc + ", " + val + ")"
9335+ end
9336+ end
9337+ # Fiber.yield(val)
9338+ if mname == "yield" && recv >= 0
9339+ if @nd_type[recv] == "ConstantReadNode"
9340+ if @nd_name[recv] == "Fiber"
9341+ return "sp_Fiber_yield(" + compile_arg0(nid) + ")"
9342+ end
9343+ end
9344+ end
9345+
91429346 # No receiver
91439347 if recv < 0
91449348 return compile_no_recv_call_expr(nid, mname)