Commit bf3b9ef2

bf3b9ef251c7Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

[]= in expression position for hash and array receivers

(h[k] = v) and (a[i] = v) now compile as ({ set; v; }) returning the assigned value, matching Ruby semantics.

Co-Authored-By: Claude Sonnet 4.6 [email protected]

Details

Commit
bf3b9ef251c7
Parent
d7aa7e53388d

src/codegen.cmodifiedView file

@@ -5221,6 +5221,43 @@
52215221 if (handled) return;
52225222 }
52235223
5224+ /* `[]=` in expression position: mutate and return the assigned value.
5225+ Ruby's `(h[k] = v)` and `(a[i] = v)` evaluate to v. */
5226+ if (!strcmp(name, "[]=") && argc == 2 && recv >= 0) {
5227+ TyKind vt = comp_ntype(c, argv[1]);
5228+ if (ty_is_hash(rt)) {
5229+ const char *hn = ty_hash_cname(rt);
5230+ if (hn) {
5231+ int tv = ++g_tmp;
5232+ buf_puts(b, "({ ");
5233+ emit_ctype(c, vt != TY_UNKNOWN ? vt : TY_POLY, b);
5234+ buf_printf(b, " _t%d = ", tv);
5235+ if ((rt == TY_SYM_POLY_HASH || rt == TY_STR_POLY_HASH) && vt != TY_POLY)
5236+ emit_boxed(c, argv[1], b);
5237+ else
5238+ emit_expr(c, argv[1], b);
5239+ buf_printf(b, "; if (sp_gc_is_frozen("); emit_expr(c, recv, b); buf_puts(b, ")) sp_raise_frozen_hash(); ");
5240+ buf_printf(b, "sp_%sHash_set(", hn); emit_expr(c, recv, b); buf_puts(b, ", ");
5241+ emit_expr(c, argv[0], b); buf_printf(b, ", _t%d); _t%d; })", tv, tv);
5242+ return;
5243+ }
5244+ }
5245+ if (ty_is_array(rt) || rt == TY_POLY_ARRAY) {
5246+ const char *k = rt == TY_POLY_ARRAY ? "Poly" : array_kind(rt);
5247+ if (k) {
5248+ int tv = ++g_tmp;
5249+ buf_puts(b, "({ ");
5250+ emit_ctype(c, vt != TY_UNKNOWN ? vt : TY_POLY, b);
5251+ buf_printf(b, " _t%d = ", tv);
5252+ if (rt == TY_POLY_ARRAY && vt != TY_POLY) emit_boxed(c, argv[1], b);
5253+ else emit_expr(c, argv[1], b);
5254+ buf_printf(b, "; sp_%sArray_set(", k); emit_expr(c, recv, b); buf_puts(b, ", ");
5255+ emit_expr(c, argv[0], b); buf_printf(b, ", _t%d); _t%d; })", tv, tv);
5256+ return;
5257+ }
5258+ }
5259+ }
5260+
52245261 /* Last-resort fallbacks for inspect/to_s on unresolved receivers.
52255262 The test array_unresolved_inspect_no_segv expects "[]" when an
52265263 unsupported method chains into inspect. Emit a safe nil-degrade