Commit 6edcb409

6edcb4097963Merged

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

Description

Keep the lazy-init when @ivar ||= expr feeds a poly-receiver setter

The expression-context handler for @ivar ||= expr / @ivar &&= expr (InstanceVariable{Or,And}WriteNode) only emitted the write-back guard for poly/bool/int/string ivar types. For a pointer-backed ivar (object/array/hash/fiber/proc/io/...) the ||= case fell through to a bare read of the ivar, dropping the if (!@x) @x = expr init entirely.

That bare-read path is normally unreachable because an or-write in statement position is lowered by codegen_stmt.c (which does handle the object types). But when the or-write is used as a value -- e.g. the RHS of recv.attr = @ivar ||= expr where recv is polymorphic, so the setter is dispatched through a switch (cls_id) and the RHS is pre-evaluated into a temp via emit_expr -- the expression handler runs and silently emitted just self->iv_x. The ivar stayed nil and the setter was handed nil.

Mirror codegen_stmt.c's pointer-backed branch here, emitting ({ if (!@x) @x = expr; @x; }) (and the if (@x) form for &&=), so the init and write-back survive in value position.

Fixes #1447

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
6edcb4097963
Parent
48f5ee665084

src/codegen_expr.cmodifiedView file

@@ -473,6 +473,18 @@
473473 buf_printf(b, "; %s; })", ref3);
474474 }
475475 }
476+ /* a pointer-backed ivar (object/array/hash/fiber/proc/...) reads falsy
477+ when NULL, so `@x ||= v` is `if (!@x) @x = v` and `@x &&= v` is
478+ `if (@x) @x = v`. Falling through to a bare read dropped the init when
479+ this or-write was the RHS of a poly-receiver setter switch (#1447). */
480+ else if (ty_is_object(ivt3) || ty_is_array(ivt3) || ty_is_hash(ivt3) ||
481+ ivt3 == TY_FIBER || ivt3 == TY_PROC || ivt3 == TY_IO ||
482+ ivt3 == TY_STRINGIO || ivt3 == TY_STRINGSCANNER ||
483+ ivt3 == TY_MATCHDATA || ivt3 == TY_EXCEPTION || ivt3 == TY_REGEX) {
484+ buf_printf(b, "({ if (%s%s) %s = ", is_or ? "!" : "", ref3, ref3);
485+ emit_expr(c, v, b);
486+ buf_printf(b, "; %s; })", ref3);
487+ }
476488 else if (!is_or) {
477489 buf_printf(b, "({ %s = ", ref3);
478490 emit_expr(c, v, b);