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 end
61606160 return "int_array"
61616161 end
6162+ # `map!` / `collect!` transform in place and return the receiver, so
6163+ # the result keeps the receiver's array type. A typed (non-poly) array
6164+ # is homogeneous, so only handle it when the block result keeps the
6165+ # 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] >= 0
6168+ if recv >= 0
6169+ rt_mb = infer_type(recv)
6170+ if rt_mb == "poly_array"
6171+ return rt_mb
6172+ end
6173+ if is_array_type(rt_mb) == 1
6174+ et_mb = iter_elem_type(rt_mb)
6175+ bbody_mb = @nd_body[@nd_block[nid]]
6176+ if bbody_mb >= 0
6177+ bbs_mb = get_stmts(bbody_mb)
6178+ if bbs_mb.length > 0
6179+ bp_mb2 = get_block_param(nid, 0)
6180+ push_scope
6181+ if bp_mb2 != ""
6182+ declare_var(bp_mb2, et_mb)
6183+ end
6184+ res_t_mb = infer_type(bbs_mb.last)
6185+ pop_scope
6186+ if map_bang_elem_matches(et_mb, res_t_mb) == 1
6187+ return rt_mb
6188+ end
6189+ end
6190+ end
6191+ end
6192+ end
6193+ end
61626194 if mname == "map"
61636195 if recv >= 0
61646196 # 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 end
3111331145
31146+ # 1 iff a map!/collect! block result of type `result_t` can be stored
31147+ # back into an array whose element kind is `elem` (homogeneous typed
31148+ # 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 : 0
31153+ end
31154+ if elem == "string"
31155+ return (bt == "string" || bt == "mutable_str") ? 1 : 0
31156+ end
31157+ if elem == "float"
31158+ return (bt == "float") ? 1 : 0
31159+ end
31160+ if elem == "symbol"
31161+ return (bt == "symbol") ? 1 : 0
31162+ end
31163+ 0
31164+ end
31165+
3111431166
3111531167
3111631168