Commit 4575503e

4575503ed2c4Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

feat(analyze): confidence-based RBS arbitration for ivars (#626 sub-issue 2 phase 1)

--rbs was advisory: spinel pre-filled the inferred-type tables from the RBS seeds before running inference, so the iterative passes could (and did) widen RBS-pinned slots back off the declared type. Cross-class poly-recv attr_writer fan-out (#579 / #626 sub-issue 1) is the canonical case -- a sibling class's obj.attr = some_value site widened Mat#@nrows to sp_RbVal even when RBS declared it Integer.

Add a confidence-tier arbitration pass that runs after every inference pass has converged:

  • Track a shadow @cls_ivar_rbs_types table populated by apply_rbs_seeds, mirroring the layout of @cls_ivar_names. Un-pinned slots stay empty; pinned slots carry the declared type.
  • arbitrate_rbs_vs_inferred_ivars walks the shadow and, for each RBS-pinned slot, looks at the slot's observation set in @cls_ivar_observed_types:
    • If cls_ivar_init_definite == 1 AND any observed type is incompatible with the RBS declaration (different base, not a nullable refinement, not a same-kind hash variant), emit a hard error -- the user wrote both a concrete literal and a contradicting RBS line, and only they can resolve it.
    • Otherwise (observations came from cross-class fan-out, body-driven widening, or the slot is just the int placeholder), silently restore the RBS-declared type as the slot's final inferred type.

Inference still gets to run with the RBS seed as a starting point (it's used to narrow downstream method calls and call-site unification), but the arbitration is the last word on the slot type. RBS becomes the high-confidence override exactly where spinel's inference is least sure, while staying out of the way when the source is clear and unambiguous.

Verified manually: a Mat declared attr_accessor nrows: Integer in RBS keeps mrb_int iv_nrows even when a sibling class's poly-recv obj.nrows = "string" would otherwise fan out the widening. A Box declared attr_accessor value: String in RBS with @value = 42 (literal int) in source errors with "RBS conflict on Box@value".

Method-level arbitration (param / return) lands in a followup commit.

Refs #626 (sub-issue 2).

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

Details

Commit
4575503ed2c4
Parent
1ed5df4a6fcc

spinel_analyze.rbmodifiedView file

@@ -167,6 +167,14 @@
167167 # dimension is semicolon-separated and parallel to
168168 # `@cls_ivar_names[ci]`.
169169 @cls_ivar_observed_types = "".split(",")
170+ # Per-class shadow of `@cls_ivar_types`, populated only by
171+ # `apply_rbs_seeds`. Each entry mirrors `@cls_ivar_names[ci]`'s
172+ # `;`-separated layout: an RBS-pinned slot carries its declared
173+ # type; an un-pinned slot carries the empty string. Consumed by
174+ # `arbitrate_rbs_vs_inferred_ivars` after the iterative inference
175+ # loop -- when inference and RBS disagree, this table is what
176+ # we restore the slot to. Issue #626 sub-issue 2.
177+ @cls_ivar_rbs_types = "".split(",")
170178 # Per-class set of ivar names that are read with a nil predicate
171179 # somewhere in the program — `<ivar>.nil?`, `<ivar> == nil`,
172180 # `<ivar> != nil`. Gates nil-scalar widening to poly so an ivar
@@ -7647,6 +7655,18 @@
76477655 end
76487656 @cls_ivar_observed_types.push(obs_init)
76497657 @cls_ivar_nil_checked.push("")
7658+ # RBS shadow: one empty slot per struct field, joined by ";". No
7659+ # seed yet -- apply_rbs_seeds fills entries when an RBS line
7660+ # matches a real field name.
7661+ rbs_init = ""
7662+ sk4 = 0
7663+ while sk4 < struct_fields.length
7664+ if sk4 > 0
7665+ rbs_init = rbs_init + ";"
7666+ end
7667+ sk4 = sk4 + 1
7668+ end
7669+ @cls_ivar_rbs_types.push(rbs_init)
76507670 # Auto-generate initialize method for struct-derived classes
76517671 if struct_fields.length > 0
76527672 init_params = ""
@@ -8725,12 +8745,18 @@
87258745 @cls_ivar_types_version = @cls_ivar_types_version + 1
87268746 @cls_ivar_init_definite[ci] = @cls_ivar_init_definite[ci] + ";" + definite.to_s
87278747 @cls_ivar_observed_types[ci] = @cls_ivar_observed_types[ci] + ";"
8748+ if ci < @cls_ivar_rbs_types.length
8749+ @cls_ivar_rbs_types[ci] = @cls_ivar_rbs_types[ci] + ";"
8750+ end
87288751 else
87298752 @cls_ivar_names[ci] = iname
87308753 @cls_ivar_types[ci] = itype
87318754 @cls_ivar_types_version = @cls_ivar_types_version + 1
87328755 @cls_ivar_init_definite[ci] = definite.to_s
87338756 @cls_ivar_observed_types[ci] = ""
8757+ if ci < @cls_ivar_rbs_types.length
8758+ @cls_ivar_rbs_types[ci] = ""
8759+ end
87348760 end
87358761 end
87368762
@@ -10819,6 +10845,7 @@
1081910845 @cls_ivar_init_definite.push("1;1")
1082010846 @cls_ivar_observed_types.push("obj_Method;int")
1082110847 @cls_ivar_nil_checked.push("")
10848+ @cls_ivar_rbs_types.push(";")
1082210849 @cls_meth_names.push("initialize")
1082310850 @cls_meth_params.push("self_obj,fn_ptr")
1082410851 @cls_meth_ptypes.push("obj_Method,int")
@@ -10852,6 +10879,7 @@
1085210879 @cls_ivar_init_definite.push("")
1085310880 @cls_ivar_observed_types.push("")
1085410881 @cls_ivar_nil_checked.push("")
10882+ @cls_ivar_rbs_types.push("")
1085510883 @cls_meth_names.push("")
1085610884 @cls_meth_params.push("")
1085710885 @cls_meth_ptypes.push("")
@@ -20233,6 +20261,120 @@
2023320261 # Seed one method's param types and/or return type. `-` in either
2023420262 # slot means "leave alone" (don't override what collect_all
2023520263 # produced from `def` arity). Missing method = silent skip.
20264+ # #626 sub-issue 2: confidence-based RBS arbitration. After all
20265+ # inference passes converge, walk the RBS shadow tables and
20266+ # compare to the inferred types. When they disagree:
20267+ #
20268+ # * Inference's slot type came from a literal write in
20269+ # `initialize` (`@x = 42`, `cls_ivar_init_definite == 1`)
20270+ # AND the RBS-declared type is incompatible → hard error.
20271+ # The user wrote both a concrete literal and a contradicting
20272+ # RBS declaration; only they can resolve the disagreement.
20273+ # * Otherwise inference's source was a call-site observation,
20274+ # a body-driven widening, a cross-class poly-recv fan-out,
20275+ # or just the int placeholder → silently restore the RBS
20276+ # type. RBS is the more reliable signal in those cases.
20277+ #
20278+ # Runs after the iterative loop / post-passes so the inferred
20279+ # type is the converged final form rather than an intermediate
20280+ # state.
20281+ def arbitrate_rbs_vs_inferred_ivars
20282+ ci = 0
20283+ while ci < @cls_ivar_rbs_types.length
20284+ rbs_row = @cls_ivar_rbs_types[ci]
20285+ if rbs_row == ""
20286+ ci = ci + 1
20287+ next
20288+ end
20289+ rbs_parts = rbs_row.split(";", -1)
20290+ has_pin = 0
20291+ pk = 0
20292+ while pk < rbs_parts.length
20293+ if rbs_parts[pk] != ""
20294+ has_pin = 1
20295+ pk = rbs_parts.length
20296+ else
20297+ pk = pk + 1
20298+ end
20299+ end
20300+ if has_pin == 0
20301+ ci = ci + 1
20302+ next
20303+ end
20304+ names = @cls_ivar_names[ci].split(";")
20305+ types = @cls_ivar_types[ci].split(";")
20306+ defs = @cls_ivar_init_definite[ci].split(";")
20307+ # observed_types are the actual concrete types the inference
20308+ # passes saw written into this slot, accumulated separately from
20309+ # the running @cls_ivar_types (which apply_rbs_seeds may already
20310+ # have rewritten to the RBS-declared type). When the user's
20311+ # source had a definite literal write whose type contradicts
20312+ # the RBS declaration, the observation lives here even after
20313+ # the pre-fill -- that's the high-confidence conflict we want
20314+ # to report.
20315+ obs_row = @cls_ivar_observed_types[ci].split(";", -1)
20316+ changed = 0
20317+ k = 0
20318+ while k < names.length
20319+ if k < rbs_parts.length && rbs_parts[k] != "" && k < types.length
20320+ rbs_t = rbs_parts[k]
20321+ cur_t = types[k]
20322+ definite = 0
20323+ if k < defs.length && defs[k] == "1"
20324+ definite = 1
20325+ end
20326+ if definite == 1 && k < obs_row.length && obs_row[k] != ""
20327+ obs_list = obs_row[k].split(",")
20328+ oi = 0
20329+ while oi < obs_list.length
20330+ ot = obs_list[oi]
20331+ if ot != "" && rbs_inferred_incompatible?(rbs_t, ot)
20332+ $stderr.puts "Spinel: RBS conflict on " + @cls_names[ci] + names[k] + ": declared \"" + rbs_t + "\" but a literal write inferred \"" + ot + "\""
20333+ exit(1)
20334+ end
20335+ oi = oi + 1
20336+ end
20337+ end
20338+ # No definite conflict: silently restore RBS as the slot type.
20339+ if rbs_t != cur_t
20340+ types[k] = rbs_t
20341+ changed = 1
20342+ end
20343+ end
20344+ k = k + 1
20345+ end
20346+ if changed == 1
20347+ @cls_ivar_types[ci] = types.join(";")
20348+ @cls_ivar_types_version = @cls_ivar_types_version + 1
20349+ end
20350+ ci = ci + 1
20351+ end
20352+ end
20353+
20354+ # Two types are "incompatible" for the RBS arbitration if they're
20355+ # not the same base AND not a nullable refinement of each other.
20356+ # Strict equality would over-trigger errors on benign refinements
20357+ # (`string` vs `string?`, `int_array` vs `poly_array`); the
20358+ # compatibility test below mirrors the relaxations that
20359+ # `update_ivar_type` / `unify_call_types` already make.
20360+ def rbs_inferred_incompatible?(rbs_t, inf_t)
20361+ if rbs_t == inf_t
20362+ return false
20363+ end
20364+ if base_type(rbs_t) == base_type(inf_t)
20365+ return false
20366+ end
20367+ # Container variant refinements where one is the other's poly form.
20368+ if (rbs_t == "int_array" && inf_t == "poly_array") ||
20369+ (rbs_t == "poly_array" && inf_t == "int_array")
20370+ return false
20371+ end
20372+ if is_hash_type(rbs_t) == 1 && is_hash_type(inf_t) == 1
20373+ return false
20374+ end
20375+ true
20376+ end
20377+
2023620378 def seed_class_method(ci, mname, ret, ptypes_token)
2023720379 midx = cls_find_method_direct(ci, mname)
2023820380 if midx < 0
@@ -20347,6 +20489,25 @@
2034720489 else
2034820490 add_ivar(ci, iname, itype, 1)
2034920491 end
20492+ # Record the RBS-declared type in the shadow so
20493+ # arbitrate_rbs_vs_inferred_ivars can restore it after the
20494+ # iterative inference loop, in case some pass widens the slot
20495+ # off the RBS pin. Issue #626 sub-issue 2.
20496+ rbs_names = @cls_ivar_names[ci].split(";")
20497+ rbs_types = @cls_ivar_rbs_types[ci].split(";", -1)
20498+ while rbs_types.length < rbs_names.length
20499+ rbs_types.push("")
20500+ end
20501+ rj = 0
20502+ while rj < rbs_names.length
20503+ if rbs_names[rj] == iname
20504+ rbs_types[rj] = itype
20505+ rj = rbs_names.length
20506+ else
20507+ rj = rj + 1
20508+ end
20509+ end
20510+ @cls_ivar_rbs_types[ci] = rbs_types.join(";")
2035020511 end
2035120512
2035220513 # End-to-end whole-program analysis. Splits cleanly out of `compile`
@@ -20545,6 +20706,14 @@
2054520706 widen_returns_for_mixed_paths
2054620707 # Fix lambda return types based on call-site usage
2054720708 fix_lambda_return_types
20709+ # #626 sub-issue 2: confidence-based RBS arbitration. Inference
20710+ # may have widened ivar slots off the RBS-pinned types (cross-
20711+ # class poly-recv attr_writer fan-out, body-driven widening,
20712+ # etc.); restore them now unless a definite literal write in
20713+ # initialize actually contradicts the RBS declaration -- only
20714+ # the user can resolve that disagreement. Runs after every type-
20715+ # inference pass so the slot we're comparing against is final.
20716+ arbitrate_rbs_vs_inferred_ivars
2054820717 # Pre-detect bigint variables before feature detection
2054920718 pre_detect_bigint
2055020719 detect_features