Commit 489a4199

489a419932e8Merged

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

Description

Specialize a subclass class method through a non-overriding intermediate

A class method called on a subclass was specialized (cloned, so its implicit-self calls resolve in the subclass) only when its body directly calls a method the subclass overrides. When the override was reached only transitively -- through an intermediate class method the subclass does NOT override -- nothing on the chain was cloned, so it stayed bound to the base and an abstract raise-only base method ran (#1451):

Base.last_row -> all_rows -> table_name   # Article overrides only table_name
Article.last_row  =>  Base.table_name raises, instead of "articles"

Two parts:

  1. cmethod_needs_specialization now detects overrides reached transitively: a new cmethod_reaches_override walks bare implicit-self cmethod calls, descending into inherited (non-overridden) intermediates, with a depth cap that doubles as a cycle guard.

  2. The clone is now recursive (specialize_cmethod_for): when an entry method is cloned for a subclass, every inherited intermediate it reaches that itself needs specialization is cloned for the subclass too, so the cloned body's implicit-self call rebinds to the subclass copy rather than the base. The "subclass already owns this cmethod" guard makes it idempotent and terminates mutual recursion.

The direct 1-hop case (#1443's class-method sibling) and the bare-new create-method case (#224/#229) are unchanged. A transitive bare-new through an intermediate (build -> create -> new) is a separate, return-type-inference gap and is left as-is (it was already silently mis-constructing the base). Full gate green (tests, bench, optcarrot checksum 59662).

Fixes #1451

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
489a419932e8
Parent
1e1854d5ab11

src/analyze_scope.cmodifiedView file

@@ -1756,10 +1756,40 @@
17561756 return 0;
17571757 }
17581758
1759+/* Does the inherited cls method `mi` (defined on def_cls), run as a class method
1760+ of `ci`, reach a bare cmethod call that resolves to a DIFFERENT method for ci
1761+ -- directly, or TRANSITIVELY through a non-overriding intermediate cmethod?
1762+ E.g. `last_row` calls `all_rows` (which ci does not override) calls
1763+ `table_name` (which ci does): `last_row` reaches an override and so must be
1764+ specialized for ci too, or its implicit-self chain stays bound to the base and
1765+ the override is skipped (#1451). The depth cap bounds the walk and doubles as a
1766+ cycle guard for mutually-recursive cmethods. */
1767+static int cmethod_reaches_override(Compiler *c, int mi, int ci, int def_cls, int depth) {
1768+ if (depth > 64) return 0;
1769+ const NodeTable *nt = c->nt;
1770+ for (int id = 0; id < nt->count; id++) {
1771+ if (c->nscope[id] != mi) continue;
1772+ const char *ty = nt_type(nt, id);
1773+ if (!ty || strcmp(ty, "CallNode")) continue;
1774+ if (nt_ref(nt, id, "receiver") >= 0) continue; /* receiverless only */
1775+ const char *nm = nt_str(nt, id, "name");
1776+ if (!nm || !strcmp(nm, "new")) continue; /* direct `new` is the caller's has_new path */
1777+ int sub_def = -1;
1778+ int mci = comp_cmethod_in_chain(c, ci, nm, NULL);
1779+ int mdef = comp_cmethod_in_chain(c, def_cls, nm, &sub_def);
1780+ if (mci >= 0 && mci != mdef) return 1; /* ci overrides nm directly */
1781+ /* nm is inherited unchanged by ci -- but its own body may still reach an
1782+ override; descend into the def-chain version. */
1783+ if (mdef >= 0 && sub_def >= 0 &&
1784+ cmethod_reaches_override(c, mdef, ci, sub_def, depth + 1)) return 1;
1785+ }
1786+ return 0;
1787+}
1788+
17591789 /* Does the inherited cls method `mi` (defined on def_cls) contain a bare call
17601790 that would resolve differently when run as a class method of `ci`? That is:
1761- a bare `new` (constructs ci), or a bare cmethod call `m` that ci defines but
1762- def_cls does not (so the inherited body's `m` means ci's version). */
1791+ a bare `new` (constructs ci), or a bare cmethod call that resolves to ci's
1792+ own version directly or transitively (cmethod_reaches_override). */
17631793 int cmethod_needs_specialization(Compiler *c, int mi, int ci, int def_cls, int *has_new) {
17641794 const NodeTable *nt = c->nt;
17651795 int need = 0;
@@ -1771,21 +1801,84 @@
17711801 if (nt_ref(nt, id, "receiver") >= 0) continue; /* receiverless only */
17721802 const char *nm = nt_str(nt, id, "name");
17731803 if (!nm) continue;
1774- if (!strcmp(nm, "new")) { if (has_new) *has_new = 1; need = 1; continue; }
1775- /* a bare cmethod call that resolves to a different method for ci than for
1776- the defining class (ci adds or overrides it) */
1777- int mci = comp_cmethod_in_chain(c, ci, nm, NULL);
1778- int mdef = comp_cmethod_in_chain(c, def_cls, nm, NULL);
1779- if (mci >= 0 && mci != mdef) need = 1;
1804+ if (!strcmp(nm, "new")) { if (has_new) *has_new = 1; need = 1; }
17801805 }
1806+ if (cmethod_reaches_override(c, mi, ci, def_cls, 0)) need = 1;
17811807 return need;
17821808 }
17831809
1810+/* Clone inherited cls method `mi` (defined on def_cls) as a ci-owned copy whose
1811+ body is re-attributed to ci, so its bare `new` constructs ci and its
1812+ implicit-self cmethod calls resolve in ci's chain. Then recurse: any bare
1813+ cmethod call in mi's body that ci inherits unchanged but that itself needs
1814+ specialization (reaches an override, or does `new`) is cloned for ci too, so
1815+ the cloned body's implicit-self call rebinds to ci's copy instead of staying
1816+ on the base -- that transitive rebind is the #1451 fix. The ci-already-owns
1817+ guard makes this idempotent and terminates mutually-recursive cmethods. */
1818+static void specialize_cmethod_for(Compiler *c, int mi, int def_cls, int ci) {
1819+ if (comp_cmethod_in_class(c, ci, c->scopes[mi].name) >= 0) return;
1820+ NodeTable *nt = (NodeTable *)c->nt;
1821+ int has_new = 0;
1822+ (void)cmethod_needs_specialization(c, mi, ci, def_cls, &has_new);
1823+ int src_body = c->scopes[mi].body;
1824+ int new_body = src_body >= 0 ? nt_clone_subtree(nt, src_body) : -1;
1825+ if (src_body >= 0 && new_body < 0) return; /* clone failed: skip */
1826+ comp_grow_node_arrays(c);
1827+ Scope *src = &c->scopes[mi];
1828+ Scope *dst = comp_scope_new(c, src->name, src->def_node);
1829+ src = &c->scopes[mi]; /* realloc-safe */
1830+ int dst_idx = c->nscopes - 1;
1831+ dst->body = new_body;
1832+ if (new_body >= 0) walk_scope(c, new_body, dst_idx, ci);
1833+ dst->class_id = ci;
1834+ dst->is_cmethod = 1;
1835+ dst->yields = src->yields;
1836+ dst->nrequired = src->nrequired;
1837+ dst->rest_idx = src->rest_idx;
1838+ dst->kwrest_idx = src->kwrest_idx;
1839+ /* A bare-`new` create method returns the specialized subclass instance, so
1840+ pin its return type. Other specializations let normal return inference
1841+ compute the type from the cloned, ci-attributed body. */
1842+ if (has_new) {
1843+ dst->ret = ty_object(ci);
1844+ dst->ret_specialized = 1;
1845+ }
1846+ if (src->blk_param) dst->blk_param = strdup(src->blk_param);
1847+ dst->nparams = src->nparams;
1848+ if (src->nparams > 0) {
1849+ dst->pnames = malloc(sizeof(char *) * (size_t)src->nparams);
1850+ dst->pdefault = malloc(sizeof(int) * (size_t)src->nparams);
1851+ for (int p = 0; p < src->nparams; p++) {
1852+ dst->pnames[p] = src->pnames[p] ? strdup(src->pnames[p]) : NULL;
1853+ dst->pdefault[p] = src->pdefault ? src->pdefault[p] : -1;
1854+ if (dst->pnames[p]) { LocalVar *lv = scope_local_intern(dst, dst->pnames[p]); lv->is_param = 1; }
1855+ }
1856+ }
1857+ /* Recurse into the inherited intermediates this body reaches. Scan the
1858+ ORIGINAL mi body (cloned nodes are attributed to dst, not mi); a sub-clone
1859+ reallocs c->scopes/c->nscope, so use indices and refetch. */
1860+ int scan_n = nt->count;
1861+ for (int id = 0; id < scan_n; id++) {
1862+ if (c->nscope[id] != mi) continue;
1863+ const char *ty = nt_type(nt, id);
1864+ if (!ty || strcmp(ty, "CallNode")) continue;
1865+ if (nt_ref(nt, id, "receiver") >= 0) continue;
1866+ const char *nm = nt_str(nt, id, "name");
1867+ if (!nm || !strcmp(nm, "new")) continue;
1868+ int sub_def = -1;
1869+ int sub_mi = comp_cmethod_in_chain(c, ci, nm, &sub_def);
1870+ if (sub_mi < 0 || sub_def == ci) continue; /* unresolved, or ci-native */
1871+ int sub_new = 0;
1872+ if (cmethod_needs_specialization(c, sub_mi, ci, sub_def, &sub_new))
1873+ specialize_cmethod_for(c, sub_mi, sub_def, ci);
1874+ }
1875+}
1876+
17841877 /* `Subclass.create` where `create` is an inherited class method whose body
17851878 does `new(...)`: Ruby's bare `new` constructs the *calling* class, so copy
17861879 the inherited cls method into each calling subclass (the copy's class_id
17871880 makes codegen's `new` resolve to that subclass). The defining-class source
1788- is DCE'd unless it is itself called directly. Covers #224 / #229. */
1881+ is DCE'd unless it is itself called directly. Covers #224 / #229 / #1451. */
17891882 void specialize_inherited_cls_new(Compiler *c) {
17901883 NodeTable *nt = (NodeTable *)c->nt;
17911884 int snap = c->nscopes;
@@ -1809,48 +1902,11 @@
18091902 if (mi < 0 || def_cls == ci || mi >= snap) continue; /* not inherited */
18101903 int has_new = 0;
18111904 if (!cmethod_needs_specialization(c, mi, ci, def_cls, &has_new)) continue;
1812-
1813- /* Copy the inherited cls method scope, owned by ci, with its OWN clone of
1814- the body AST so locals/dispatches inside resolve against ci (the bare
1815- `new` constructs ci, and `instance = new` is typed obj_ci). */
1816- int src_body = c->scopes[mi].body;
1817- int new_body = src_body >= 0 ? nt_clone_subtree(nt, src_body) : -1;
1818- if (src_body >= 0 && new_body < 0) continue; /* clone failed: skip */
1819- comp_grow_node_arrays(c);
1820- did_clone = 1;
1821- Scope *src = &c->scopes[mi];
1822- Scope *dst = comp_scope_new(c, src->name, src->def_node);
1823- src = &c->scopes[mi]; /* realloc-safe */
1824- int dst_idx = c->nscopes - 1;
1825- dst->body = new_body;
1826- /* attribute the cloned subtree to the new scope */
1827- if (new_body >= 0) walk_scope(c, new_body, dst_idx, ci);
1828- dst->class_id = ci;
1829- dst->is_cmethod = 1;
1830- dst->yields = src->yields;
1831- dst->nrequired = src->nrequired;
1832- dst->rest_idx = src->rest_idx;
1833- dst->kwrest_idx = src->kwrest_idx;
1834- /* A bare-`new` create method returns the specialized subclass instance, so
1835- pin its return type. Other specializations (a body calling a subclass-
1836- specific class method) let the normal return inference compute the type
1837- from the cloned, ci-attributed body. */
1838- if (has_new) {
1839- dst->ret = ty_object(ci);
1840- dst->ret_specialized = 1;
1841- }
1842- if (src->blk_param) dst->blk_param = strdup(src->blk_param);
1843- dst->nparams = src->nparams;
1844- if (src->nparams > 0) {
1845- dst->pnames = malloc(sizeof(char *) * (size_t)src->nparams);
1846- dst->pdefault = malloc(sizeof(int) * (size_t)src->nparams);
1847- for (int p = 0; p < src->nparams; p++) {
1848- dst->pnames[p] = src->pnames[p] ? strdup(src->pnames[p]) : NULL;
1849- dst->pdefault[p] = src->pdefault ? src->pdefault[p] : -1;
1850- if (dst->pnames[p]) { LocalVar *lv = scope_local_intern(dst, dst->pnames[p]); lv->is_param = 1; }
1851- }
1852- }
1905+ /* Clone mi for ci and, transitively, the inherited intermediates it reaches
1906+ (#1451). nscopes growth below stands in for the old did_clone flag. */
1907+ specialize_cmethod_for(c, mi, def_cls, ci);
18531908 }
1909+ did_clone = (c->nscopes > snap);
18541910 /* DCE the now-shadowed source cls methods that are never called on their
18551911 own defining class. */
18561912 for (int s = 0; s < snap; s++) {