Commit 5e2b5b7c

5e2b5b7cea34Merged

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

Description

fix(analyze): uninitialized ivar reads register a nil slot (#712)

class C; def x; @x; end; end used to fail C compilation with "struct sp_C has no member named iv_x". scan_ivars only added slots for writes; a read-only ivar never got a struct field, so the generated self->iv_x had nothing to land on.

Fix: scan_ivars now registers a "nil" slot for any InstanceVariableReadNode whose name has no own-class or ancestor slot yet. The slot's 0/nil default surfaces as nil through .inspect / .nil? and through the regular int/poly widening when a later write supplies a concrete type.

Test: test/uninit_ivar_returns_nil.rb covers both the read-only case (C.new.x -> nil) and the read-before-write case (D.new.get -> nil, then set; get -> "x").

457 tests pass; optcarrot checksum 59662.

Closes #712

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

Details

Commit
5e2b5b7cea34
Parent
17cffcb5507b

spinel_analyze.rbmodifiedView file

@@ -9706,6 +9706,18 @@
97069706 ti = ti + 1
97079707 end
97089708 end
9709+ # Read-only ivars: `def x; @x; end` with no write anywhere
9710+ # should not fail with "struct has no field iv_x". Register the
9711+ # slot as "nil" so codegen emits self->iv_x (defaulting to 0/nil)
9712+ # and Ruby semantics surface (`puts c.x.inspect` -> "nil"). A
9713+ # later write in another method widens the slot via the usual
9714+ # update_ivar_type path. Issue #712.
9715+ if @nd_type[nid] == "InstanceVariableReadNode"
9716+ iname_r = @nd_name[nid]
9717+ if ivar_exists(ci, iname_r) == 0 && ivar_exists_in_ancestor(ci, iname_r) == 0
9718+ add_ivar(ci, iname_r, "nil", 0)
9719+ end
9720+ end
97099721 # Recurse into children
97109722 scan_ivars_children(ci, nid)
97119723 end