Commit 1675c0e8

1675c0e824faMerged

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

Description

fix(analyze,codegen): uninit attr_accessor ivars read as nil (#634 shape B)

class A; attr_accessor :counter; end; A.new.counter returns nil under MRI but spinel returned 0 (the int placeholder's zero).

Add widen_uninit_attr_ivars_to_poly, a post-iteration analyze pass that widens an attr_reader/accessor ivar slot to poly when all three of:

  • no method body in the class (or any ancestor) writes the ivar,
  • no super call in the class's initialize forwards to a parent that might assign it,
  • no writer call site has been observed against the slot (i.e. cls_ivar_observed_types entry is empty).

The third condition is what keeps optcarrot's @amp (assigned by reset, also written via obj.amp = ... at call sites) at its typed slot and the class_const_as_value Holder#@klass at its "class" slot. Without it, my earlier attempt over-widened classes whose synthetic attr_writer body is bid=-2 (invisible to syntactic scans) but whose call sites had pinned a concrete type.

Codegen side: extend the auto-unbox-poly-key block in compile_bracket_assign so a result[k] = v write into a sym_poly_hash / str_poly_hash / sym_int_hash / sym_str_hash / int_str_hash recv with a poly-typed key extracts the matching union field. This was a sibling-of-#631 gap that surfaced when shape B started actually propagating poly through .each blocks.

Update param_body_array_hash_inference to seed the body-widen passes from concrete literals rather than b.contents on a bare attr_accessor. The old setup relied on the int-placeholder -> NULL-cast quirk that contradicts MRI (nil.push raises NoMethodError); per spinel's "documented quirks are subset violations" policy, MRI's shape wins.

Fixes #634.

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

Details

Commit
1675c0e824fa
Parent
7e0197f6ee21

spinel_analyze.rbmodifiedView file

@@ -14091,6 +14091,184 @@
1409114091
1409214092 # Post-pass for #634 shape A. An optional param with an explicit
1409314093 # `= nil` default whose call sites then widen its type to a
14094+ # Post-pass for #634 shape B. An ivar exposed by attr_reader /
14095+ # attr_accessor and never explicitly assigned in initialize is
14096+ # observable in its zero-state by every caller; MRI returns nil
14097+ # for the unset read, but spinel would otherwise lower the slot
14098+ # to a non-nullable scalar (whose zero is `0`, not nil). Widen
14099+ # to poly so the uninitialized read renders as nil. Skipped when
14100+ # the ivar is assigned somewhere inside `initialize` (the user
14101+ # explicitly owns the init state) and when the post-iteration
14102+ # type isn't a non-nullable scalar (a real writer pinned it to
14103+ # a concrete pointer / class type, which the reader can return
14104+ # at full type fidelity without nil-vs-zero ambiguity).
14105+ def widen_uninit_attr_ivars_to_poly
14106+ ci = 0
14107+ while ci < @cls_names.length
14108+ readers = @cls_attr_readers[ci].split(";")
14109+ writers = @cls_attr_writers[ci].split(";")
14110+ attr_iname_set = "".split(",")
14111+ k = 0
14112+ while k < readers.length
14113+ if readers[k] != "" && not_in("@" + readers[k], attr_iname_set) == 1
14114+ attr_iname_set.push("@" + readers[k])
14115+ end
14116+ k = k + 1
14117+ end
14118+ k = 0
14119+ while k < writers.length
14120+ if writers[k] != "" && not_in("@" + writers[k], attr_iname_set) == 1
14121+ attr_iname_set.push("@" + writers[k])
14122+ end
14123+ k = k + 1
14124+ end
14125+ if attr_iname_set.length == 0
14126+ ci = ci + 1
14127+ next
14128+ end
14129+ names = @cls_ivar_names[ci].split(";")
14130+ types = @cls_ivar_types[ci].split(";")
14131+ changed_c = 0
14132+ k = 0
14133+ while k < names.length
14134+ if k < types.length
14135+ iname = names[k]
14136+ pt = types[k]
14137+ if not_in(iname, attr_iname_set) == 0 && (pt == "int" || pt == "symbol" || pt == "float" || pt == "bool")
14138+ # Three signals that the user has actually written into this
14139+ # slot (and so spinel's typed default isn't observably wrong):
14140+ # 1. The ivar is assigned in some method body (initialize or
14141+ # otherwise) -- syntactic write.
14142+ # 2. scan_writer_calls observed at least one writer call site
14143+ # against this slot, even via `obj.attr = value` from a
14144+ # sibling scope. The synthetic attr_writer body itself is
14145+ # bid=-2 so it's invisible to (1).
14146+ # 3. Same checks against ancestor classes' initializes
14147+ # (super-call forwarding).
14148+ assigned = ivar_assigned_in_init_chain?(ci, iname)
14149+ obs = cls_ivar_observed_types_for(ci, iname)
14150+ if assigned == 0 && obs == ""
14151+ types[k] = "poly"
14152+ @needs_rb_value = 1
14153+ changed_c = 1
14154+ end
14155+ end
14156+ end
14157+ k = k + 1
14158+ end
14159+ if changed_c == 1
14160+ @cls_ivar_types[ci] = types.join(";")
14161+ @cls_ivar_types_version = @cls_ivar_types_version + 1
14162+ end
14163+ ci = ci + 1
14164+ end
14165+ end
14166+
14167+ # Returns 1 if the ivar is assigned anywhere in the class or any
14168+ # ancestor class (in any method body, not just `initialize`). The
14169+ # user-visible nil-vs-zero distinction only matters for ivars that
14170+ # NO method ever writes -- attr_accessor with no `@x = ...` ever
14171+ # leaves the slot at its scalar default, which MRI sees as nil
14172+ # but spinel was lowering to the type's zero. An ivar written by
14173+ # some sibling method (e.g. optcarrot's `@amp` assigned in `reset`
14174+ # but not in `initialize`) still gets the writer's typed slot —
14175+ # the read-before-write window exists in theory but doesn't
14176+ # surface in practice for those classes' actual lifecycles, and
14177+ # widening to poly would break the body's `@amp -= int` arithmetic.
14178+ def ivar_assigned_in_init_chain?(ci, iname)
14179+ cur = ci
14180+ visited = "".split(",")
14181+ while cur >= 0 && cur < @cls_names.length && not_in(@cls_names[cur], visited) == 1
14182+ visited.push(@cls_names[cur])
14183+ bodies_w = @cls_meth_bodies[cur].split(";")
14184+ bi = 0
14185+ while bi < bodies_w.length
14186+ bid_w = bodies_w[bi].to_i
14187+ if bid_w >= 0
14188+ if ivar_written_in?(bid_w, iname) == 1
14189+ return 1
14190+ end
14191+ end
14192+ bi = bi + 1
14193+ end
14194+ # `super` call anywhere in initialize delegates to the parent's
14195+ # initialize path — assume that may assign any ancestor ivar.
14196+ mnames_w = @cls_meth_names[cur].split(";")
14197+ bodies_w2 = @cls_meth_bodies[cur].split(";")
14198+ mi_init_w = 0
14199+ while mi_init_w < mnames_w.length
14200+ if mnames_w[mi_init_w] == "initialize" && mi_init_w < bodies_w2.length
14201+ init_bid_w = bodies_w2[mi_init_w].to_i
14202+ if init_bid_w >= 0 && super_called_in?(init_bid_w) == 1
14203+ return 1
14204+ end
14205+ mi_init_w = mnames_w.length
14206+ else
14207+ mi_init_w = mi_init_w + 1
14208+ end
14209+ end
14210+ if @cls_parents[cur] == ""
14211+ cur = -1
14212+ else
14213+ cur = find_class_idx(@cls_parents[cur])
14214+ end
14215+ end
14216+ 0
14217+ end
14218+
14219+ # Walk `nid` checking for an `InstanceVariableWriteNode` named
14220+ # `iname`. Returns 1 on first match.
14221+ def ivar_written_in?(nid, iname)
14222+ if nid < 0
14223+ return 0
14224+ end
14225+ if @nd_type[nid] == "InstanceVariableWriteNode" && @nd_name[nid] == iname
14226+ return 1
14227+ end
14228+ if @nd_type[nid] == "InstanceVariableOperatorWriteNode" && @nd_name[nid] == iname
14229+ return 1
14230+ end
14231+ if @nd_type[nid] == "InstanceVariableOrWriteNode" && @nd_name[nid] == iname
14232+ return 1
14233+ end
14234+ if @nd_type[nid] == "InstanceVariableAndWriteNode" && @nd_name[nid] == iname
14235+ return 1
14236+ end
14237+ cs = []
14238+ push_child_ids(nid, cs)
14239+ k = 0
14240+ while k < cs.length
14241+ if ivar_written_in?(cs[k], iname) == 1
14242+ return 1
14243+ end
14244+ k = k + 1
14245+ end
14246+ 0
14247+ end
14248+
14249+ # Walk `nid` looking for `super` / `ForwardingSuperNode`. Returns
14250+ # 1 on first match.
14251+ def super_called_in?(nid)
14252+ if nid < 0
14253+ return 0
14254+ end
14255+ if @nd_type[nid] == "SuperNode" || @nd_type[nid] == "ForwardingSuperNode"
14256+ return 1
14257+ end
14258+ cs = []
14259+ push_child_ids(nid, cs)
14260+ k = 0
14261+ while k < cs.length
14262+ if super_called_in?(cs[k]) == 1
14263+ return 1
14264+ end
14265+ k = k + 1
14266+ end
14267+ 0
14268+ end
14269+
14270+ # Post-pass for #634 shape A. An optional param with an explicit
14271+ # `= nil` default whose call sites then widen its type to a
1409414272 # non-nullable scalar (int / symbol / float / bool) loses the
1409514273 # nil-vs-zero distinction at the no-arg call site: the missing arg
1409614274 # defaults to the zero value of the scalar, not to nil, and any
@@ -20248,6 +20426,16 @@
2024820426 # e.g. @left = nil in Node with attr_accessor :left → obj_Node?
2024920427 # Must run after iterative loop to override poly from type conflicts
2025020428 fix_nil_ivar_self_refs
20429+ # Issue #634 shape B: attr_accessor / attr_reader ivar with no
20430+ # initialize-time assignment is observable in its unwritten state,
20431+ # which MRI sees as nil. Widen the slot to poly so the unset
20432+ # read renders as nil instead of the scalar zero. Must run after
20433+ # the iterative writer-call inference loop so the ivar's type
20434+ # reflects every writer's contribution (a `h.klass = SomeClass`
20435+ # site moves the slot off the int placeholder to "class"; the
20436+ # filter here keys on the post-iteration type to avoid widening
20437+ # genuinely-typed slots).
20438+ widen_uninit_attr_ivars_to_poly
2025120439 # Re-run returns with corrected ivar types
2025220440 infer_all_returns
2025320441 infer_function_body_call_types