Commit 836cf3a3

836cf3a39322Merged

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

Description

fix(codegen): Stage 1 — module-level singleton-accessor constant fold

Issue #126 (Sam Ruby's first follow-up to #83): a module value assigned to a class << self; attr_accessor :x; end accessor used to read back as 0. The whole class << self block was silently dropped at parse time (no PM_SINGLETON_CLASS_NODE case in spinel_parse.c), and codegen had no representation for "module as a value" — so the assignment was a no-op and the read fell through to the default int.

Stage 1 of a planned three-stage rollout. Handles the static-fold case: a single assignment of a constant-resolvable RHS (typically a module/class name) is folded at codegen time, and read sites substitute the resolved constant in <recv>.<method> chains. This unblocks Roundhouse's adapter-slot pattern (the issue's motivating use case) without yet introducing runtime sentinel encoding for genuinely polymorphic slots.

Pieces:

  • spinel_parse.c: emit SingletonClassNode { expression, body } for PM_SINGLETON_CLASS_NODE. Only expression == self is meaningful in current scope.

  • collect_module: scan the module body for SingletonClassNodes containing attr_accessor :name calls; register (module_name, accessor_name) keys for the static-fold pass.

  • New pass resolve_module_singleton_accessors (between class collection and return-type inference): walk every CallNode for Module.accessor = RHS writes against a registered key. If every visible write resolves to the same ConstantReadNode name, fold the entry to that name; mixed / non-constant / multi-value writes leave the entry unresolved.

  • compile_call_stmt: skip emit for a folded Module.accessor = X write — read sites substitute the constant directly.

  • compile_call_expr: detect Module.accessor.<method> chains and rewrite as sp_<ResolvedConstant>_cls_<method>(args). The chain receiver is the inner CallNode Module.accessor; its receiver is the ConstantReadNode that names the module.

  • infer_call_type: same substitution for the chain so the result type is the resolved class-method's return type, threaded correctly into typed dispatchers like puts.

test/module_singleton_accessor.rb covers the issue's exact reproducer, the string-returning downstream method that surfaced as a C type mismatch, and a class-as-value variant on the same accessor shape.

Stage 2 (polymorphic slots, runtime sentinel switch) and Stage 3 (module values across function boundaries) remain to do. The issue's third variant (module M; @x = ConstName; def self.x; @x; end; end) also still emits an undeclared identifier — the @ivar form goes through a different lowering and needs its own fold extension; tracked under #126's residue.

Refs #126

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

Details

Commit
836cf3a39322
Parent
d78e9e79afa8

spinel_codegen.rbmodifiedView file

@@ -257,6 +257,19 @@
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):
261+ # `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).
271+ @module_acc_keys = "".split(",")
272+ @module_acc_const = "".split(",")
260273 @pending_method_ref = ""
261274 @lambda_counter = 0
262275 @lambda_funcs = ""
@@ -1721,6 +1734,28 @@
17211734 mname = @nd_name[nid]
17221735 recv = @nd_receiver[nid]
17231736
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.
1741+ if recv >= 0 && @nd_type[recv] == "CallNode"
1742+ inner_recv = @nd_receiver[recv]
1743+ inner_mname = @nd_name[recv]
1744+ if inner_recv >= 0 && @nd_type[inner_recv] == "ConstantReadNode"
1745+ mod_name = @nd_name[inner_recv]
1746+ 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]
1753+ end
1754+ end
1755+ end
1756+ end
1757+ end
1758+
17241759 # Operators
17251760 r = infer_operator_type(nid, mname, recv)
17261761 if r != ""
@@ -3988,6 +4023,73 @@
39884023 end
39894024
39904025 # ---- Collection pass ----
4026+ # Returns the module-singleton-accessor index for "<Module>.<accessor>",
4027+ # or -1 if not registered.
4028+ def find_module_acc_idx(key)
4029+ i = 0
4030+ while i < @module_acc_keys.length
4031+ if @module_acc_keys[i] == key
4032+ return i
4033+ end
4034+ i = i + 1
4035+ end
4036+ -1
4037+ end
4038+
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+ def resolve_module_singleton_accessors
4049+ if @module_acc_keys.length == 0
4050+ return
4051+ end
4052+ nid = 0
4053+ while nid < @nd_type.length
4054+ if @nd_type[nid] == "CallNode"
4055+ mname = @nd_name[nid]
4056+ if mname.length > 1 && mname[mname.length - 1] == "="
4057+ recv = @nd_receiver[nid]
4058+ if recv >= 0 && @nd_type[recv] == "ConstantReadNode"
4059+ mod_name = @nd_name[recv]
4060+ if module_name_exists(mod_name) == 1
4061+ accessor = mname[0, mname.length - 1]
4062+ key = mod_name + "." + accessor
4063+ idx = find_module_acc_idx(key)
4064+ if idx >= 0
4065+ args_id = @nd_arguments[nid]
4066+ if args_id >= 0
4067+ arg_ids = get_args(args_id)
4068+ if arg_ids.length > 0 && @nd_type[arg_ids[0]] == "ConstantReadNode"
4069+ 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] = ""
4078+ end
4079+ else
4080+ # Non-constant RHS: poisons the fold for this slot.
4081+ @module_acc_const[idx] = ""
4082+ end
4083+ end
4084+ end
4085+ end
4086+ end
4087+ end
4088+ end
4089+ nid = nid + 1
4090+ end
4091+ end
4092+
39914093 # Walk every class's parent chain. A cycle anywhere on the chain is
39924094 # a fatal program error: bail with a clear message instead of letting
39934095 # the recursive helpers loop forever. Self-inheritance (`class A < A`)
@@ -4066,6 +4168,13 @@
40664168 # assigned `ClassName.new`; no block params; no closures; no yield.
40674169 rewrite_instance_eval_calls
40684170
4171+ # Pass 2.7: resolve module-level singleton accessors via constant
4172+ # fold (issue #126, Stage 1). Single assignment of a constant
4173+ # name (typically a module/class) to `M.acc` or `@acc` inside
4174+ # `module M` is folded; reads later substitute the resolved
4175+ # constant.
4176+ resolve_module_singleton_accessors
4177+
40694178 # Pass 2.5: infer lambda parameter types from call sites
40704179 infer_lambda_param_types
40714180
@@ -5505,6 +5614,31 @@
55055614 @const_expr_ids.push(expr_id)
55065615 @const_scope_names.push(mname)
55075616 end
5617+ # `class << self; attr_accessor :foo; end` — register `foo` as a
5618+ # module-level singleton accessor. Stage 1 of issue #126: the
5619+ # accessor's value is resolved later via the constant-fold pass
5620+ # (rewrite_module_singleton_accessors) once we've seen all writes.
5621+ if @nd_type[sid] == "SingletonClassNode"
5622+ sbody = @nd_body[sid]
5623+ if sbody >= 0
5624+ sbody_stmts = get_stmts(sbody)
5625+ sbody_stmts.each { |sst|
5626+ if @nd_type[sst] == "CallNode" && @nd_name[sst] == "attr_accessor"
5627+ args_id = @nd_arguments[sst]
5628+ if args_id >= 0
5629+ arg_ids = get_args(args_id)
5630+ arg_ids.each { |aid|
5631+ if @nd_type[aid] == "SymbolNode"
5632+ accessor = @nd_content[aid]
5633+ @module_acc_keys.push(mname + "." + accessor)
5634+ @module_acc_const.push("")
5635+ end
5636+ }
5637+ end
5638+ end
5639+ }
5640+ end
5641+ end
55085642 }
55095643 end
55105644
@@ -14140,6 +14274,45 @@
1414014274 mname = @nd_name[nid]
1414114275 recv = @nd_receiver[nid]
1414214276
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.
14285+ if recv >= 0 && @nd_type[recv] == "CallNode"
14286+ inner_recv = @nd_receiver[recv]
14287+ inner_mname = @nd_name[recv]
14288+ if inner_recv >= 0 && @nd_type[inner_recv] == "ConstantReadNode"
14289+ mod_name = @nd_name[inner_recv]
14290+ 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.
14297+ args_id = @nd_arguments[nid]
14298+ arg_strs = ""
14299+ if args_id >= 0
14300+ aargs = get_args(args_id)
14301+ k = 0
14302+ while k < aargs.length
14303+ if k > 0
14304+ arg_strs = arg_strs + ", "
14305+ end
14306+ arg_strs = arg_strs + compile_expr(aargs[k])
14307+ k = k + 1
14308+ end
14309+ end
14310+ return "sp_" + resolved + "_cls_" + sanitize_name(mname) + "(" + arg_strs + ")"
14311+ end
14312+ end
14313+ end
14314+ end
14315+
1414314316 # Hoisted instance_eval block: emit a direct C call to the synthetic
1414414317 # file-scope function. The receiver is a local variable known to
1414514318 # carry a class instance (the rewriter checked this); pass it as the
@@ -20538,6 +20711,20 @@
2053820711 return
2053920712 end
2054020713
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.
20717+ if mname.length > 1 && mname[mname.length - 1] == "=" && recv >= 0 && @nd_type[recv] == "ConstantReadNode"
20718+ mod_name = @nd_name[recv]
20719+ if module_name_exists(mod_name) == 1
20720+ 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
20724+ end
20725+ end
20726+ end
20727+
2054120728 # Hoisted instance_eval block (statement context): the lifted
2054220729 # function returns void, so emit it as a plain statement.
2054320730 if is_ieval_call_name(mname) == 1