Commit 5d13c029

5d13c0299186Merged

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

Description

fix(codegen): self.class. dispatches to subclass override (#422)

self.class.<cmeth> evaluated inside a parent-defined instance method statically resolved against the method body's defining class and routed every call to the parent's cmeth -- wrong when the runtime instance is a subclass that overrides. The canonical "abstract base class with template-method pattern" (e.g. ActiveRecord::Base#save calling self.class._adapter_insert) landed on the abstract method instead of the per-model override and cascaded into a wall of C-compile errors downstream in real-blog.

Fix shape:

  • Struct layout: every non-value-type sp_ picks up mrb_int cls_id as its first field. Layout-roots (no parent in @cls_names, including classes whose declared parent is a built-in like StandardError that spinel doesn't model) emit it directly; subclasses inherit it through parent-fields-first ordering, so (sp_Base *)child_ptr preserves the offset and ->cls_id reads correctly.

  • Constructors: sp_<C>_new now writes self->cls_id = <ci>LL after the alloc, tagging the instance with its concrete class index.

  • Chained dispatch: in compile_object_method_expr's <obj>.class.<cmeth>(...) arm, when descendants of the recv's static class override <cmeth> as a cmeth, lower to a switch (<recv>->cls_id) { case <C>: tmp = sp_<C>_cls_<m>(); break; ... default: <static-base-call> } instead of the static base-class call. Gated on recv being side-effect-free (SelfNode / LocalVariableReadNode), non-value-type, zero-arg cmeth, and all candidate owners' return types matching -- out-of-bounds shapes fall back to the existing static behavior unchanged. The static path is also retained when no descendant overrides exist, so the layout/constructor cost stays load-bearing only on programs that exercise the dispatch.

Scope: covers the canonical zero-arg self.class.<m> shape from the issue. Multi-arg cmeth dispatch and dynamic recv (e.g. a poly-typed local that may carry instances of unrelated trees) are deferred -- they need either arg-eval temporization or the full poly-cls_id lookup path that lands as part of #404 Phase 3.

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

Details

Commit
5d13c0299186
Parent
b0c1423a0eeb

spinel_codegen.rbmodifiedView file

@@ -1843,6 +1843,53 @@
18431843 -1
18441844 end
18451845
1846+ # Issue #422: look up the C return type of `ci`'s cmeth named
1847+ # `mname`. Walks @cls_cmeth_returns directly (cls_cmethod_owner
1848+ # already resolves inheritance, so callers pass the owner ci).
1849+ # Defaults to "int" when the name isn't present -- the chained
1850+ # dispatch path verifies owner >= 0 before consulting this.
1851+ def cls_cmeth_return_type(ci, mname)
1852+ if ci < 0
1853+ return "int"
1854+ end
1855+ cmnames = @cls_cmeth_names[ci].split(";")
1856+ cm_returns = @cls_cmeth_returns[ci].split(";")
1857+ cj = 0
1858+ while cj < cmnames.length
1859+ if cmnames[cj] == mname
1860+ if cj < cm_returns.length
1861+ return cm_returns[cj]
1862+ end
1863+ return "int"
1864+ end
1865+ cj = cj + 1
1866+ end
1867+ "int"
1868+ end
1869+
1870+ # Issue #422: enumerate descendants of inner_ci (including
1871+ # inner_ci itself) whose cmeth owner differs from base_owner.
1872+ # Each entry is encoded `<descendant_ci>,<owner_ci>` separated
1873+ # by `;`. Empty string when no overrides exist (caller stays on
1874+ # the static-dispatch path).
1875+ def cls_cmeth_override_descendants(inner_ci, base_owner, mname)
1876+ out = ""
1877+ ck = 0
1878+ while ck < @cls_names.length
1879+ if ck == inner_ci || cls_is_descendant(ck, inner_ci) == 1
1880+ ow = cls_cmethod_owner(ck, mname)
1881+ if ow >= 0 && ow != base_owner
1882+ if out != ""
1883+ out = out + ";"
1884+ end
1885+ out = out + ck.to_s + "," + ow.to_s
1886+ end
1887+ end
1888+ ck = ck + 1
1889+ end
1890+ out
1891+ end
1892+
18461893 # `<arr>.method(:op)` for built-in array types: which (recv_type,
18471894 # mname) pairs we can lower into a Method-dispatch adapter. Limited
18481895 # to int_array's bracket ops + push for now (the optcarrot CPU
@@ -6718,7 +6765,35 @@
67186765 end
67196766 end
67206767
6768+ # Issue #422: a class is a layout-root iff it has no parent in
6769+ # @cls_names (either no declared parent, or its declared parent
6770+ # is a built-in like StandardError that spinel doesn't emit as
6771+ # a sp_<C> struct). Layout-roots own the cls_id slot at offset
6772+ # 0; subclasses pick it up through parent-fields-first walking.
6773+ def is_layout_root(ci)
6774+ if @cls_parents[ci] == ""
6775+ return 1
6776+ end
6777+ if find_class_idx(@cls_parents[ci]) < 0
6778+ return 1
6779+ end
6780+ 0
6781+ end
6782+
67216783 def emit_class_fields(ci)
6784+ # Issue #422: per-instance cls_id as the first field on a
6785+ # root-of-its-tree non-value-type class. Subclasses inherit
6786+ # the slot via parent-fields-first ordering, so a cast
6787+ # `sp_Child *` -> `sp_Base *` preserves the cls_id at the
6788+ # same offset and `self->cls_id` reads it correctly from a
6789+ # parent-typed pointer. Value-types are excluded (no
6790+ # heap-allocated instance, no subclasses by design). A class
6791+ # whose declared parent isn't in @cls_names (built-in like
6792+ # StandardError that spinel doesn't model as a sp_* struct)
6793+ # is effectively a root for layout purposes -- treat the same.
6794+ if @cls_is_value_type[ci] == 0 && is_layout_root(ci) == 1
6795+ emit_raw(" mrb_int cls_id;")
6796+ end
67226797 # Parent fields first
67236798 if @cls_parents[ci] != ""
67246799 pi = find_class_idx(@cls_parents[ci])
@@ -6759,6 +6834,12 @@
67596834 emit_parent_fields(pi)
67606835 end
67616836 end
6837+ # Issue #422: cls_id at the root of the parent chain. See
6838+ # emit_class_fields' comment for the offset-preservation
6839+ # rationale.
6840+ if @cls_is_value_type[ci] == 0 && is_layout_root(ci) == 1
6841+ emit_raw(" mrb_int cls_id;")
6842+ end
67626843 names = @cls_ivar_names[ci].split(";")
67636844 types = @cls_ivar_types[ci].split(";")
67646845 j = 0
@@ -7605,6 +7686,11 @@
76057686 scan_fn = "sp_" + cname + "_gc_scan"
76067687 end
76077688 emit_raw(" sp_" + cname + " *self = (sp_" + cname + " *)sp_gc_alloc(sizeof(sp_" + cname + "), NULL, " + scan_fn + ");")
7689+ # Issue #422: tag the freshly-allocated instance with its
7690+ # concrete class id so a parent-method's `self.class.<cmeth>`
7691+ # path can read self->cls_id at runtime and switch to the
7692+ # subclass's override.
7693+ emit_raw(" self->cls_id = " + ci.to_s + "LL;")
76087694 emit_raw(" SP_GC_ROOT(self);")
76097695 end
76107696
@@ -16002,6 +16088,67 @@
1600216088 if owner_419 >= 0
1600316089 owner_name_419 = @cls_names[owner_419]
1600416090 ca_419 = compile_call_args(nid)
16091+ # Issue #422: when descendants of inner_ci override
16092+ # `mname` as a cmeth, the static call below routes
16093+ # everything to the base class -- wrong when the
16094+ # runtime instance is actually a subclass. Lower to
16095+ # a switch on `<inner>->cls_id` so the dispatch lands
16096+ # on the override. Gated on:
16097+ # - inner_recv simple (SelfNode or LocalVar) so its
16098+ # C expression has no side effects and can be
16099+ # reused for both `->cls_id` and the per-arm call.
16100+ # - inner_ci non-value-type (value types have no
16101+ # cls_id slot and no subclassing in spinel).
16102+ # - args absent (the no-arg case covers the canonical
16103+ # #422 reproducer and lets us reuse compile_call_args
16104+ # output across arms without reasoning about side
16105+ # effects from arg expressions).
16106+ # - all candidate owners' return types match (otherwise
16107+ # a unified result temp can't be typed).
16108+ ovr_422 = ""
16109+ if @cls_is_value_type[inner_ci_419] == 0 && ca_419 == ""
16110+ nty_422 = @nd_type[inner_recv_419]
16111+ if nty_422 == "SelfNode" || nty_422 == "LocalVariableReadNode"
16112+ ovr_422 = cls_cmeth_override_descendants(inner_ci_419, owner_419, mname)
16113+ end
16114+ end
16115+ if ovr_422 != ""
16116+ base_rt_422 = cls_cmeth_return_type(owner_419, mname)
16117+ ovr_pairs_422 = ovr_422.split(";")
16118+ rt_ok_422 = 1
16119+ op_422 = 0
16120+ while op_422 < ovr_pairs_422.length
16121+ pair_422 = ovr_pairs_422[op_422].split(",")
16122+ cand_owner_check_422 = pair_422[1].to_i
16123+ cand_rt_422 = cls_cmeth_return_type(cand_owner_check_422, mname)
16124+ if cand_rt_422 != base_rt_422
16125+ rt_ok_422 = 0
16126+ op_422 = ovr_pairs_422.length
16127+ else
16128+ op_422 = op_422 + 1
16129+ end
16130+ end
16131+ if rt_ok_422 == 1
16132+ inner_c_422 = compile_expr(inner_recv_419)
16133+ tmp_422 = new_temp
16134+ rt_c_422 = c_type(base_rt_422)
16135+ default_call_422 = "sp_" + owner_name_419 + "_cls_" + sanitize_name(mname) + "()"
16136+ emit(" " + rt_c_422 + " " + tmp_422 + " = " + default_call_422 + ";")
16137+ emit(" switch (" + inner_c_422 + "->cls_id) {")
16138+ op2_422 = 0
16139+ while op2_422 < ovr_pairs_422.length
16140+ pair2_422 = ovr_pairs_422[op2_422].split(",")
16141+ cand_cid_422 = pair2_422[0]
16142+ cand_owner_422 = pair2_422[1].to_i
16143+ cand_name_422 = @cls_names[cand_owner_422]
16144+ cand_call_422 = "sp_" + cand_name_422 + "_cls_" + sanitize_name(mname) + "()"
16145+ emit(" case " + cand_cid_422 + "LL: " + tmp_422 + " = " + cand_call_422 + "; break;")
16146+ op2_422 = op2_422 + 1
16147+ end
16148+ emit(" }")
16149+ return tmp_422
16150+ end
16151+ end
1600516152 if ca_419 == ""
1600616153 return "sp_" + owner_name_419 + "_cls_" + sanitize_name(mname) + "()"
1600716154 end