Commit f411b843
f411b843fab0Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · +3 added · ~1 modified
Description
fix(codegen): defer element type for empty [] across function boundaries
Issue #58: writes performed on a parameter inside the callee did not feed back to the caller's variable type. So
def foo(ary); ary.push("foo"); end a = [] foo(a)
made foo's ary parameter an sp_IntArray * (the default for an
empty array literal), then the body's ary.push("foo") tried to push
a char * into an mrb_int slot — a C type error.
The conceptual fix is the deferred-element-type idea: an empty []
literal carries no element data, so its element type should be picked
by the first concrete use rather than nailed down at the literal site.
Implementation-wise that lives as a flag rather than a new type tag —
the new-type-tag form would have required parity branches at ~30+
existing int_array decision sites, including in the self-hosted
codegen itself.
Three new pieces:
-
Empty-flag tracking (
@scan_empty_flags,@meth_param_empty,@cls_meth_ptypes_empty). A local that was assigned an empty array literal gets the flag; a subsequent concrete-array write clears it. The flag flows from caller arg to callee param via the call-site scan. -
Body-push promotion (
infer_param_array_type_from_body). For each method whose param isint_arrayAND the empty-flag is set, scan the body forparam.push(known_elem). If every observed push agrees on a single concrete element type (string / float / symbol), promote@meth_param_types[mi][k](or@cls_meth_ptypes) to the matching typed-array. Without the empty-flag guard, a caller passing a real int_array ([1, 2, 3]) would be silently retyped — the flag keeps the promotion sound. Without the single-type check, a body that pushes mixed types stays atint_arrayand surfaces as a real error rather than picking one arbitrarily. Runs inside the existing iterative inference loop. -
Caller back-propagation (in
scan_localsitself). When the call site's arg is a local with empty-flag and the matching param has been promoted to a concrete typed-array, lift the local's type to match. The loop converges over a few iterations because the inference signature now includes@cls_meth_ptypes.
Plus two codegen-side adjustments:
compile_call_args_with_defaultsemitssp_StrArray_new()/sp_FloatArray_new()directly when the call site's empty-[]literal targets a typed-array param. Without this the literal always emittedsp_IntArray_new(), producing a -Wincompatible-pointer-types warning at the call.detect_poly_in_nodetreats an empty literal as compatible with any concrete typed-array param. Otherwise the body-promotedstr_arrayparam would mismatch the caller'sint_array-inferred[]and bounce the param back topoly.
Coverage:
- test/empty_array_param_local.rb — issue's exact reproducer
- test/empty_array_param_direct.rb —
foo([])(literal at call site) - test/empty_array_param_class_method.rb — instance method on user class
Inheritance gap (class Child < Base; end; Child.new.method_on_base([]))
is intentionally out of scope: the existing class-method param-from-
caller pass doesn't walk the inheritance chain to populate the parent
class's @cls_meth_ptypes, so the body-promotion guard never fires.
Filing as follow-up.
Bootstrap fixed-point clean; 131 tests + 56 benches pass.
Closes #58
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- f411b843fab0
- Parent
- fdc0137303d7
spinel_codegen.rbmodifiedView file
@meth_names = "".split(",") @meth_param_names = "".split(",") @meth_param_types = "".split(",") # Per-param "deferred element" flag: "1" means at least one caller # passed an empty `[]` literal (or a local that itself was assigned # an empty literal). Used by the param body-push promotion pass # (issue #58) to decide whether the param's int_array can be safely # promoted to a concrete typed-array based on body usage. @meth_param_empty = "".split(",") @meth_return_types = "".split(",") @meth_body_ids = [] @meth_has_defaults = "".split(",") @cls_meth_returns = "".split(",") @cls_meth_bodies = "".split(",") @cls_meth_defaults = "".split(",") # Mirror of @meth_param_empty for class methods. Pipe-separated by # method, comma-separated by param. Issue #58. @cls_meth_ptypes_empty = "".split(",") @cls_attr_readers = "".split(",") @cls_attr_writers = "".split(",") @cls_cmeth_names = "".split(",") 0 end # Issue #58: empty `[]` literal needs deferred element-type # resolution. This helper distinguishes `[]` from `[1, 2, 3]` so the # promotion machinery can know "writes haven't fixed the element type # yet, so a later push can still pick it". def is_empty_array_literal(nid) if nid < 0 return 0 end if @nd_type[nid] != "ArrayNode" return 0 end elems = parse_id_list(@nd_elements[nid]) if elems.length == 0 return 1 end 0 end def base_type(t) if t.length > 1 && t[t.length - 1] == "?" return t[0, t.length - 1] params = collect_params_str(sid) @meth_param_names.push(params) @meth_param_types.push(collect_ptypes_str(sid, -1)) @meth_param_empty.push("") @meth_return_types.push("int") @meth_body_ids.push(@nd_body[sid]) @meth_has_yield.push(0) @cls_meth_returns.push("void") @cls_meth_bodies.push("-2") @cls_meth_defaults.push(init_defaults) @cls_meth_ptypes_empty.push("") else @cls_meth_names.push("") @cls_meth_params.push("") @cls_meth_returns.push("") @cls_meth_bodies.push("") @cls_meth_defaults.push("") @cls_meth_ptypes_empty.push("") end @cls_attr_readers.push(attr_readers) @cls_attr_writers.push(attr_writers) @cls_meth_returns[ci] = @cls_meth_returns[ci] + ";" + ret @cls_meth_bodies[ci] = @cls_meth_bodies[ci] + ";" + body_id.to_s @cls_meth_defaults[ci] = @cls_meth_defaults[ci] + "|" + defaults @cls_meth_ptypes_empty[ci] = @cls_meth_ptypes_empty[ci] + "|" else @cls_meth_names[ci] = name @cls_meth_params[ci] = params @cls_meth_returns[ci] = ret @cls_meth_bodies[ci] = body_id.to_s @cls_meth_defaults[ci] = defaults @cls_meth_ptypes_empty[ci] = "" end end @meth_names.push(mname) @meth_param_names.push(params_str) @meth_param_types.push(ptypes_str) @meth_param_empty.push("") @meth_return_types.push("int") @meth_body_ids.push(body_id) @meth_has_defaults.push(defaults_str) @meth_names.push(mname) @meth_param_names.push(params_str) @meth_param_types.push(ptypes_str) @meth_param_empty.push("") @meth_return_types.push("int") @meth_body_ids.push(body_id) @meth_has_defaults.push("") @meth_names.push(mname + "_cls_" + dmname) @meth_param_names.push(collect_params_str(sid)) @meth_param_types.push(collect_ptypes_str(sid, -1)) @meth_param_empty.push("") @meth_return_types.push("int") @meth_body_ids.push(@nd_body[sid]) @meth_has_yield.push(0) @cls_meth_returns.push("") @cls_meth_bodies.push("") @cls_meth_defaults.push("") @cls_meth_ptypes_empty.push("") @cls_attr_readers.push("") @cls_attr_writers.push("") @cls_cmeth_names.push("") end end # Issue #58: collect every element type seen in `pname.push(elem)` # or `pname << elem` patterns under nid. The deferred-element-type # promotion pass uses this to decide what concrete typed-array a # parameter should be promoted to when callers all passed empty # `[]` literals. def collect_param_push_elem_types(nid, pname, acc) if nid < 0 return end if @nd_type[nid] == "CallNode" if @nd_name[nid] == "push" || @nd_name[nid] == "<<" recv = @nd_receiver[nid] if recv >= 0 && @nd_type[recv] == "LocalVariableReadNode" if @nd_name[recv] == pname args_id = @nd_arguments[nid] if args_id >= 0 aargs = get_args(args_id) if aargs.length > 0 at = infer_type(aargs[0]) if not_in(at, acc) == 1 acc.push(at) end end end end end end end if @nd_body[nid] >= 0 collect_param_push_elem_types(@nd_body[nid], pname, acc) end stmts = parse_id_list(@nd_stmts[nid]) k = 0 while k < stmts.length collect_param_push_elem_types(stmts[k], pname, acc) k = k + 1 end if @nd_expression[nid] >= 0 collect_param_push_elem_types(@nd_expression[nid], pname, acc) end if @nd_left[nid] >= 0 collect_param_push_elem_types(@nd_left[nid], pname, acc) end if @nd_right[nid] >= 0 collect_param_push_elem_types(@nd_right[nid], pname, acc) end if @nd_arguments[nid] >= 0 collect_param_push_elem_types(@nd_arguments[nid], pname, acc) end args2 = parse_id_list(@nd_args[nid]) k = 0 while k < args2.length collect_param_push_elem_types(args2[k], pname, acc) k = k + 1 end if @nd_receiver[nid] >= 0 collect_param_push_elem_types(@nd_receiver[nid], pname, acc) end if @nd_predicate[nid] >= 0 collect_param_push_elem_types(@nd_predicate[nid], pname, acc) end if @nd_subsequent[nid] >= 0 collect_param_push_elem_types(@nd_subsequent[nid], pname, acc) end if @nd_else_clause[nid] >= 0 collect_param_push_elem_types(@nd_else_clause[nid], pname, acc) end if @nd_block[nid] >= 0 collect_param_push_elem_types(@nd_block[nid], pname, acc) end end # Issue #58: promote each top-level method parameter from int_array # to a concrete typed-array (str_array, float_array, sym_array) # when (a) every caller passed an empty `[]` literal — guarded by # @meth_param_empty[mi][k] == "1" — and (b) the body's pushes on # that parameter all agree on a single concrete element type. # Without (a), a caller passing a real int_array would be silently # miscompiled. Without (b), a body that pushes mixed types should # surface as a type error rather than picking one arbitrarily. def infer_param_array_type_from_body iter = 0 changed = 1 while changed == 1 && iter < 4 changed = 0 iter = iter + 1 # Top-level methods. Set up the method's scope so that # collect_param_push_elem_types' infer_type calls can resolve # other parameters (e.g. `buf.push(name)` where `name` is a # string-typed parameter on the same method). mi = 0 while mi < @meth_names.length bid = @meth_body_ids[mi] if bid >= 0 pnames = @meth_param_names[mi].split(",") ptypes = @meth_param_types[mi].split(",") empty_str = "" if mi < @meth_param_empty.length empty_str = @meth_param_empty[mi] end empties = empty_str.split(",") push_scope dj = 0 while dj < pnames.length pt = "int" if dj < ptypes.length pt = ptypes[dj] end declare_var(pnames[dj], pt) dj = dj + 1 end ml = "".split(",") mt = "".split(",") scan_locals(bid, ml, mt, pnames) lk = 0 while lk < ml.length declare_var(ml[lk], mt[lk]) lk = lk + 1 end promoted = 0 pk = 0 while pk < pnames.length if pk < ptypes.length && pk < empties.length if empties[pk] == "1" && ptypes[pk] == "int_array" elem_acc = "".split(",") collect_param_push_elem_types(bid, pnames[pk], elem_acc) promoted_type = empty_array_promotion_for(elem_acc) if promoted_type != "" ptypes[pk] = promoted_type if promoted_type == "str_array" @needs_str_array = 1 end if promoted_type == "float_array" @needs_float_array = 1 end promoted = 1 changed = 1 end end end pk = pk + 1 end pop_scope if promoted == 1 @meth_param_types[mi] = ptypes.join(",") end end mi = mi + 1 end # Class methods (instance methods on user classes). Same # scope-setup so `buf.push(name)` resolves the param type. ci = 0 while ci < @cls_names.length @current_class_idx = ci all_params = @cls_meth_params[ci].split("|") all_ptypes = @cls_meth_ptypes[ci].split("|") all_empty = @cls_meth_ptypes_empty[ci].split("|") bodies = @cls_meth_bodies[ci].split(";") cls_changed = 0 mj = 0 while mj < all_params.length bid = -1 if mj < bodies.length bid = bodies[mj].to_i end if bid >= 0 cm_pnames = all_params[mj].split(",") cm_ptypes = "".split(",") cm_empties = "".split(",") if mj < all_ptypes.length cm_ptypes = all_ptypes[mj].split(",") end if mj < all_empty.length cm_empties = all_empty[mj].split(",") end push_scope cdj = 0 while cdj < cm_pnames.length cpt = "int" if cdj < cm_ptypes.length cpt = cm_ptypes[cdj] end declare_var(cm_pnames[cdj], cpt) cdj = cdj + 1 end cml = "".split(",") cmt = "".split(",") scan_locals(bid, cml, cmt, cm_pnames) cmlk = 0 while cmlk < cml.length declare_var(cml[cmlk], cmt[cmlk]) cmlk = cmlk + 1 end pk = 0 cm_promoted = 0 while pk < cm_pnames.length if pk < cm_ptypes.length && pk < cm_empties.length if cm_empties[pk] == "1" && cm_ptypes[pk] == "int_array" elem_acc = "".split(",") collect_param_push_elem_types(bid, cm_pnames[pk], elem_acc) promoted_type = empty_array_promotion_for(elem_acc) if promoted_type != "" cm_ptypes[pk] = promoted_type if promoted_type == "str_array" @needs_str_array = 1 end if promoted_type == "float_array" @needs_float_array = 1 end cm_promoted = 1 changed = 1 end end end pk = pk + 1 end pop_scope if cm_promoted == 1 all_ptypes[mj] = cm_ptypes.join(",") cls_changed = 1 end end mj = mj + 1 end if cls_changed == 1 @cls_meth_ptypes[ci] = all_ptypes.join("|") end ci = ci + 1 end @current_class_idx = -1 end end # Helper: given the set of element types observed in pname.push(...) # patterns, return the typed-array tag to promote to, or "" if the # observations don't agree on a single concrete type. def empty_array_promotion_for(elem_acc) if elem_acc.length != 1 return "" end if elem_acc[0] == "string" return "str_array" end if elem_acc[0] == "float" return "float_array" end if elem_acc[0] == "symbol" return "sym_array" end "" end # Does class `ci` provide `mname` as a reader, writer, or method? # Walks parent classes for inherited members. def class_has_method(ci, mname) while k < arg_ids.length at = infer_type_deep(arg_ids[k]) if k < ptypes.length ct = ptypes[k] # Skip rest/splat params (int_array) - they handle multiple args if ct == "int_array" k = k + 1 next ct = ptypes[k] # Skip rest/splat params (int_array) - they handle multiple args if ct == "int_array" k = k + 1 next end # Issue #58: an empty `[]` literal at the call site is # compatible with any concrete typed-array param type. # Without this, `foo([])` against a body-promoted # `str_array` param triggers the ct != at mismatch and # bumps the param back to poly. if is_empty_array_literal(arg_ids[k]) == 1 if ct == "str_array" || ct == "float_array" || ct == "sym_array" || is_ptr_array_type(ct) == 1 k = k + 1 next end end if ct != at if ct != "poly" # refines. Identical fingerprints between successive iterations means a # fixed point has been reached and further iterations are wasted work. def inference_signature @meth_return_types.join("|") + "/" + @cls_ivar_types.join("|") + "/" + @meth_param_types.join("|") @meth_return_types.join("|") + "/" + @cls_ivar_types.join("|") + "/" + @meth_param_types.join("|") + "/" + @cls_meth_ptypes.join("/") end def compile while iter < 4 infer_all_returns infer_ivar_types_from_writers # Issue #58: after scan_locals has populated @meth_param_empty # via the per-call-site forward propagation, promote int_array # params to concrete typed-arrays where bodies push known types. # Then the next iteration's scan_locals back-propagates those # promoted types to caller-side locals. infer_param_array_type_from_body detect_poly_params cur_sig = inference_signature if cur_sig == prev_sig # a fresh (empty) names array. if names.length == 0 @scan_literal_flags = "".split(",") # Parallel to `names`: "1" if every write to this local so far was # an empty `[]` literal — used to defer the array element type # until first `push` (issue #58). A subsequent write with a # concrete element resets the flag to "". @scan_empty_flags = "".split(",") end if @nd_type[nid] == "MultiWriteNode" targets = parse_id_list(@nd_targets[nid]) names.push(lname) types.push("int") @scan_literal_flags.push("") @scan_empty_flags.push("") end end end else @scan_literal_flags.push("") end # Track empty-array literal so a later push() can promote # the local's element type (issue #58). if is_empty_array_literal(@nd_expression[nid]) == 1 @scan_empty_flags.push("1") else @scan_empty_flags.push("") end end else if not_in(lname, params) == 1 # Check if type changed at = infer_type(@nd_expression[nid]) # Concrete (non-empty) array overwrite clears the deferred # element-type flag — a `[1,2,3]` write commits to int_array. if is_empty_array_literal(@nd_expression[nid]) == 0 ei = 0 while ei < names.length if names[ei] == lname && ei < @scan_empty_flags.length @scan_empty_flags[ei] = "" end ei = ei + 1 end end ki = 0 while ki < names.length if names[ki] == lname end end end # Issue #58: empty-array param promotion at instance-method call # sites — `obj.method(arg)`. Same forward/backward propagation as # the top-level branch below, but reads/writes the per-class # @cls_meth_ptypes / @cls_meth_ptypes_empty storage. if @nd_type[nid] == "CallNode" icm_recv = @nd_receiver[nid] if icm_recv >= 0 icm_rt = infer_type(icm_recv) # When the receiver is a local declared in this same # scan_locals pass (`r = Recorder.new` followed by `r.method(...)`), # infer_type still returns "int" because we haven't called # declare_var yet. Fall back to the names/types accumulator. if icm_rt == "int" && @nd_type[icm_recv] == "LocalVariableReadNode" icm_recv_name = @nd_name[icm_recv] icm_ni0 = 0 while icm_ni0 < names.length if names[icm_ni0] == icm_recv_name icm_rt = types[icm_ni0] end icm_ni0 = icm_ni0 + 1 end end if is_obj_type(icm_rt) == 1 icm_cname = icm_rt[4, icm_rt.length - 4] icm_ci = find_class_idx(icm_cname) if icm_ci >= 0 icm_mname = @nd_name[nid] icm_midx = cls_find_method_direct(icm_ci, icm_mname) # Walk parents if not found on the receiver class itself icm_owner_ci = icm_ci if icm_midx < 0 icm_owner_name = find_method_owner(icm_ci, icm_mname) if icm_owner_name != "" icm_owner_ci = find_class_idx(icm_owner_name) if icm_owner_ci >= 0 icm_midx = cls_find_method_direct(icm_owner_ci, icm_mname) end end end if icm_midx >= 0 icm_args_id = @nd_arguments[nid] if icm_args_id >= 0 icm_aargs = get_args(icm_args_id) icm_all_ptypes = @cls_meth_ptypes[icm_owner_ci].split("|") icm_all_empty = @cls_meth_ptypes_empty[icm_owner_ci].split("|") icm_ptypes = "".split(",") icm_empties = "".split(",") if icm_midx < icm_all_ptypes.length icm_ptypes = icm_all_ptypes[icm_midx].split(",") end if icm_midx < icm_all_empty.length icm_empties = icm_all_empty[icm_midx].split(",") end icm_changed = 0 icm_k = 0 while icm_k < icm_aargs.length icm_arg_id = icm_aargs[icm_k] icm_arg_is_empty = is_empty_array_literal(icm_arg_id) icm_local_idx = -1 if @nd_type[icm_arg_id] == "LocalVariableReadNode" icm_arg_lname = @nd_name[icm_arg_id] icm_ni = 0 while icm_ni < names.length if names[icm_ni] == icm_arg_lname icm_local_idx = icm_ni end icm_ni = icm_ni + 1 end if icm_local_idx >= 0 && icm_local_idx < @scan_empty_flags.length if @scan_empty_flags[icm_local_idx] == "1" icm_arg_is_empty = 1 end end end if icm_arg_is_empty == 1 while icm_empties.length <= icm_k icm_empties.push("") end if icm_empties[icm_k] != "1" icm_empties[icm_k] = "1" icm_changed = 1 end end if icm_local_idx >= 0 && icm_k < icm_ptypes.length icm_pt = icm_ptypes[icm_k] if types[icm_local_idx] == "int_array" && icm_local_idx < @scan_empty_flags.length && @scan_empty_flags[icm_local_idx] == "1" if icm_pt == "str_array" types[icm_local_idx] = "str_array" @needs_str_array = 1 end if icm_pt == "float_array" types[icm_local_idx] = "float_array" @needs_float_array = 1 end if icm_pt == "sym_array" types[icm_local_idx] = "sym_array" end end end icm_k = icm_k + 1 end if icm_changed == 1 icm_all_empty[icm_midx] = icm_empties.join(",") @cls_meth_ptypes_empty[icm_owner_ci] = icm_all_empty.join("|") end end end end end end end # Issue #58: empty-array param promotion at top-level function # call sites. Two directions in one place: # (a) Forward: if `arg` is `[]` literal or a local with the # empty flag set, mark @meth_param_empty[mi][k] = "1" so a # later body-promotion pass can refine the param type. # (b) Backward: if @meth_param_types[mi][k] has already been # promoted to a concrete typed-array (str_array, etc.) and # `arg` is a local with the empty flag, upgrade the local's # type to match — this is what propagates the deferred # resolution back to the caller's variable. if @nd_type[nid] == "CallNode" if @nd_receiver[nid] < 0 ea_mname = @nd_name[nid] ea_mi = find_method_idx(ea_mname) if ea_mi >= 0 ea_args_id = @nd_arguments[nid] if ea_args_id >= 0 ea_aargs = get_args(ea_args_id) ea_ptypes = @meth_param_types[ea_mi].split(",") ea_empty_str = "" if ea_mi < @meth_param_empty.length ea_empty_str = @meth_param_empty[ea_mi] end ea_empties = ea_empty_str.split(",") ea_changed = 0 ea_k = 0 while ea_k < ea_aargs.length ea_arg_id = ea_aargs[ea_k] ea_arg_is_empty = is_empty_array_literal(ea_arg_id) ea_local_idx = -1 if @nd_type[ea_arg_id] == "LocalVariableReadNode" ea_arg_lname = @nd_name[ea_arg_id] ea_ni = 0 while ea_ni < names.length if names[ea_ni] == ea_arg_lname ea_local_idx = ea_ni end ea_ni = ea_ni + 1 end if ea_local_idx >= 0 && ea_local_idx < @scan_empty_flags.length if @scan_empty_flags[ea_local_idx] == "1" ea_arg_is_empty = 1 end end end if ea_arg_is_empty == 1 while ea_empties.length <= ea_k ea_empties.push("") end if ea_empties[ea_k] != "1" ea_empties[ea_k] = "1" ea_changed = 1 end end # Backward: param already promoted, lift the local too. if ea_local_idx >= 0 && ea_k < ea_ptypes.length ea_pt = ea_ptypes[ea_k] if types[ea_local_idx] == "int_array" && ea_local_idx < @scan_empty_flags.length && @scan_empty_flags[ea_local_idx] == "1" if ea_pt == "str_array" types[ea_local_idx] = "str_array" @needs_str_array = 1 end if ea_pt == "float_array" types[ea_local_idx] = "float_array" @needs_float_array = 1 end if ea_pt == "sym_array" types[ea_local_idx] = "sym_array" end end end ea_k = ea_k + 1 end if ea_changed == 1 @meth_param_empty[ea_mi] = ea_empties.join(",") end end end end end # Detect hash value type from h["key"] = val if @nd_type[nid] == "CallNode" if @nd_name[nid] == "[]=" k = k + 1 next end # Issue #58: empty `[]` literal at the call site needs to # construct the right typed-array container. The literal's # own infer_type returns int_array (compile_array_literal # emits sp_IntArray_new()), but if the param is a concrete # typed-array, emit the matching constructor instead. if is_empty_array_literal(positional_ids[k]) == 1 if ptypes[k] == "str_array" @needs_str_array = 1 @needs_gc = 1 result = result + "sp_StrArray_new()" k = k + 1 next end if ptypes[k] == "float_array" @needs_float_array = 1 @needs_gc = 1 result = result + "sp_FloatArray_new()" k = k + 1 next end if ptypes[k] == "sym_array" @needs_int_array = 1 @needs_gc = 1 result = result + "sp_IntArray_new()" k = k + 1 next end end end result = result + compile_expr(positional_ids[k]) elsetest/empty_array_param_class_method.rbaddedView file
Loading diff…
test/empty_array_param_direct.rbaddedView file
Loading diff…
test/empty_array_param_local.rbaddedView file
Loading diff…