Commit 219767d2

219767d27954Merged

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

Description

codegen: handle CallOrWriteNode / CallAndWriteNode (obj.attr ||= / &&=)

Emit a single receiver evaluation into a temp, then conditionally assign through the ivar, matching Ruby semantics for ||= / &&=.

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

Details

Commit
219767d27954
Parent
8916bb9cdbaa

src/codegen.cmodifiedView file

@@ -9099,6 +9099,38 @@
90999099 }
91009100 return;
91019101 }
9102+ if (!strcmp(ty, "CallOrWriteNode") || !strcmp(ty, "CallAndWriteNode")) {
9103+ int is_or = !strcmp(ty, "CallOrWriteNode");
9104+ int recv = nt_ref(nt, id, "receiver");
9105+ const char *attr = nt_str(nt, id, "name"); /* attr/reader name */
9106+ int v = nt_ref(nt, id, "value");
9107+ if (recv < 0 || !attr) { unsupported(c, id, is_or ? "call-or-write" : "call-and-write"); return; }
9108+ TyKind rt = comp_ntype(c, recv);
9109+ if (!ty_is_object(rt)) { unsupported(c, id, is_or ? "call-or-write (non-object)" : "call-and-write (non-object)"); return; }
9110+ int class_id = ty_object_class(rt);
9111+ char ivn[300]; snprintf(ivn, sizeof ivn, "@%s", attr);
9112+ int iidx = comp_ivar_index(&c->classes[class_id], ivn);
9113+ TyKind ivt = iidx >= 0 ? c->classes[class_id].ivar_types[iidx] : TY_UNKNOWN;
9114+ int tr = ++g_tmp;
9115+ emit_indent(b, indent);
9116+ buf_puts(b, "{ ");
9117+ emit_ctype(c, rt, b); buf_printf(b, " _t%d = ", tr); emit_expr(c, recv, b); buf_puts(b, "; ");
9118+ if (ivt == TY_POLY) {
9119+ buf_printf(b, "if (%ssp_poly_truthy(((sp_%s *)_t%d.v.p)->iv_%s)) ((sp_%s *)_t%d.v.p)->iv_%s = ",
9120+ is_or ? "!" : "", c->classes[class_id].name, tr, attr,
9121+ c->classes[class_id].name, tr, attr);
9122+ emit_boxed(c, v, b); buf_puts(b, "; }\n");
9123+ }
9124+ else if (ivt == TY_BOOL) {
9125+ buf_printf(b, "if (%s_t%d->iv_%s) _t%d->iv_%s = ", is_or ? "!" : "", tr, attr, tr, attr);
9126+ emit_expr(c, v, b); buf_puts(b, "; }\n");
9127+ }
9128+ else if (!is_or) { /* &&= on always-truthy type: always assign */
9129+ buf_printf(b, "_t%d->iv_%s = ", tr, attr); emit_expr(c, v, b); buf_puts(b, "; }\n");
9130+ }
9131+ else { buf_puts(b, "}\n"); } /* ||= on always-truthy type: no-op, but receiver evaluated */
9132+ return;
9133+ }
91029134 if (!strcmp(ty, "InstanceVariableWriteNode")) {
91039135 const char *nm = nt_str(nt, id, "name");
91049136 int v = nt_ref(nt, id, "value");