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 caller55845584
# gets the recv's exact type rather than an unresolved fallback.5585+
# Struct member accessors: `S.new(...).to_a` / `.values` collect the5586+
# 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) < 05590+
@needs_poly_array = 15591+
return "poly_array"5592+
end5593+
end55855594
if mname == "to_h"55865595
if recv >= 055875596
rt = infer_type(recv)@@ -16944,6 +16953,24 @@
1694416953
01694516954
end1694616955
16956+
# If recv is statically a synthetic-struct instance, return its16957+
# class index; otherwise -1. Used to type Struct#to_a/values/to_h.16958+
def struct_recv_ci(recv)16959+
if recv < 016960+
return -116961+
end16962+
rt = base_type(infer_type(recv))16963+
if is_obj_type(rt) == 016964+
return -116965+
end16966+
cn = rt[4, rt.length - 4]16967+
ci = find_class_idx(cn)16968+
if ci >= 0 && synthetic_struct_class?(ci) == 116969+
return ci16970+
end16971+
-116972+
end16973+
1694716974
# Post-pass for #634 shape A. An optional param with an explicit1694816975
# `= nil` default whose call sites then widen its type to a1694916976
# Post-pass for #634 shape B. An ivar exposed by attr_reader /spinel_codegen.rbmodifiedView file
Loading diff…
test/struct_to_a_values.rbaddedView file
Loading diff…
test/struct_to_a_values.rb.expectedaddedView file
Loading diff…