Commit 370ba007

370ba00705d3Merged

Ryan Seys <[email protected]> · 5 months ago · 6 files · +2 added · ~4 modified

Description

analyze,codegen: infer the each_with_object accumulator type from memo usage

An each_with_object([]) accumulator seeded with an empty array took its element type from the seed alone, defaulting to int -- so a block that pushed strings or mixed values built int storage and printed garbage, and a forwarded &callable was declined outright. Recover the element type from how the memo is actually filled.

  • ewo_memo_elem_type scans the block body for what is pushed onto the memo (memo << e / memo.push(e)) and unifies it into the accumulator element type. When the block only forwards to a callable value (callable.call(elem, memo), the value-forwarding desugar), it follows into the callable's definition -- inline lambda, local proc, or method(:m) -- and scans its second parameter the same way.
  • The inferred type overrides the bare int_array guess (the no-evidence default) rather than unifying with it, so an early guess cannot widen a later string/poly memo to poly_array across the inference fixpoint.
  • The forwarding desugar no longer declines each_with_object: an array receiver yields the (element, accumulator) pair to a two-param synthetic block. A {} hash memo stays unsupported (it is unsupported for a literal block too).
  • Codegen builds an empty [] seed as a fresh typed array of the inferred element type instead of materializing it as int storage.

Fixes both the literal each_with_object([]) { |x, m| m << x.to_s } case (previously int-typed) and &proc / &->(){} / &method(:m) forwarding.

Details

Commit
370ba00705d3
Parent
6cbe880fc0cd

src/analyze.hmodifiedView file

@@ -21,6 +21,11 @@
2121 /* Name of a block's idx-th required parameter, or NULL. */
2222 const char *block_param_name(Compiler *c, int block, int idx);
2323
24+/* Element type an `each_with_object([])` accumulator is filled with, inferred
25+ from how the memo param is pushed to (following a forwarded callable's body).
26+ TY_UNKNOWN when undetermined; callers default an empty `[]` to int_array. */
27+TyKind ewo_memo_elem_type(Compiler *c, int callid);
28+
2429 /* Class index when a receiverless instance_eval/exec resolves to self, else -1. */
2530 int ie_implicit_self_class(Compiler *c, int id);
2631