Commit efe8e57e

efe8e57e0a17Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): convert *_ptr_array → poly_array at call boundary

When a function's parameter is inferred as poly_array (because at least one caller passes a heterogeneous literal) but another caller passes a homogeneous typed PtrArray ([A.new, A.new] → sp_PtrArray of obj_A), the two layouts are incompatible at the C boundary -- PtrArray slots are raw void * while PolyArray slots are sp_RbVal with tag + cls_id. The call emitted -Wincompatible-pointer-types and the function received memory it couldn't decode.

compile_expr_for_expected_type now detects *_ptr_array → poly_array and emits an inline conversion: allocate a fresh PolyArray and box each element via sp_box_obj(elem, cls_id), where cls_id comes from the ptr_array's elem type (obj_<Class>). The boxed array is then passed as the call arg. GC-rooted during construction so the per-element box doesn't free the half-built array.

Limited to obj-typed elements for v1; nested ptr_array_ptr_array and other non-obj elements fall through to the existing path.

Fixes #582.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
efe8e57e0a17
Parent
d48348e846f8

spinel_codegen.rbmodifiedView file

@@ -5396,6 +5396,34 @@
53965396 if expected_base == "poly" && at != "poly"
53975397 return box_value_to_poly(at, val)
53985398 end
5399+ # `*_ptr_array → poly_array` at the call boundary. The callee
5400+ # was inferred to take poly_array (because at least one caller
5401+ # passes a heterogeneous literal) but this caller passes a
5402+ # homogeneous typed PtrArray. The two layouts are incompatible
5403+ # (PtrArray is raw `void *` slots; PolyArray is sp_RbVal slots
5404+ # with tag + cls_id), so convert at the boundary: allocate a
5405+ # fresh PolyArray and box each PtrArray element via
5406+ # sp_box_obj(elem, cls_id). Issue #582.
5407+ if expected_base == "poly_array" && is_ptr_array_type(at) == 1
5408+ elem_t_pa = ptr_array_elem_type(at)
5409+ if is_obj_type(elem_t_pa) == 1
5410+ @needs_gc = 1
5411+ @needs_rb_value = 1
5412+ cname_pa = elem_t_pa[4, elem_t_pa.length - 4]
5413+ cidx_pa = find_class_idx(cname_pa)
5414+ if cidx_pa >= 0
5415+ cid_pa = cls_id_for_user_internal(cidx_pa)
5416+ src_pa = new_temp
5417+ dst_pa = new_temp
5418+ ii_pa = new_temp
5419+ emit(" sp_PtrArray *" + src_pa + " = " + val + ";")
5420+ emit(" sp_PolyArray *" + dst_pa + " = sp_PolyArray_new();")
5421+ emit(" SP_GC_ROOT(" + dst_pa + ");")
5422+ emit(" for (mrb_int " + ii_pa + " = 0; " + ii_pa + " < sp_PtrArray_length(" + src_pa + "); " + ii_pa + "++) sp_PolyArray_push(" + dst_pa + ", sp_box_obj(sp_PtrArray_get(" + src_pa + ", " + ii_pa + "), " + cid_pa.to_s + "LL));")
5423+ return dst_pa
5424+ end
5425+ end
5426+ end
53995427 if expected_base == "string"
54005428 if at == "poly"
54015429 @needs_rb_value = 1