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
buf_printf(b, "; %s; })", ref3); } } /* a pointer-backed ivar (object/array/hash/fiber/proc/...) reads falsy when NULL, so `@x ||= v` is `if (!@x) @x = v` and `@x &&= v` is `if (@x) @x = v`. Falling through to a bare read dropped the init when this or-write was the RHS of a poly-receiver setter switch (#1447). */ else if (ty_is_object(ivt3) || ty_is_array(ivt3) || ty_is_hash(ivt3) || ivt3 == TY_FIBER || ivt3 == TY_PROC || ivt3 == TY_IO || ivt3 == TY_STRINGIO || ivt3 == TY_STRINGSCANNER || ivt3 == TY_MATCHDATA || ivt3 == TY_EXCEPTION || ivt3 == TY_REGEX) { buf_printf(b, "({ if (%s%s) %s = ", is_or ? "!" : "", ref3, ref3); emit_expr(c, v, b); buf_printf(b, "; %s; })", ref3); } else if (!is_or) { buf_printf(b, "({ %s = ", ref3); emit_expr(c, v, b);test/or_write_ivar_poly_setter.rbaddedView file
Loading diff…
test/or_write_ivar_poly_setter.rb.expectedaddedView file
Loading diff…