Commit b13c605b

b13c605b20bdMerged

Yusuke Endoh <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): PtrArray accumulator for map blocks returning typed arrays

recv.map { ... [...] } whose block returns a typed array (int_array/float_array/str_array/sym_array) needs to accumulate into a PtrArray, not an IntArray. The IntArray accumulator path casts each pushed value through mrb_int — for an array element that's a heap pointer, the slot has the right bit pattern but no GC-traceable type, and the inner array can be collected mid-use.

Detect array-typed block return on the (Range/Integer-step) recv path: emit sp_PtrArray * accumulator and sp_PtrArray_push per element, falling back to IntArray for scalar block returns (the existing path).

Details

Commit
b13c605b20bd
Parent
1cf6a187efa1

spinel_codegen.rbmodifiedView file

@@ -28313,6 +28313,7 @@
2831328313 end
2831428314 @needs_int_array = 1
2831528315 @needs_gc = 1
28316+ ret_is_arr = false
2831628317 if block_ret_r == "string"
2831728318 @needs_str_array = 1
2831828319 emit(" sp_StrArray *" + tmp_arr + " = sp_StrArray_new();")
@@ -28476,7 +28477,18 @@
2847628477 pop_scope
2847728478 return tmp_arr
2847828479 else
28479- emit(" sp_IntArray *" + tmp_arr + " = sp_IntArray_new();")
28480+ # Block returning a homogeneous typed array (e.g.
28481+ # `[1, 6].map { (0..n).map { ... } }`) — accumulator must
28482+ # be a PtrArray so GC keeps each element alive (an IntArray
28483+ # accumulator with pointer-payload mrb_ints would let the
28484+ # inner arrays be collected).
28485+ ret_is_arr2 = (block_ret == "int_array" || block_ret == "float_array" || block_ret == "str_array" || block_ret == "sym_array")
28486+ if ret_is_arr2
28487+ @needs_ptr_array = 1
28488+ emit(" sp_PtrArray *" + tmp_arr + " = sp_PtrArray_new();")
28489+ else
28490+ emit(" sp_IntArray *" + tmp_arr + " = sp_IntArray_new();")
28491+ end
2848028492 emit(" SP_GC_ROOT(" + tmp_arr + ");")
2848128493 emit(" for (mrb_int " + tmp_i + " = 0; " + tmp_i + " < sp_IntArray_length(" + rc + "); " + tmp_i + "++) {")
2848228494 if bp_is_lambda == 1
@@ -28492,9 +28504,13 @@
2849228504 if stmts3.length > 0
2849328505 last = stmts3[stmts3.length - 1]
2849428506 val = compile_expr(last)
28495- emit(" sp_IntArray_push(" + tmp_arr + ", " + val + ");")
28507+ if ret_is_arr2
28508+ emit(" sp_PtrArray_push(" + tmp_arr + ", (void *)(" + val + "));")
28509+ else
28510+ emit(" sp_IntArray_push(" + tmp_arr + ", " + val + ");")
28511+ end
2849628512 else
28497- emit_map_default_push(tmp_arr, "int_array")
28513+ emit_map_default_push(tmp_arr, ret_is_arr2 ? "ptr_array" : "int_array")
2849828514 end
2849928515 end
2850028516 @indent = @indent - 1