Commit a332dd6e

a332dd6e56d8Merged

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

Description

fix(codegen): infer_call_type for attr-writer returns rhs type

@a = obj.attr = val chains mistyped the outer LHS as int. infer_call_type had no special case for attr-writer CallNodes (obj.attr = val), so it fell through to the int default. Codegen was emitting the right C-level assignment expression (rc->iv_attr = arg) (which evaluates to the rhs in C), but the surrounding LHS was declared mrb_int, so outer = (rc->iv_attr = obj_value) typed the outer slot as int and later uses went through the wrong dispatch.

Fix: when infer_call_type sees a CallNode whose name ends with = (excluding the comparison operators == / != / <= / >=), and the receiver is obj-typed and has an attr_writer for the slot, return the rhs argument's type. Mirrors Ruby's assignment-expression semantics — the chain's value is the rhs.

The codegen at compile_call_expr already returns the C assignment expression (rc->iv_attr = arg0_w) for this shape, so the fix is purely on the inference side.

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

Details

Commit
a332dd6e56d8
Parent
fea5369dddb0

spinel_codegen.rbmodifiedView file

@@ -2244,6 +2244,34 @@
22442244 end
22452245 end
22462246
2247+ # `obj.attr = val` (attr-writer call) — Ruby semantics: the
2248+ # assignment expression evaluates to the rhs value, so the
2249+ # inferred type is the rhs argument's type. Without this, a
2250+ # chain like `@a = obj.attr = val` mistypes the outer `@a`
2251+ # as int because the inner call falls through to the int
2252+ # default.
2253+ if mname.length > 1 && mname[mname.length - 1] == "=" &&
2254+ mname != "==" && mname != "!=" && mname != "<=" && mname != ">="
2255+ if recv >= 0
2256+ rt_w = infer_type(recv)
2257+ if is_obj_type(rt_w) == 1
2258+ bname_w = mname[0, mname.length - 1]
2259+ bt_w = base_type(rt_w)
2260+ cname_w = bt_w[4, bt_w.length - 4]
2261+ ci_w = find_class_idx(cname_w)
2262+ if ci_w >= 0 && cls_has_attr_writer(ci_w, bname_w) == 1
2263+ args_id_w = @nd_arguments[nid]
2264+ if args_id_w >= 0
2265+ arg_ids_w = get_args(args_id_w)
2266+ if arg_ids_w.length > 0
2267+ return infer_type(arg_ids_w[0])
2268+ end
2269+ end
2270+ end
2271+ end
2272+ end
2273+ end
2274+
22472275 # User-defined top-level method (bare call): take precedence over
22482276 # name-based builtin inference so `def minmax(a,b); ... end; minmax(1,2)`
22492277 # binds to the user def instead of Array#minmax's tuple return.