Commit 6f513a0b

6f513a0b5956Merged

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

Description

Implement Struct#to_a and #values

A Struct instance had no to_a/values, so Person.new("Alice", 30).to_a raised "undefined method". Gather the member values (in declaration order) into a poly_array, since struct members can be heterogeneous. Each member is read from its ivar and boxed by its inferred type.

Gated on a synthetic struct (initialize body marker "-2") that does not define its own to_a/values, so a user override still wins. The struct receiver is GC-rooted while its members are read across the PolyArray allocations.

Refs #1238

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

Details

Commit
6f513a0b5956
Parent
f5e38f7d8013

spinel_analyze.rbmodifiedView file

@@ -5582,6 +5582,15 @@
55825582 # of [key, value] pairs). Issue #738.
55835583 # `to_h` on a Hash variant is identity. Surface so the caller
55845584 # gets the recv's exact type rather than an unresolved fallback.
5585+ # Struct member accessors: `S.new(...).to_a` / `.values` collect the
5586+ # member values into a poly_array (members can be heterogeneous).
5587+ if mname == "to_a" || mname == "values"
5588+ sci_sv = struct_recv_ci(recv)
5589+ if sci_sv >= 0 && cls_find_method(sci_sv, mname) < 0
5590+ @needs_poly_array = 1
5591+ return "poly_array"
5592+ end
5593+ end
55855594 if mname == "to_h"
55865595 if recv >= 0
55875596 rt = infer_type(recv)
@@ -16944,6 +16953,24 @@
1694416953 0
1694516954 end
1694616955
16956+ # If recv is statically a synthetic-struct instance, return its
16957+ # class index; otherwise -1. Used to type Struct#to_a/values/to_h.
16958+ def struct_recv_ci(recv)
16959+ if recv < 0
16960+ return -1
16961+ end
16962+ rt = base_type(infer_type(recv))
16963+ if is_obj_type(rt) == 0
16964+ return -1
16965+ end
16966+ cn = rt[4, rt.length - 4]
16967+ ci = find_class_idx(cn)
16968+ if ci >= 0 && synthetic_struct_class?(ci) == 1
16969+ return ci
16970+ end
16971+ -1
16972+ end
16973+
1694716974 # Post-pass for #634 shape A. An optional param with an explicit
1694816975 # `= nil` default whose call sites then widen its type to a
1694916976 # Post-pass for #634 shape B. An ivar exposed by attr_reader /