Commit 533e8aa3

533e8aa3a861Merged

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

Description

Infer the return type of a class/module self-method that yields

A class/module self-method (singleton method, def self.go) whose value comes from yield had its return type left untyped (poly): the block's value type was never propagated back, so every downstream use of the result (puts, .to_s, Integer(...)) degraded or failed to compile. Instance-method yield already worked.

yield_value_type scans call sites that pass a block to method mi and unifies their block-body types into mi's yielded value type. For a receiverful call it resolved the callee only for an object-instance receiver (obj.m { }) or the Klass.new { } constructor case; a call on a class/module constant (Klass.m { } / Mod.m { }) fell through unmatched, so no block type was collected and the self-method stayed poly. Resolve a ConstantReadNode receiver to its class/module and look up the singleton method via comp_cmethod_in_chain so the block's value type flows back into the self-method's return type.

(The def Klass.m form defined outside the class body is a separate pre-existing gap -- it is untyped even without yield -- and is not addressed here.)

Fixes #1446

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

Details

Commit
533e8aa3a861
Parent
5f566f22d197

src/analyze_util.cmodifiedView file

@@ -215,6 +215,15 @@
215215 int nci = comp_class_index(c, nt_str(nt, crecv, "name"));
216216 if (nci >= 0) rmi = comp_method_in_chain(c, nci, "initialize", NULL);
217217 }
218+ /* `Klass.m { block }` / `Mod.m { block }`: a class/module self-method
219+ (singleton). Resolve the constant and look up its singleton method so
220+ the block's value type flows back to m's return type -- instance
221+ methods resolve via the ty_is_object arm above (#1446). */
222+ else if (nt_type(nt, crecv) &&
223+ !strcmp(nt_type(nt, crecv), "ConstantReadNode")) {
224+ int nci = comp_class_index(c, nt_str(nt, crecv, "name"));
225+ if (nci >= 0) rmi = comp_cmethod_in_chain(c, nci, cn, NULL);
226+ }
218227 }
219228 if (rmi != mi) continue;
220229 /* `mi(&b)` / `mi(...)`: the call forwards the block of its enclosing