Commit 4a05401c

4a05401ce2b3Merged

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

Description

fix(codegen): Stage 2 — runtime sentinel switch for poly module slots

Issue #126 Stage 2: a class << self; attr_accessor :x; end accessor that's written more than once with different module/class names now goes through a runtime sentinel switch instead of constant folding. Stage 1 covered the single-write case; Stage 2 covers the genuinely polymorphic adapter-swap pattern (e.g. Rails flipping ActiveRecord.adapter between SqliteAdapter and PgAdapter at runtime).

Pieces:

  • @module_acc_consts[i] now holds the union of distinct ConstantReadNode RHSes as a ;-separated list. The resolve-pass walks every write, accumulates the set, and poisons the slot with ? if any RHS is non-constant.

  • New helpers: module_acc_resolved(mod, acc) returns the list, and module_sentinel(name) returns each module's index+1 as its runtime id (0 reserved for "uninitialised slot").

  • emit_global_constants now also emits static mrb_int sp_module_<Mod>_<acc> = 0; storage for every Stage-2 (2+ candidate) slot.

  • compile_call_stmt write side: Stage 1 entries (1 candidate) still emit nothing; Stage 2 entries emit slot = <sentinel>; so the read site can dispatch.

  • compile_call_expr chain dispatch: 1 candidate stays inline; 2+ candidates emit a chained ternary ((slot == SP_A) ? sp_A_cls_m(...) : (slot == SP_B) ? ... : 0).

  • infer_call_type returns the candidate set's common return type (or poly if they disagree). With one candidate the type is unchanged from Stage 1.

test/module_singleton_accessor_poly.rb covers the two-adapter swap and a three-candidate conditional-assignment shape.

Stage 3 (module values flowing across function boundaries — typed parameters / returns / ivars holding modules) remains; that one needs the sentinel encoding to leak into the type system, which is more invasive.

Refs #126

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

Details

Commit
4a05401ce2b3
Parent
836cf3a39322

spinel_codegen.rbmodifiedView file

@@ -257,19 +257,15 @@
257257 # Module tracking: module_name -> body node id
258258 @module_names = "".split(",")
259259 @module_body_ids = []
260- # Module-level singleton accessors (issue #126, Stage 1):
260+ # Module-level singleton accessors (issue #126):
261261 # `class << self; attr_accessor :foo; end` inside `module M`.
262- # Stage 1 only supports the static-fold case: each accessor is
263- # written exactly once with a constant-resolvable RHS (typically a
264- # module name). The folded value at the (module, accessor) key is
265- # then substituted at read sites, so `M.foo.method` lowers via
266- # the existing module-class-method dispatch path on the resolved
267- # constant. Keys are "<Module>.<accessor>"; `@module_acc_const`
268- # holds the resolved constant name (a module/class name) or "" if
269- # unresolved (writes are non-constant or there are multiple
270- # writes).
262+ # `@module_acc_consts[i]` is a `;`-separated list of distinct
263+ # constant names assigned to this slot (Stage 1: single name →
264+ # inline; Stage 2: multiple names → runtime sentinel switch).
265+ # Empty string means at least one write was non-constant — the
266+ # slot falls through to the un-folded path.
271267 @module_acc_keys = "".split(",")
272- @module_acc_const = "".split(",")
268+ @module_acc_consts = "".split(",")
273269 @pending_method_ref = ""
274270 @lambda_counter = 0
275271 @lambda_funcs = ""
@@ -1734,22 +1730,35 @@
17341730 mname = @nd_name[nid]
17351731 recv = @nd_receiver[nid]
17361732
1737- # Issue #126 Stage 1: `Module.accessor.<method>` resolves to
1738- # `<ConstName>.<method>` via the constant fold. The return type
1739- # needs the same substitution as the codegen path so `puts` and
1740- # other typed dispatchers see the right type.
1733+ # Issue #126: chain return type for `Module.accessor.<method>`.
1734+ # All resolved candidates' class methods should agree on a return
1735+ # type; if they disagree the chain becomes poly. Returning early
1736+ # only when we have a confident answer means the existing
1737+ # operator/comparison/etc paths still get to chime in for shapes
1738+ # that don't match this chain.
17411739 if recv >= 0 && @nd_type[recv] == "CallNode"
17421740 inner_recv = @nd_receiver[recv]
17431741 inner_mname = @nd_name[recv]
17441742 if inner_recv >= 0 && @nd_type[inner_recv] == "ConstantReadNode"
17451743 mod_name = @nd_name[inner_recv]
17461744 if module_name_exists(mod_name) == 1
1747- idx = find_module_acc_idx(mod_name + "." + inner_mname)
1748- if idx >= 0 && @module_acc_const[idx] != ""
1749- resolved = @module_acc_const[idx]
1750- mi = find_method_idx(resolved + "_cls_" + mname)
1751- if mi >= 0
1752- return @meth_return_types[mi]
1745+ rconsts = module_acc_resolved(mod_name, inner_mname)
1746+ if rconsts != "" && rconsts != "?"
1747+ cands = rconsts.split(";")
1748+ common = ""
1749+ cands.each { |cn|
1750+ mi = find_method_idx(cn + "_cls_" + mname)
1751+ if mi >= 0
1752+ rt = @meth_return_types[mi]
1753+ if common == ""
1754+ common = rt
1755+ elsif common != rt
1756+ common = "poly"
1757+ end
1758+ end
1759+ }
1760+ if common != ""
1761+ return common
17531762 end
17541763 end
17551764 end
@@ -4036,15 +4045,15 @@
40364045 -1
40374046 end
40384047
4039- # Issue #126 Stage 1: walk the AST for `Module.accessor = RHS` writes
4040- # where (Module, accessor) was registered in `collect_module` as a
4041- # singleton accessor (`class << self; attr_accessor :accessor; end`).
4042- # When every visible write resolves to the same ConstantReadNode (a
4043- # module or class name), record that name; later read sites substitute
4044- # the constant for the chained dispatch. Mixed / non-constant / multi-
4045- # value writes leave the entry unresolved, and the read site falls
4046- # through to the existing (currently-broken) path — Stage 2 will pick
4047- # those up via runtime sentinel dispatch.
4048+ # Issue #126: walk the AST for `Module.accessor = RHS` writes where
4049+ # (Module, accessor) was registered in `collect_module` as a
4050+ # singleton accessor. Accumulate the set of distinct ConstantReadNode
4051+ # RHSes; the lowering paths read this list to choose:
4052+ # - 0 entries: never written, falls through (un-folded)
4053+ # - 1 entry: Stage 1, inline `<resolved>.<method>` directly
4054+ # - 2+ entries: Stage 2, sentinel switch over the union
4055+ # A non-constant RHS poisons the slot with a `?` sentinel marker —
4056+ # the lowering paths treat that as un-folded.
40484057 def resolve_module_singleton_accessors
40494058 if @module_acc_keys.length == 0
40504059 return
@@ -4061,24 +4070,24 @@
40614070 accessor = mname[0, mname.length - 1]
40624071 key = mod_name + "." + accessor
40634072 idx = find_module_acc_idx(key)
4064- if idx >= 0
4073+ if idx >= 0 && @module_acc_consts[idx] != "?"
40654074 args_id = @nd_arguments[nid]
40664075 if args_id >= 0
40674076 arg_ids = get_args(args_id)
40684077 if arg_ids.length > 0 && @nd_type[arg_ids[0]] == "ConstantReadNode"
40694078 rhs_name = @nd_name[arg_ids[0]]
4070- cur = @module_acc_const[idx]
4071- if cur == ""
4072- @module_acc_const[idx] = rhs_name
4073- elsif cur != rhs_name
4074- # Multiple distinct constants → leave unresolved
4075- # by marking with a sentinel empty string. The
4076- # read site falls through to the un-folded path.
4077- @module_acc_const[idx] = ""
4079+ cur = @module_acc_consts[idx]
4080+ cur_list = cur.split(";")
4081+ if not_in(rhs_name, cur_list) == 1
4082+ if cur == ""
4083+ @module_acc_consts[idx] = rhs_name
4084+ else
4085+ @module_acc_consts[idx] = cur + ";" + rhs_name
4086+ end
40784087 end
40794088 else
4080- # Non-constant RHS: poisons the fold for this slot.
4081- @module_acc_const[idx] = ""
4089+ # Non-constant RHS poisons the slot.
4090+ @module_acc_consts[idx] = "?"
40824091 end
40834092 end
40844093 end
@@ -4090,6 +4099,31 @@
40904099 end
40914100 end
40924101
4102+ # Returns the resolved constant list for this (module, accessor):
4103+ # `<Name1>;<Name2>;...` for foldable, `""` if never written, `"?"`
4104+ # if poisoned (non-constant RHS).
4105+ def module_acc_resolved(mod_name, accessor)
4106+ idx = find_module_acc_idx(mod_name + "." + accessor)
4107+ if idx < 0
4108+ return ""
4109+ end
4110+ @module_acc_consts[idx]
4111+ end
4112+
4113+ # Sentinel value for Stage 2 switch dispatch. Each module's index in
4114+ # `@module_names` doubles as its sentinel id; reading `Module` as a
4115+ # value lowers to this integer.
4116+ def module_sentinel(mname)
4117+ i = 0
4118+ while i < @module_names.length
4119+ if @module_names[i] == mname
4120+ return i + 1
4121+ end
4122+ i = i + 1
4123+ end
4124+ 0
4125+ end
4126+
40934127 # Walk every class's parent chain. A cycle anywhere on the chain is
40944128 # a fatal program error: bail with a clear message instead of letting
40954129 # the recursive helpers loop forever. Self-inheritance (`class A < A`)
@@ -5631,7 +5665,7 @@
56315665 if @nd_type[aid] == "SymbolNode"
56325666 accessor = @nd_content[aid]
56335667 @module_acc_keys.push(mname + "." + accessor)
5634- @module_acc_const.push("")
5668+ @module_acc_consts.push("")
56355669 end
56365670 }
56375671 end
@@ -9954,6 +9988,30 @@
99549988 if @const_names.length > 0
99559989 emit_raw("")
99569990 end
9991+ # Issue #126 Stage 2: storage for module-level singleton accessors
9992+ # whose resolved set has 2+ candidates. The slot stores the
9993+ # assigned module's sentinel (mrb_int from `module_sentinel`); the
9994+ # write site emits `slot = N;` and the chain dispatch reads back
9995+ # via a sentinel switch.
9996+ j = 0
9997+ emitted = 0
9998+ while j < @module_acc_keys.length
9999+ consts = @module_acc_consts[j]
10000+ if consts != "" && consts != "?" && consts.split(";").length > 1
10001+ key = @module_acc_keys[j]
10002+ # key shape is "<Mod>.<accessor>"; turn the dot into an
10003+ # underscore for the C identifier.
10004+ dot = key.index(".")
10005+ mod = key[0, dot]
10006+ acc = key[dot + 1, key.length - dot - 1]
10007+ emit_raw("static mrb_int sp_module_" + mod + "_" + sanitize_name(acc) + " = 0;")
10008+ emitted = 1
10009+ end
10010+ j = j + 1
10011+ end
10012+ if emitted == 1
10013+ emit_raw("")
10014+ end
995710015 end
995810016
995910017 def is_value_type_ivar(t)
@@ -14274,26 +14332,18 @@
1427414332 mname = @nd_name[nid]
1427514333 recv = @nd_receiver[nid]
1427614334
14277- # Issue #126 Stage 1: `Module.accessor.<method>` where
14278- # (Module, accessor) was statically resolved by
14279- # `resolve_module_singleton_accessors`. Substitute the resolved
14280- # constant for the receiver and let the normal call dispatch handle
14281- # the resulting `<Constant>.<method>` call. The substitution
14282- # happens by synthesising a virtual ConstantReadNode-like dispatch
14283- # in-place: we intercept at compile_call_expr's top, look at recv,
14284- # and re-route through the resolved-constant call.
14335+ # Issue #126: `Module.accessor.<method>` where the slot was
14336+ # resolved by `resolve_module_singleton_accessors`. With a single
14337+ # constant in the resolved set, inline the call directly. With
14338+ # two or more, emit a sentinel-switch over the slot variable.
1428514339 if recv >= 0 && @nd_type[recv] == "CallNode"
1428614340 inner_recv = @nd_receiver[recv]
1428714341 inner_mname = @nd_name[recv]
1428814342 if inner_recv >= 0 && @nd_type[inner_recv] == "ConstantReadNode"
1428914343 mod_name = @nd_name[inner_recv]
1429014344 if module_name_exists(mod_name) == 1
14291- idx = find_module_acc_idx(mod_name + "." + inner_mname)
14292- if idx >= 0 && @module_acc_const[idx] != ""
14293- resolved = @module_acc_const[idx]
14294- # Build a temporary substitute receiver: a ConstantReadNode
14295- # of the resolved name. Reusing alloc_node would mutate the
14296- # AST, so instead we forge the call expression directly.
14345+ rconsts = module_acc_resolved(mod_name, inner_mname)
14346+ if rconsts != "" && rconsts != "?"
1429714347 args_id = @nd_arguments[nid]
1429814348 arg_strs = ""
1429914349 if args_id >= 0
@@ -14307,7 +14357,24 @@
1430714357 k = k + 1
1430814358 end
1430914359 end
14310- return "sp_" + resolved + "_cls_" + sanitize_name(mname) + "(" + arg_strs + ")"
14360+ cands = rconsts.split(";")
14361+ if cands.length == 1
14362+ return "sp_" + cands[0] + "_cls_" + sanitize_name(mname) + "(" + arg_strs + ")"
14363+ end
14364+ # Stage 2: sentinel switch. The slot stores the assigned
14365+ # module's sentinel; we walk the candidate list and dispatch
14366+ # the first match. Default `0` mirrors the un-initialised
14367+ # slot value (slot was zero-init, never written before read).
14368+ slot = "sp_module_" + mod_name + "_" + sanitize_name(inner_mname)
14369+ expr = "0"
14370+ ki = cands.length - 1
14371+ while ki >= 0
14372+ cn = cands[ki]
14373+ call_c = "sp_" + cn + "_cls_" + sanitize_name(mname) + "(" + arg_strs + ")"
14374+ expr = "((" + slot + " == " + module_sentinel(cn).to_s + ") ? " + call_c + " : " + expr + ")"
14375+ ki = ki - 1
14376+ end
14377+ return expr
1431114378 end
1431214379 end
1431314380 end
@@ -20711,16 +20778,31 @@
2071120778 return
2071220779 end
2071320780
20714- # Issue #126 Stage 1: `Module.accessor = X` where the entry was
20715- # statically folded. The read sites substitute the constant, so
20716- # the write side has nothing to emit.
20781+ # Issue #126: `Module.accessor = X` write.
20782+ # Stage 1 (1 candidate): no emit; reads fold to that constant.
20783+ # Stage 2 (2+ candidates): emit `slot = SP_MOD_<X>;` so the
20784+ # read site's sentinel switch picks the right branch.
2071720785 if mname.length > 1 && mname[mname.length - 1] == "=" && recv >= 0 && @nd_type[recv] == "ConstantReadNode"
2071820786 mod_name = @nd_name[recv]
2071920787 if module_name_exists(mod_name) == 1
2072020788 accessor = mname[0, mname.length - 1]
20721- idx = find_module_acc_idx(mod_name + "." + accessor)
20722- if idx >= 0 && @module_acc_const[idx] != ""
20723- return
20789+ rconsts = module_acc_resolved(mod_name, accessor)
20790+ if rconsts != "" && rconsts != "?"
20791+ cands = rconsts.split(";")
20792+ if cands.length == 1
20793+ return
20794+ end
20795+ # Stage 2: write the sentinel for the assigned module.
20796+ args_id2 = @nd_arguments[nid]
20797+ if args_id2 >= 0
20798+ ai = get_args(args_id2)
20799+ if ai.length > 0 && @nd_type[ai[0]] == "ConstantReadNode"
20800+ rhs = @nd_name[ai[0]]
20801+ slot = "sp_module_" + mod_name + "_" + sanitize_name(accessor)
20802+ emit(" " + slot + " = " + module_sentinel(rhs).to_s + ";")
20803+ return
20804+ end
20805+ end
2072420806 end
2072520807 end
2072620808 end