Commit 6322a5e3

6322a5e35310Merged

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

Description

fix(codegen): widen ivar slot when sibling writers disagree

Issue #247: a class with two methods writing the same ivar to different concrete types used to narrow the slot to whichever writer's update_ivar_type call ran last — and the loser then emitted slot = wrong_type_value against a struct field of the winning type, miscompiling the assignment.

The canonical shape (typed-hash[key] read in initialize, def-style attr writer in another method) hits this:

class C
  def initialize(h); @id = h[:id]; end       # writer 1: int
  def write_any(v);  @id = v;       end       # writer 2: string
end

Pre-fix: iv_id is const char *; sp_C_initialize emits self->iv_id = sp_SymIntHash_get(...) (mrb_int into const-char-* slot) — gcc warns -Wint-conversion, the runtime stores a pointer-shaped int and reads garbage.

The hard part is recognizing that writer 1's "int" is a real concrete int (SymIntHash#[] always returns mrb_int) rather than infer_type's catch-all fallback. The existing cls_ivar_definite_flag gate (#264) was literal-only and didn't fire for CallNode rhs.

Fix: per-(class, ivar) accumulate every writer's distinct concrete- type observation into a parallel array, recording inside scan_writer_calls where the local-scope context (params declared at iteratively-widened ptypes) lets infer_type resolve correctly. After all writer-scan iterations finish, finalize_ivar_heterogeneity walks the accumulator: if a slot saw 2+ distinct concrete types, widen it to poly. "Concrete" means infer_type returned a non-int / non-nil type, OR the rhs is a definite-literal AST or a typed-hash [key] read whose return type is statically pinned (is_definite_ivar _init extended to recognize these).

Fixes #247

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
6322a5e35310
Parent
a0864f361051

spinel_codegen.rbmodifiedView file

@@ -134,6 +134,18 @@
134134 # "best-guess inference"; only when both old and new writes are
135135 # definite-literal do we widen to poly on disagreement.
136136 @cls_ivar_init_definite = "".split(",")
137+ # Issue #247: per-(class, ivar) accumulator of distinct concrete
138+ # writer types observed by scan_writer_calls. After all writer-scan
139+ # iterations finish, if the list contains 2+ distinct entries the
140+ # slot is widened to poly. Observations are recorded with the scope
141+ # active inside scan_writer_calls (params declared with their
142+ # iteratively-widened ptypes), so `value` in
143+ # `def write_any(value); @id = value` resolves to its caller-pinned
144+ # string type rather than the placeholder "int" it would default to
145+ # outside that scope. Each entry is a comma-separated list of
146+ # distinct types per ivar; the outer dimension is semicolon-
147+ # separated and parallel to `@cls_ivar_names[ci]`.
148+ @cls_ivar_observed_types = "".split(",")
137149 # Top-level (script-scope) ivars. Lowered to `static` file-scope
138150 # globals because `main()` / top-level `def` bodies have no `self`.
139151 @toplevel_ivar_names = "".split(",")
@@ -6060,6 +6072,17 @@
60606072 sk2 = sk2 + 1
60616073 end
60626074 @cls_ivar_init_definite.push(struct_definite)
6075+ # Initialize observed_types parallel to ivar_names: one empty
6076+ # comma-list per struct field, joined by semicolons.
6077+ obs_init = ""
6078+ sk3 = 0
6079+ while sk3 < struct_fields.length
6080+ if sk3 > 0
6081+ obs_init = obs_init + ";"
6082+ end
6083+ sk3 = sk3 + 1
6084+ end
6085+ @cls_ivar_observed_types.push(obs_init)
60636086 # Auto-generate initialize method for struct-derived classes
60646087 if struct_fields.length > 0
60656088 init_params = ""
@@ -6769,18 +6792,87 @@
67696792 @cls_ivar_names[ci] = @cls_ivar_names[ci] + ";" + iname
67706793 @cls_ivar_types[ci] = @cls_ivar_types[ci] + ";" + itype
67716794 @cls_ivar_init_definite[ci] = @cls_ivar_init_definite[ci] + ";" + definite.to_s
6795+ @cls_ivar_observed_types[ci] = @cls_ivar_observed_types[ci] + ";"
67726796 else
67736797 @cls_ivar_names[ci] = iname
67746798 @cls_ivar_types[ci] = itype
67756799 @cls_ivar_init_definite[ci] = definite.to_s
6800+ @cls_ivar_observed_types[ci] = ""
6801+ end
6802+ end
6803+
6804+ # Issue #247: record `at` as a distinct observation for the slot if
6805+ # it's a concrete (non-fallback) type. "Concrete" means either
6806+ # `at != "int"` and `at != "nil"` (those are infer_type's catch-all
6807+ # placeholders), or the rhs is a definite-literal AST. The dedup
6808+ # keeps the list short — a slot written with int from twenty
6809+ # different `obj.length` call sites still records "int" once.
6810+ def record_ivar_observation(ci, iname, at, expr_id)
6811+ is_concrete = 0
6812+ if at != "int" && at != "nil"
6813+ is_concrete = 1
6814+ elsif expr_id >= 0 && is_definite_ivar_init(expr_id) == 1
6815+ is_concrete = 1
6816+ end
6817+ if is_concrete == 0
6818+ return
6819+ end
6820+ names = @cls_ivar_names[ci].split(";")
6821+ # Pad obs to names.length: split(";", -1) preserves trailing "" but
6822+ # an entirely-empty storage gives a 0-length array. Walk by index
6823+ # and treat missing entries as "".
6824+ obs_str = @cls_ivar_observed_types[ci]
6825+ k = 0
6826+ while k < names.length
6827+ if names[k] == iname
6828+ # Build an array of slots, one per ivar, defaulting empty.
6829+ slots = "".split(",")
6830+ ix = 0
6831+ while ix < names.length
6832+ slots.push("")
6833+ ix = ix + 1
6834+ end
6835+ if obs_str != ""
6836+ parts = obs_str.split(";", -1)
6837+ px = 0
6838+ while px < parts.length && px < slots.length
6839+ slots[px] = parts[px]
6840+ px = px + 1
6841+ end
6842+ end
6843+ existing = slots[k].split(",")
6844+ ex = 0
6845+ while ex < existing.length
6846+ if existing[ex] == at
6847+ return
6848+ end
6849+ ex = ex + 1
6850+ end
6851+ if slots[k] == ""
6852+ slots[k] = at
6853+ else
6854+ slots[k] = slots[k] + "," + at
6855+ end
6856+ @cls_ivar_observed_types[ci] = slots.join(";")
6857+ return
6858+ end
6859+ k = k + 1
67766860 end
67776861 end
67786862
67796863 # Issue #130: was the AST expression a definite-literal that
67806864 # `infer_ivar_init_type` types unambiguously? Used by scan_ivars to
6781- # decide when to widen a multi-write ivar slot to poly. Only literal
6782- # AST kinds count; CallNodes and LocalVariableReadNodes don't, even
6783- # if the inference happens to return a known concrete type.
6865+ # decide when to widen a multi-write ivar slot to poly.
6866+ #
6867+ # Issue #247: also accepts typed-hash[key] reads — when the receiver
6868+ # is a hash whose value type is statically known
6869+ # (str_int_hash / sym_int_hash / *_str_hash / int_str_hash), the call
6870+ # always produces that value type. Letting the heterogeneity check
6871+ # in finalize_ivar_heterogeneity record this writer's "int" (or
6872+ # "string") as a *concrete* observation lets a sibling-method writer
6873+ # of a different concrete type trigger the poly widen, instead of
6874+ # silently narrowing the slot to whichever sibling won the type
6875+ # race.
67846876 def is_definite_ivar_init(nid)
67856877 if nid < 0
67866878 return 0
@@ -6792,6 +6884,15 @@
67926884 if t == "SymbolNode" || t == "TrueNode" || t == "FalseNode"
67936885 return 1
67946886 end
6887+ if t == "CallNode" && @nd_name[nid] == "[]"
6888+ recv = @nd_receiver[nid]
6889+ if recv >= 0
6890+ rt = infer_type(recv)
6891+ if rt == "str_int_hash" || rt == "sym_int_hash" || rt == "str_str_hash" || rt == "sym_str_hash" || rt == "int_str_hash"
6892+ return 1
6893+ end
6894+ end
6895+ end
67956896 # Issue #131: a ternary whose branches are themselves definite is
67966897 # definite. Lets the #130 multi-write widening rule still fire when
67976898 # a later concrete write disagrees with an IfNode-typed slot.
@@ -8013,6 +8114,7 @@
80138114 @cls_ivar_names.push("")
80148115 @cls_ivar_types.push("")
80158116 @cls_ivar_init_definite.push("")
8117+ @cls_ivar_observed_types.push("")
80168118 @cls_meth_names.push("")
80178119 @cls_meth_params.push("")
80188120 @cls_meth_ptypes.push("")
@@ -9925,8 +10027,41 @@
992510027 # Scan main-level code
992610028 scan_writer_calls(@root_id)
992710029 pop_scope
10030+ # Issue #247: now that every writer's concrete type observation is
10031+ # recorded into @cls_ivar_observed_types[ci] (deduped per slot),
10032+ # widen any slot with 2+ distinct concrete types to poly. The
10033+ # narrow-then-overwrite path in update_ivar_type can otherwise
10034+ # leave the slot pinned to whichever writer's update_ivar_type
10035+ # call ran last, causing the loser's emit site to type-mismatch.
10036+ finalize_ivar_heterogeneity
992810037 end
992910038
10039+ def finalize_ivar_heterogeneity
10040+ ci = 0
10041+ while ci < @cls_names.length
10042+ names = @cls_ivar_names[ci].split(";")
10043+ types = @cls_ivar_types[ci].split(";")
10044+ obs = @cls_ivar_observed_types[ci].split(";", -1)
10045+ changed = 0
10046+ ivk = 0
10047+ while ivk < names.length
10048+ if ivk < types.length && ivk < obs.length && types[ivk] != "poly"
10049+ distinct = obs[ivk].split(",")
10050+ if distinct.length >= 2
10051+ types[ivk] = "poly"
10052+ @needs_rb_value = 1
10053+ changed = 1
10054+ end
10055+ end
10056+ ivk = ivk + 1
10057+ end
10058+ if changed == 1
10059+ @cls_ivar_types[ci] = types.join(";")
10060+ end
10061+ ci = ci + 1
10062+ end
10063+ end
10064+
993010065 def scan_writer_calls(nid)
993110066 bname = ""
993210067 if nid < 0
@@ -9961,6 +10096,13 @@
996110096 # widen the promoted type to poly on the next iteration.
996210097 if is_empty_hash_literal(bottom) == 0 && is_empty_array_literal(bottom) == 0
996310098 at = infer_type(bottom)
10099+ # Issue #247: record this writer's concrete type observation
10100+ # while the local-scope context is set up (params declared at
10101+ # their iteratively-widened ptypes). After all writer-scans
10102+ # finish, finalize_ivar_heterogeneity reads the accumulated
10103+ # per-slot list and widens to poly when 2+ distinct concrete
10104+ # types appear.
10105+ record_ivar_observation(@current_class_idx, iname, at, bottom)
996410106 # Chain participants bypass the `int` guard so that
996510107 # `@string_slot = @int_slot = expr_returning_int` widens
996610108 # the head to poly instead of leaving it stuck at