Commit 30fec84f
30fec84f4ba5Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
Implement Array#map! / #collect! on typed arrays
Both were unresolved for int/str/float/sym/poly arrays. Transform each element in place (storing the block's result back) and return the mutated receiver. Typed arrays are homogeneous, so the block must keep the element type; a type-changing block (e.g. int_array.map! { |x| x.to_s }) falls through to the unresolved path in both passes rather than emit a mismatched store. Poly arrays re-box each result.
Refs #1216
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 30fec84f4ba5
- Parent
- e726b9c0be0f
spinel_analyze.rbmodifiedView file
@@ -6159,6 +6159,38 @@
61596159
end61606160
return "int_array"61616161
end6162+
# `map!` / `collect!` transform in place and return the receiver, so6163+
# the result keeps the receiver's array type. A typed (non-poly) array6164+
# is homogeneous, so only handle it when the block result keeps the6165+
# element type; a type-changing block (int_array.map! { |x| x.to_s })6166+
# falls through, matching codegen's guard.6167+
if (mname == "map!" || mname == "collect!") && @nd_block[nid] >= 06168+
if recv >= 06169+
rt_mb = infer_type(recv)6170+
if rt_mb == "poly_array"6171+
return rt_mb6172+
end6173+
if is_array_type(rt_mb) == 16174+
et_mb = iter_elem_type(rt_mb)6175+
bbody_mb = @nd_body[@nd_block[nid]]6176+
if bbody_mb >= 06177+
bbs_mb = get_stmts(bbody_mb)6178+
if bbs_mb.length > 06179+
bp_mb2 = get_block_param(nid, 0)6180+
push_scope6181+
if bp_mb2 != ""6182+
declare_var(bp_mb2, et_mb)6183+
end6184+
res_t_mb = infer_type(bbs_mb.last)6185+
pop_scope6186+
if map_bang_elem_matches(et_mb, res_t_mb) == 16187+
return rt_mb6188+
end6189+
end6190+
end6191+
end6192+
end6193+
end61626194
if mname == "map"61636195
if recv >= 061646196
# Declare bp inside a scope so infer_type sees the inner element type, not a shadowed outer local.@@ -31111,6 +31143,26 @@
3111131143
elem_type_of_array(recv_type)3111231144
end3111331145
31146+
# 1 iff a map!/collect! block result of type `result_t` can be stored31147+
# back into an array whose element kind is `elem` (homogeneous typed31148+
# arrays). Mirrors the codegen-side helper of the same name.31149+
def map_bang_elem_matches(elem, result_t)31150+
bt = base_type(result_t)31151+
if elem == "int"31152+
return (bt == "int") ? 1 : 031153+
end31154+
if elem == "string"31155+
return (bt == "string" || bt == "mutable_str") ? 1 : 031156+
end31157+
if elem == "float"31158+
return (bt == "float") ? 1 : 031159+
end31160+
if elem == "symbol"31161+
return (bt == "symbol") ? 1 : 031162+
end31163+
031164+
end31165+
3111431166
3111531167
3111631168
spinel_codegen.rbmodifiedView file
Loading diff…
test/array_map_bang.rbaddedView file
Loading diff…
test/array_map_bang.rb.expectedaddedView file
Loading diff…