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 end
25742574 return "int"
25752575 end
2576+ # Method#call / Method#[]: the C-level signature lowers to
2577+ # `(void *self, mrb_int...) -> mrb_int`, so the inferred
2578+ # return is `int`. Non-int returns (string, obj, etc.) from
2579+ # the bound underlying method are out of scope. Ref #215.
2580+ if rt == "obj_Method"
2581+ return "int"
2582+ end
25762583 end
25772584 end
25782585
2586+ # `method(:foo)` produces a heap-allocated Method (the synthetic
2587+ # class registered in register_builtin_classes). Two captured
2588+ # 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 to
2591+ # the inferred receiver, regardless of where the call sits.
2592+ # Top-level `method(:foo)` with no receiver keeps the legacy
2593+ # static-alias placeholder; LocalVariableWriteNode then records
2594+ # 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 >= 0
2598+ return "obj_Method"
2599+ end
2600+ if recv >= 0 && is_obj_type(infer_type(recv)) == 1
2601+ return "obj_Method"
2602+ end
2603+ end
2604+
25792605 # `obj.attr = val` (attr-writer call) — Ruby semantics: the
25802606 # assignment expression evaluates to the rhs value, so the
25812607 # inferred type is the rhs argument's type. Without this, a
@@ -5616,6 +5642,13 @@
56165642 collect_class(sid)
56175643 end
56185644 }
5645+ # Pass 1.3: synthetic built-in classes (Method). Appended AFTER
5646+ # user classes so existing user-class indices don't shift; the
5647+ # poly-dispatch BUILTIN_PTR_ARRAY branch in
5648+ # emit_poly_builtin_dispatch assumes `cls_id 0` is the first user
5649+ # class and would silently misroute every poly call if Method
5650+ # took that slot. Ref #215.
5651+ register_builtin_classes
56195652 # Pass 1.4: register class variables (@@var). Walks each class
56205653 # 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 end
87618794
8795+ # Synthetic built-in user class for `method(:foo)` capture: every
8796+ # `m = method(:foo)` / `obj.method(:foo)` produces an instance of
8797+ # 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 type
8802+ # makes ivar_is_gc_ptr true, which makes the auto-generated gc
8803+ # scanner emit `sp_gc_mark(self->iv_self_obj)`. The actual
8804+ # captured pointer is the bound receiver (any user class), cast
8805+ # to `sp_Method *`. sp_gc_mark dispatches via the GC header's
8806+ # `scan` field — set at the *bound receiver's* allocation time —
8807+ # not via the static pointer type, so the cast is safe at the
8808+ # GC level even though it's a type lie at the C level.
8809+ # detect_method_taken_classes excludes the bound receiver's
8810+ # class from value-type optimization so the captured pointer
8811+ # never dangles (value-type instances live on the caller's
8812+ # 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 every
8815+ # target). The Method.call/[] codegen in compile_call_expr casts
8816+ # it back to a function pointer of the right shape.
8817+ def register_builtin_classes
8818+ @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+ end
8843+
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 end
1499715079 end
1499815080
15081+ # Build the set of class indices whose instances are captured by a
15082+ # `method(:foo)` / `<obj>.method(:foo)` and end up stored in a
15083+ # heap-allocated Method's `@self_obj`. Such classes must stay
15084+ # heap-allocated — value-type optimization would put `self` on the
15085+ # caller's stack, and the captured pointer would dangle when the
15086+ # binding method returns. Ref #215.
15087+ #
15088+ # The walk needs scope set up so `infer_type` on a chained
15089+ # `<recv>.method(:foo)` can resolve `<recv>` (a local, an ivar via
15090+ # attr_reader, or a chained call) back to its `obj_<X>` type.
15091+ def detect_method_taken_classes
15092+ @method_taken_class_indices = "".split(",")
15093+ # Walk class methods first.
15094+ i = 0
15095+ while i < @cls_names.length
15096+ 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_idx
15103+ @current_class_idx = i
15104+ mi = 0
15105+ while mi < mnames.length
15106+ if mi < bodies.length
15107+ bid = bodies[mi].to_i
15108+ if bid >= 0
15109+ pnames = ""
15110+ ptypes = ""
15111+ if mi < all_params.length
15112+ pnames = all_params[mi]
15113+ end
15114+ if mi < all_ptypes.length
15115+ ptypes = all_ptypes[mi]
15116+ end
15117+ method_taken_walk_with_scope(bid, pnames, ptypes, i)
15118+ end
15119+ end
15120+ mi = mi + 1
15121+ end
15122+ @current_class_idx = saved_ci
15123+ end
15124+ i = i + 1
15125+ end
15126+ # Walk top-level methods.
15127+ mi = 0
15128+ while mi < @meth_names.length
15129+ bid = @meth_body_ids[mi]
15130+ if bid >= 0
15131+ method_taken_walk_with_scope(bid, @meth_param_names[mi], @meth_param_types[mi], -1)
15132+ end
15133+ mi = mi + 1
15134+ end
15135+ # Walk the top-level main script body too — `bm = make().method(:foo)`
15136+ # at script scope must propagate the captured-receiver class into
15137+ # 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_scope
15141+ lnames = "".split(",")
15142+ ltypes = "".split(",")
15143+ sk = 0
15144+ while sk < stmts.length
15145+ scan_locals(stmts[sk], lnames, ltypes, "".split(","))
15146+ sk = sk + 1
15147+ end
15148+ lk = 0
15149+ while lk < lnames.length
15150+ declare_var(lnames[lk], ltypes[lk])
15151+ lk = lk + 1
15152+ end
15153+ sk = 0
15154+ while sk < stmts.length
15155+ collect_method_taken(stmts[sk], -1)
15156+ sk = sk + 1
15157+ end
15158+ pop_scope
15159+ end
15160+ end
15161+
15162+ def method_taken_walk_with_scope(bid, pnames_str, ptypes_str, enclosing_ci)
15163+ push_scope
15164+ pnames = pnames_str.split(",")
15165+ ptypes = ptypes_str.split(",")
15166+ k = 0
15167+ while k < pnames.length
15168+ pt = "int"
15169+ if k < ptypes.length
15170+ pt = ptypes[k]
15171+ end
15172+ declare_var(pnames[k], pt)
15173+ k = k + 1
15174+ end
15175+ lnames = "".split(",")
15176+ ltypes = "".split(",")
15177+ scan_locals(bid, lnames, ltypes, pnames)
15178+ lk = 0
15179+ while lk < lnames.length
15180+ declare_var(lnames[lk], ltypes[lk])
15181+ lk = lk + 1
15182+ end
15183+ collect_method_taken(bid, enclosing_ci)
15184+ pop_scope
15185+ end
15186+
15187+ def collect_method_taken(nid, enclosing_ci)
15188+ if nid < 0
15189+ return
15190+ end
15191+ if @nd_type[nid] == "CallNode" && @nd_name[nid] == "method"
15192+ args_id = @nd_arguments[nid]
15193+ if args_id >= 0
15194+ a = get_args(args_id)
15195+ if a.length >= 1
15196+ recv = @nd_receiver[nid]
15197+ target = -1
15198+ if recv < 0
15199+ target = enclosing_ci
15200+ else
15201+ rt = infer_type(recv)
15202+ if is_obj_type(rt) == 1
15203+ target = find_class_idx(rt[4, rt.length - 4])
15204+ end
15205+ end
15206+ if target >= 0 && not_in(target.to_s, @method_taken_class_indices) == 1
15207+ @method_taken_class_indices.push(target.to_s)
15208+ end
15209+ end
15210+ end
15211+ end
15212+ cs = []
15213+ push_child_ids(nid, cs)
15214+ k = 0
15215+ while k < cs.length
15216+ collect_method_taken(cs[k], enclosing_ci)
15217+ k = k + 1
15218+ end
15219+ end
15220+
1499915221 def recalc_needs_gc
1500015222 # Recalculate @needs_gc: only needed if non-value-type classes are used
1500115223 @needs_gc = 0
@@ -15038,6 +15260,7 @@
1503815260 detect_param_mutated_types
1503915261 detect_ptr_array_stored_types
1504015262 detect_poly_returned_types
15263+ detect_method_taken_classes
1504115264 # Multiple passes: value type detection depends on other classes
1504215265 2.times do
1504315266 i = 0
@@ -15119,7 +15342,18 @@
1511915342 pri = pri + 1
1512015343 end
1512115344 end
15345+ # Exclude classes whose instances are captured by a Method
15346+ # (via `method(:foo)` on self, or `<obj>.method(:foo)` from
15347+ # anywhere). The captured receiver must be a stable heap
15348+ # pointer; value-type instances live on the caller's stack
15349+ # and the pointer would dangle once the binding method
15350+ # returns. Ref #215.
1512215351 if all_val == 1
15352+ if not_in(i.to_s, @method_taken_class_indices) == 0
15353+ all_val = 0
15354+ end
15355+ end
15356+ if all_val == 1
1512315357 @cls_is_value_type[i] = 1
1512415358 end
1512515359 end
@@ -15177,6 +15411,18 @@
1517715411 mk = mk + 1
1517815412 end
1517915413 end
15414+ # Method-captured receivers must stay heap-allocated. SRA
15415+ # explodes the instance into stack-resident scalars, which is
15416+ # the same dangling-pointer hazard as value-type. Defensive:
15417+ # current test corpus doesn't exercise an SRA-eligible class
15418+ # (initialize + attr_* only) being captured, but a future
15419+ # `class X; attr_accessor :n; end` followed by
15420+ # `X.new(...).method(:n)` would. Ref #215.
15421+ if eligible == 1
15422+ if not_in(i.to_s, @method_taken_class_indices) == 0
15423+ eligible = 0
15424+ end
15425+ end
1518015426 if eligible == 1
1518115427 @cls_is_sra[i] = 1
1518215428 end
@@ -15720,6 +15966,29 @@
1572015966 -1
1572115967 end
1572215968
15969+ # Walk the inheritance chain starting at class `ci` looking for the
15970+ # first ancestor that defines `mname` directly. Returns that class's
15971+ # name, or "" if no ancestor defines it. Used by the
15972+ # `method(:foo)` codegen to build the C symbol of the bound function:
15973+ # an inherited method's generated C function lives under the
15974+ # *defining* class (`sp_Parent_foo`), not the receiver's own class
15975+ # (`sp_Child_foo`), so `&sp_Child_foo` would be an unresolved symbol
15976+ # at link time. When this returns "" the codegen falls back to a
15977+ # null fn_ptr — Ruby's NoMethodError-on-invoke equivalent. Ref #215.
15978+ def find_defining_class_name(ci, mname)
15979+ walker = ci
15980+ while walker >= 0
15981+ if cls_find_method_direct(walker, mname) >= 0
15982+ return @cls_names[walker]
15983+ end
15984+ if @cls_parents[walker] == ""
15985+ return ""
15986+ end
15987+ walker = find_class_idx(@cls_parents[walker])
15988+ end
15989+ ""
15990+ end
15991+
1572315992 def method_params_decl(mi)
1572415993 mfullname = @meth_names[mi]
1572515994 pnames = @meth_param_names[mi].split(",")
@@ -19868,6 +20137,63 @@
1986820137 end
1986920138 end
1987020139
20140+ # `bm.call(args)` / `bm[args]` where bm is a Method instance —
20141+ # lower to a function-pointer cast and an indirect call. The
20142+ # bound function's C signature is
20143+ # `(void *self, mrb_int...) -> mrb_int`. The receiver expression
20144+ # 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 >= 0
20147+ if base_type(infer_type(recv)) == "obj_Method"
20148+ rc = compile_expr(recv)
20149+ bm_tmp = new_temp
20150+ emit(" sp_Method *" + bm_tmp + " = " + rc + ";")
20151+ args_id = @nd_arguments[nid]
20152+ joined = ""
20153+ sig_args = "void *"
20154+ if args_id >= 0
20155+ aargs = get_args(args_id)
20156+ k = 0
20157+ while k < aargs.length
20158+ joined = joined + ", " + compile_expr(aargs[k])
20159+ sig_args = sig_args + ", mrb_int"
20160+ k = k + 1
20161+ end
20162+ end
20163+ return "((mrb_int (*)(" + sig_args + "))(uintptr_t)" + bm_tmp + "->iv_fn_ptr)((void *)" + bm_tmp + "->iv_self_obj" + joined + ")"
20164+ end
20165+ end
20166+
20167+ # `<obj>.method(:bar)` — bind to a non-self receiver. The
20168+ # detect_method_taken_classes pass keeps the receiver class
20169+ # heap-allocated so `<obj>` evaluates to a stable pointer that
20170+ # the resulting Method can capture. Walks the inheritance chain
20171+ # to point at the *defining* class's C symbol; if no ancestor
20172+ # defines the method, falls back to a null fn_ptr. Ref #215.
20173+ if mname == "method" && recv >= 0
20174+ args_id = @nd_arguments[nid]
20175+ if args_id >= 0
20176+ arg_ids = get_args(args_id)
20177+ if arg_ids.length >= 1
20178+ recv_t = infer_type(recv)
20179+ if is_obj_type(recv_t) == 1
20180+ mref = @nd_content[arg_ids[0]]
20181+ if mref == ""
20182+ mref = @nd_name[arg_ids[0]]
20183+ end
20184+ 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+ else
20190+ return "sp_Method_new((sp_Method *)(" + rc + "), (mrb_int)0)"
20191+ end
20192+ end
20193+ end
20194+ end
20195+ end
20196+
1987120197 # Hoisted instance_eval block: emit a direct C call to the synthetic
1987220198 # file-scope function. The receiver is a local variable known to
1987320199 # carry a class instance (the rewriter checked this); pass it as the
@@ -20361,7 +20687,6 @@
2036120687 end
2036220688 end
2036320689 if mname == "method"
20364- # method(:name) - record the method reference
2036520690 args_id = @nd_arguments[nid]
2036620691 if args_id >= 0
2036720692 arg_ids = get_args(args_id)
@@ -20370,8 +20695,23 @@
2037020695 if mref == ""
2037120696 mref = @nd_name[arg_ids[0]]
2037220697 end
20373- # Return a placeholder - the actual dispatch happens in .call
20374- # We store this in the parent LocalVariableWriteNode handler
20698+ # No receiver, inside a class body: bind to `self`. Same
20699+ # inheritance-walk + null-fallback as the obj-recv path so
20700+ # the C symbol points at the defining class and a missing
20701+ # method gives a Ruby-NoMethodError-shaped null fn_ptr
20702+ # instead of a link error. Ref #215.
20703+ if @current_class_idx >= 0
20704+ 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+ else
20708+ return "sp_Method_new((sp_Method *)self, (mrb_int)0)"
20709+ end
20710+ end
20711+ # Top-level: keep the static-alias placeholder. The matching
20712+ # LocalVariableWriteNode handler in compile_stmt picks up
20713+ # @pending_method_ref and records (lname, mref) so a later
20714+ # `m.call(x)` rewrites to a direct `sp_<mref>(x)`.
2037520715 @pending_method_ref = mref
2037620716 return "0 /* method:" + mref + " */"
2037720717 end
@@ -26370,11 +26710,18 @@
2637026710 end
2637126711 if t == "LocalVariableWriteNode"
2637226712 lname = @nd_name[nid]
26373- # Check for method(:name) assignment
26713+ # `var = method(:name)` (no receiver, top-level) is the legacy
26714+ # static-alias path: the call_expr handler returns a `0`
26715+ # placeholder, we record (lname, mref) here, and a later
26716+ # `m.call(x)` is rewritten in compile_dot_call_expr to a
26717+ # direct `sp_<name>(x)` call. Inside a class body OR with a
26718+ # receiver (`var = recv.method(:_)`), the call expr already
26719+ # produced a real obj_Method instance — fall through to the
26720+ # normal compile path so the typed local picks it up. Ref #215.
2637426721 expr_id = @nd_expression[nid]
2637526722 if expr_id >= 0
2637626723 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 < 0
2637826725 args_id = @nd_arguments[expr_id]
2637926726 if args_id >= 0
2638026727 arg_ids = get_args(args_id)