Commit a5de83a0

a5de83a09a4cMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

Propagate ivar types up the inheritance chain

A base-class method runs on subclass instances, so an ivar it reads must carry the union of every subclass's assignments to that ivar. An abstract base whose @x is only ever set to nil/placeholder in its own body otherwise sees that narrow type when it calls @x.foo, even though every concrete subclass stores a real object there -- e.g. optcarrot's Oscillator#reset calling @envelope.reset where @envelope is an Envelope only in the Pulse/Noise subclasses.

Post-fixpoint, unify each class's ivar types into all of its ancestors (monotonic widening, iterated to convergence). The base read then dispatches polymorphically on the runtime class.

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

Details

Commit
a5de83a09a4c
Parent
86f0ecad079f

src/analyze.cmodifiedView file

@@ -1289,6 +1289,33 @@
12891289 else sc->reachable = 0;
12901290 }
12911291
1292+ /* Propagate ivar types up the inheritance chain: a base-class method runs on
1293+ subclass instances, so an ivar it reads must carry the union of every
1294+ subclass's assignments. Without this, an abstract base whose @x is only set
1295+ to nil/placeholder there sees the wrong type when it calls `@x.foo`, even
1296+ though every concrete subclass assigns @x a real object. Monotonic (unify
1297+ only widens), so iterate to a fixpoint. */
1298+ for (int iter = 0; iter < 16; iter++) {
1299+ int prop_changed = 0;
1300+ for (int k = 0; k < c->nclasses; k++) {
1301+ ClassInfo *kc = &c->classes[k];
1302+ for (int iv = 0; iv < kc->nivars; iv++) {
1303+ TyKind kt = kc->ivar_types[iv];
1304+ if (kt == TY_UNKNOWN) continue;
1305+ const char *ivn = kc->ivars[iv];
1306+ for (int a = kc->parent; a >= 0; a = c->classes[a].parent) {
1307+ int ai = comp_ivar_index(&c->classes[a], ivn);
1308+ if (ai < 0) continue;
1309+ TyKind merged = ty_unify(c->classes[a].ivar_types[ai], kt);
1310+ if (merged != c->classes[a].ivar_types[ai]) {
1311+ c->classes[a].ivar_types[ai] = merged; prop_changed = 1;
1312+ }
1313+ }
1314+ }
1315+ }
1316+ if (!prop_changed) break;
1317+ }
1318+
12921319 /* A block param that inference never resolved holds a yielded value of
12931320 unknown static type (e.g. an element of a poly receiver iterated by
12941321 uniq!/each): declare it boxed (poly) rather than failing codegen. Set