Commit ef05cb1a
ef05cb1aa590Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 11 files · +10 added · ~1 modified
Description
Merge pull request #312 from matz/pr/bound-method-v2
feat(codegen): heap-allocated Method objects (re-implementation of #215)
Details
- Commit
- ef05cb1aa590
- Parent
- c958bb1fcd4f
- Merge parent
- 7e7aa4667cf4
spinel_codegen.rbmodifiedView file
@@ -2573,9 +2573,35 @@
25732573
end25742574
return "int"25752575
end2576+
# Method#call / Method#[]: the C-level signature lowers to2577+
# `(void *self, mrb_int...) -> mrb_int`, so the inferred2578+
# return is `int`. Non-int returns (string, obj, etc.) from2579+
# the bound underlying method are out of scope. Ref #215.2580+
if rt == "obj_Method"2581+
return "int"2582+
end25762583
end25772584
end25782585
2586+
# `method(:foo)` produces a heap-allocated Method (the synthetic2587+
# class registered in register_builtin_classes). Two captured2588+
# forms produce a real Method:2589+
# - no receiver, inside a class body → bound to `self`.2590+
# - obj-typed receiver (e.g. `@foo.method(:bar)`) → bound to2591+
# the inferred receiver, regardless of where the call sits.2592+
# Top-level `method(:foo)` with no receiver keeps the legacy2593+
# static-alias placeholder; LocalVariableWriteNode then records2594+
# the binding and `m.call(x)` rewrites to a direct `sp_<foo>(x)`2595+
# call. Ref #215.2596+
if mname == "method"2597+
if recv < 0 && @current_class_idx >= 02598+
return "obj_Method"2599+
end2600+
if recv >= 0 && is_obj_type(infer_type(recv)) == 12601+
return "obj_Method"2602+
end2603+
end2604+
25792605
# `obj.attr = val` (attr-writer call) — Ruby semantics: the25802606
# assignment expression evaluates to the rhs value, so the25812607
# inferred type is the rhs argument's type. Without this, a@@ -5616,6 +5642,13 @@
56165642
collect_class(sid)56175643
end56185644
}5645+
# Pass 1.3: synthetic built-in classes (Method). Appended AFTER5646+
# user classes so existing user-class indices don't shift; the5647+
# poly-dispatch BUILTIN_PTR_ARRAY branch in5648+
# emit_poly_builtin_dispatch assumes `cls_id 0` is the first user5649+
# class and would silently misroute every poly call if Method5650+
# took that slot. Ref #215.5651+
register_builtin_classes56195652
# Pass 1.4: register class variables (@@var). Walks each class56205653
# body for any ClassVariable*WriteNode (Write, Operator, Or, And,56215654
# Target) and records the inferred type per (class, name). The@@ -8759,6 +8792,55 @@
87598792
@multi_const_inits.push(scope_name + "|" + nid.to_s)87608793
end87618794
8795+
# Synthetic built-in user class for `method(:foo)` capture: every8796+
# `m = method(:foo)` / `obj.method(:foo)` produces an instance of8797+
# this class, allocated by sp_Method_new and walked by the auto-8798+
# generated sp_Method_gc_scan. Ref #215.8799+
#8800+
# The two ivars:8801+
# - `@self_obj` typed `obj_Method`. Load-bearing hack: this type8802+
# makes ivar_is_gc_ptr true, which makes the auto-generated gc8803+
# scanner emit `sp_gc_mark(self->iv_self_obj)`. The actual8804+
# captured pointer is the bound receiver (any user class), cast8805+
# to `sp_Method *`. sp_gc_mark dispatches via the GC header's8806+
# `scan` field — set at the *bound receiver's* allocation time —8807+
# not via the static pointer type, so the cast is safe at the8808+
# GC level even though it's a type lie at the C level.8809+
# detect_method_taken_classes excludes the bound receiver's8810+
# class from value-type optimization so the captured pointer8811+
# never dangles (value-type instances live on the caller's8812+
# stack and would be reclaimed when the binding method returns).8813+
# - `@fn_ptr` typed `int`. Holds `(uintptr_t)&sp_<DefCls>_<mname>`8814+
# reinterpreted as mrb_int (int64_t — wide enough on every8815+
# target). The Method.call/[] codegen in compile_call_expr casts8816+
# it back to a function pointer of the right shape.8817+
def register_builtin_classes8818+
@cls_names.push("Method")8819+
@cls_is_value_type.push(0)8820+
@cls_is_sra.push(0)8821+
@cls_parents.push("")8822+
@cls_ivar_names.push("@self_obj;@fn_ptr")8823+
@cls_ivar_types.push("obj_Method;int")8824+
@cls_ivar_init_definite.push("1;1")8825+
@cls_ivar_observed_types.push("obj_Method;int")8826+
@cls_meth_names.push("initialize")8827+
@cls_meth_params.push("self_obj,fn_ptr")8828+
@cls_meth_ptypes.push("obj_Method,int")8829+
@cls_meth_returns.push("void")8830+
@cls_meth_bodies.push("-2")8831+
@cls_meth_defaults.push("0,0")8832+
@cls_meth_ptypes_empty.push("")8833+
@cls_attr_readers.push("")8834+
@cls_attr_writers.push("")8835+
@cls_cmeth_names.push("")8836+
@cls_cmeth_params.push("")8837+
@cls_cmeth_ptypes.push("")8838+
@cls_cmeth_returns.push("")8839+
@cls_cmeth_bodies.push("")8840+
@cls_cmeth_defaults.push("")8841+
@cls_meth_has_yield.push("0")8842+
end8843+
87628844
def collect_struct_class(cname, call_nid)87638845
# Generate a synthetic class from Struct.new(:field1, :field2, ...)87648846
ci = @cls_names.length@@ -14996,6 +15078,146 @@
1499615078
end1499715079
end1499815080
15081+
# Build the set of class indices whose instances are captured by a15082+
# `method(:foo)` / `<obj>.method(:foo)` and end up stored in a15083+
# heap-allocated Method's `@self_obj`. Such classes must stay15084+
# heap-allocated — value-type optimization would put `self` on the15085+
# caller's stack, and the captured pointer would dangle when the15086+
# binding method returns. Ref #215.15087+
#15088+
# The walk needs scope set up so `infer_type` on a chained15089+
# `<recv>.method(:foo)` can resolve `<recv>` (a local, an ivar via15090+
# attr_reader, or a chained call) back to its `obj_<X>` type.15091+
def detect_method_taken_classes15092+
@method_taken_class_indices = "".split(",")15093+
# Walk class methods first.15094+
i = 015095+
while i < @cls_names.length15096+
mnames_str = @cls_meth_names[i]15097+
if mnames_str != ""15098+
mnames = mnames_str.split(";")15099+
all_params = @cls_meth_params[i].split("|")15100+
all_ptypes = @cls_meth_ptypes[i].split("|")15101+
bodies = @cls_meth_bodies[i].split(";")15102+
saved_ci = @current_class_idx15103+
@current_class_idx = i15104+
mi = 015105+
while mi < mnames.length15106+
if mi < bodies.length15107+
bid = bodies[mi].to_i15108+
if bid >= 015109+
pnames = ""15110+
ptypes = ""15111+
if mi < all_params.length15112+
pnames = all_params[mi]15113+
end15114+
if mi < all_ptypes.length15115+
ptypes = all_ptypes[mi]15116+
end15117+
method_taken_walk_with_scope(bid, pnames, ptypes, i)15118+
end15119+
end15120+
mi = mi + 115121+
end15122+
@current_class_idx = saved_ci15123+
end15124+
i = i + 115125+
end15126+
# Walk top-level methods.15127+
mi = 015128+
while mi < @meth_names.length15129+
bid = @meth_body_ids[mi]15130+
if bid >= 015131+
method_taken_walk_with_scope(bid, @meth_param_names[mi], @meth_param_types[mi], -1)15132+
end15133+
mi = mi + 115134+
end15135+
# Walk the top-level main script body too — `bm = make().method(:foo)`15136+
# at script scope must propagate the captured-receiver class into15137+
# the heap-stay set just like the same shape inside a method body.15138+
if @nd_type[@root_id] == "ProgramNode"15139+
stmts = get_body_stmts(@root_id)15140+
push_scope15141+
lnames = "".split(",")15142+
ltypes = "".split(",")15143+
sk = 015144+
while sk < stmts.length15145+
scan_locals(stmts[sk], lnames, ltypes, "".split(","))15146+
sk = sk + 115147+
end15148+
lk = 015149+
while lk < lnames.length15150+
declare_var(lnames[lk], ltypes[lk])15151+
lk = lk + 115152+
end15153+
sk = 015154+
while sk < stmts.length15155+
collect_method_taken(stmts[sk], -1)15156+
sk = sk + 115157+
end15158+
pop_scope15159+
end15160+
end15161+
15162+
def method_taken_walk_with_scope(bid, pnames_str, ptypes_str, enclosing_ci)15163+
push_scope15164+
pnames = pnames_str.split(",")15165+
ptypes = ptypes_str.split(",")15166+
k = 015167+
while k < pnames.length15168+
pt = "int"15169+
if k < ptypes.length15170+
pt = ptypes[k]15171+
end15172+
declare_var(pnames[k], pt)15173+
k = k + 115174+
end15175+
lnames = "".split(",")15176+
ltypes = "".split(",")15177+
scan_locals(bid, lnames, ltypes, pnames)15178+
lk = 015179+
while lk < lnames.length15180+
declare_var(lnames[lk], ltypes[lk])15181+
lk = lk + 115182+
end15183+
collect_method_taken(bid, enclosing_ci)15184+
pop_scope15185+
end15186+
15187+
def collect_method_taken(nid, enclosing_ci)15188+
if nid < 015189+
return15190+
end15191+
if @nd_type[nid] == "CallNode" && @nd_name[nid] == "method"15192+
args_id = @nd_arguments[nid]15193+
if args_id >= 015194+
a = get_args(args_id)15195+
if a.length >= 115196+
recv = @nd_receiver[nid]15197+
target = -115198+
if recv < 015199+
target = enclosing_ci15200+
else15201+
rt = infer_type(recv)15202+
if is_obj_type(rt) == 115203+
target = find_class_idx(rt[4, rt.length - 4])15204+
end15205+
end15206+
if target >= 0 && not_in(target.to_s, @method_taken_class_indices) == 115207+
@method_taken_class_indices.push(target.to_s)15208+
end15209+
end15210+
end15211+
end15212+
cs = []15213+
push_child_ids(nid, cs)15214+
k = 015215+
while k < cs.length15216+
collect_method_taken(cs[k], enclosing_ci)15217+
k = k + 115218+
end15219+
end15220+
1499915221
def recalc_needs_gc1500015222
# Recalculate @needs_gc: only needed if non-value-type classes are used1500115223
@needs_gc = 0@@ -15038,6 +15260,7 @@
1503815260
detect_param_mutated_types1503915261
detect_ptr_array_stored_types1504015262
detect_poly_returned_types15263+
detect_method_taken_classes1504115264
# Multiple passes: value type detection depends on other classes1504215265
2.times do1504315266
i = 0@@ -15119,7 +15342,18 @@
1511915342
pri = pri + 11512015343
end1512115344
end15345+
# Exclude classes whose instances are captured by a Method15346+
# (via `method(:foo)` on self, or `<obj>.method(:foo)` from15347+
# anywhere). The captured receiver must be a stable heap15348+
# pointer; value-type instances live on the caller's stack15349+
# and the pointer would dangle once the binding method15350+
# returns. Ref #215.1512215351
if all_val == 115352+
if not_in(i.to_s, @method_taken_class_indices) == 015353+
all_val = 015354+
end15355+
end15356+
if all_val == 11512315357
@cls_is_value_type[i] = 11512415358
end1512515359
end@@ -15177,6 +15411,18 @@
1517715411
mk = mk + 11517815412
end1517915413
end15414+
# Method-captured receivers must stay heap-allocated. SRA15415+
# explodes the instance into stack-resident scalars, which is15416+
# the same dangling-pointer hazard as value-type. Defensive:15417+
# current test corpus doesn't exercise an SRA-eligible class15418+
# (initialize + attr_* only) being captured, but a future15419+
# `class X; attr_accessor :n; end` followed by15420+
# `X.new(...).method(:n)` would. Ref #215.15421+
if eligible == 115422+
if not_in(i.to_s, @method_taken_class_indices) == 015423+
eligible = 015424+
end15425+
end1518015426
if eligible == 11518115427
@cls_is_sra[i] = 11518215428
end@@ -15720,6 +15966,29 @@
1572015966
-11572115967
end1572215968
15969+
# Walk the inheritance chain starting at class `ci` looking for the15970+
# first ancestor that defines `mname` directly. Returns that class's15971+
# name, or "" if no ancestor defines it. Used by the15972+
# `method(:foo)` codegen to build the C symbol of the bound function:15973+
# an inherited method's generated C function lives under the15974+
# *defining* class (`sp_Parent_foo`), not the receiver's own class15975+
# (`sp_Child_foo`), so `&sp_Child_foo` would be an unresolved symbol15976+
# at link time. When this returns "" the codegen falls back to a15977+
# null fn_ptr — Ruby's NoMethodError-on-invoke equivalent. Ref #215.15978+
def find_defining_class_name(ci, mname)15979+
walker = ci15980+
while walker >= 015981+
if cls_find_method_direct(walker, mname) >= 015982+
return @cls_names[walker]15983+
end15984+
if @cls_parents[walker] == ""15985+
return ""15986+
end15987+
walker = find_class_idx(@cls_parents[walker])15988+
end15989+
""15990+
end15991+
1572315992
def method_params_decl(mi)1572415993
mfullname = @meth_names[mi]1572515994
pnames = @meth_param_names[mi].split(",")@@ -19868,6 +20137,63 @@
1986820137
end1986920138
end1987020139
20140+
# `bm.call(args)` / `bm[args]` where bm is a Method instance —20141+
# lower to a function-pointer cast and an indirect call. The20142+
# bound function's C signature is20143+
# `(void *self, mrb_int...) -> mrb_int`. The receiver expression20144+
# is stashed in a temp first so a side-effecting receiver (e.g.20145+
# `factory().method(:foo).call(x)`) evaluates exactly once. Ref #215.20146+
if (mname == "call" || mname == "[]") && recv >= 020147+
if base_type(infer_type(recv)) == "obj_Method"20148+
rc = compile_expr(recv)20149+
bm_tmp = new_temp20150+
emit(" sp_Method *" + bm_tmp + " = " + rc + ";")20151+
args_id = @nd_arguments[nid]20152+
joined = ""20153+
sig_args = "void *"20154+
if args_id >= 020155+
aargs = get_args(args_id)20156+
k = 020157+
while k < aargs.length20158+
joined = joined + ", " + compile_expr(aargs[k])20159+
sig_args = sig_args + ", mrb_int"20160+
k = k + 120161+
end20162+
end20163+
return "((mrb_int (*)(" + sig_args + "))(uintptr_t)" + bm_tmp + "->iv_fn_ptr)((void *)" + bm_tmp + "->iv_self_obj" + joined + ")"20164+
end20165+
end20166+
20167+
# `<obj>.method(:bar)` — bind to a non-self receiver. The20168+
# detect_method_taken_classes pass keeps the receiver class20169+
# heap-allocated so `<obj>` evaluates to a stable pointer that20170+
# the resulting Method can capture. Walks the inheritance chain20171+
# to point at the *defining* class's C symbol; if no ancestor20172+
# defines the method, falls back to a null fn_ptr. Ref #215.20173+
if mname == "method" && recv >= 020174+
args_id = @nd_arguments[nid]20175+
if args_id >= 020176+
arg_ids = get_args(args_id)20177+
if arg_ids.length >= 120178+
recv_t = infer_type(recv)20179+
if is_obj_type(recv_t) == 120180+
mref = @nd_content[arg_ids[0]]20181+
if mref == ""20182+
mref = @nd_name[arg_ids[0]]20183+
end20184+
recv_cname = recv_t[4, recv_t.length - 4]20185+
owner_cname = find_defining_class_name(find_class_idx(recv_cname), mref)20186+
rc = compile_expr(recv)20187+
if owner_cname != ""20188+
return "sp_Method_new((sp_Method *)(" + rc + "), (mrb_int)(uintptr_t)&sp_" + owner_cname + "_" + sanitize_name(mref) + ")"20189+
else20190+
return "sp_Method_new((sp_Method *)(" + rc + "), (mrb_int)0)"20191+
end20192+
end20193+
end20194+
end20195+
end20196+
1987120197
# Hoisted instance_eval block: emit a direct C call to the synthetic1987220198
# file-scope function. The receiver is a local variable known to1987320199
# carry a class instance (the rewriter checked this); pass it as the@@ -20361,7 +20687,6 @@
2036120687
end2036220688
end2036320689
if mname == "method"20364-
# method(:name) - record the method reference2036520690
args_id = @nd_arguments[nid]2036620691
if args_id >= 02036720692
arg_ids = get_args(args_id)@@ -20370,8 +20695,23 @@
2037020695
if mref == ""2037120696
mref = @nd_name[arg_ids[0]]2037220697
end20373-
# Return a placeholder - the actual dispatch happens in .call20374-
# We store this in the parent LocalVariableWriteNode handler20698+
# No receiver, inside a class body: bind to `self`. Same20699+
# inheritance-walk + null-fallback as the obj-recv path so20700+
# the C symbol points at the defining class and a missing20701+
# method gives a Ruby-NoMethodError-shaped null fn_ptr20702+
# instead of a link error. Ref #215.20703+
if @current_class_idx >= 020704+
owner_cname = find_defining_class_name(@current_class_idx, mref)20705+
if owner_cname != ""20706+
return "sp_Method_new((sp_Method *)self, (mrb_int)(uintptr_t)&sp_" + owner_cname + "_" + sanitize_name(mref) + ")"20707+
else20708+
return "sp_Method_new((sp_Method *)self, (mrb_int)0)"20709+
end20710+
end20711+
# Top-level: keep the static-alias placeholder. The matching20712+
# LocalVariableWriteNode handler in compile_stmt picks up20713+
# @pending_method_ref and records (lname, mref) so a later20714+
# `m.call(x)` rewrites to a direct `sp_<mref>(x)`.2037520715
@pending_method_ref = mref2037620716
return "0 /* method:" + mref + " */"2037720717
end@@ -26370,11 +26710,18 @@
2637026710
end2637126711
if t == "LocalVariableWriteNode"2637226712
lname = @nd_name[nid]26373-
# Check for method(:name) assignment26713+
# `var = method(:name)` (no receiver, top-level) is the legacy26714+
# static-alias path: the call_expr handler returns a `0`26715+
# placeholder, we record (lname, mref) here, and a later26716+
# `m.call(x)` is rewritten in compile_dot_call_expr to a26717+
# direct `sp_<name>(x)` call. Inside a class body OR with a26718+
# receiver (`var = recv.method(:_)`), the call expr already26719+
# produced a real obj_Method instance — fall through to the26720+
# normal compile path so the typed local picks it up. Ref #215.2637426721
expr_id = @nd_expression[nid]2637526722
if expr_id >= 02637626723
if @nd_type[expr_id] == "CallNode"26377-
if @nd_name[expr_id] == "method"26724+
if @nd_name[expr_id] == "method" && @nd_receiver[expr_id] < 0 && @current_class_idx < 02637826725
args_id = @nd_arguments[expr_id]2637926726
if args_id >= 02638026727
arg_ids = get_args(args_id)test/bound_method_array.rbaddedView file
Loading diff…
test/bound_method_array.rb.expectedaddedView file
Loading diff…
test/bound_method_basic.rbaddedView file
Loading diff…
test/bound_method_basic.rb.expectedaddedView file
Loading diff…
test/bound_method_gc.rbaddedView file
Loading diff…
test/bound_method_gc.rb.expectedaddedView file
Loading diff…
test/bound_method_obj_recv.rbaddedView file
Loading diff…
test/bound_method_obj_recv.rb.expectedaddedView file
Loading diff…
test/bound_method_single_eval.rbaddedView file
Loading diff…
test/bound_method_single_eval.rb.expectedaddedView file
Loading diff…