Skip to main content

logicaffeine_compile/optimize/
abstract_interp.rs

1use std::collections::{HashMap, HashSet};
2
3use super::writes::{count_writes_of, rebound_names, CalleeGlobals, WriteSet};
4use crate::arena::Arena;
5use crate::ast::stmt::{BinaryOpKind, Expr, Literal, MatchArm, Pattern, Stmt};
6use crate::intern::Symbol;
7
8/// Per-collection ELEMENT-TYPE tracking: a read `item k of arr` carries `arr`'s
9/// proven element type (the join of every value written into it). A
10/// homogeneously-typed collection's reads gain a concrete scalar kind, which the
11/// magic-reciprocal modulo gate (`(... + ...) % c`) consumes to replace idiv.
12/// PROMOTED 2026-06-21: default ON (kill-switch LOGOS_ELEM_TYPE=0) — coins -11%
13/// on the faithful interleaved A/B, all 33 benchmarks bit-identical, no regression
14/// (a spurious histogram +2.4% on best-of-min was confirmed noise — identical raw
15/// distributions). With it off `eval_type` treats an index read as `Top` exactly
16/// as before, so the byte output is unchanged.
17fn elem_type_enabled() -> bool {
18    crate::optimize::active_config().is_on(crate::optimization::Opt::ElemType)
19}
20
21#[derive(Clone, Debug, PartialEq)]
22enum Bound {
23    NegInf,
24    Finite(i64),
25    PosInf,
26}
27
28impl Bound {
29    fn add(&self, other: &Bound) -> Bound {
30        match (self, other) {
31            (Bound::Finite(a), Bound::Finite(b)) => match a.checked_add(*b) {
32                Some(r) => Bound::Finite(r),
33                None => {
34                    if *a > 0 {
35                        Bound::PosInf
36                    } else {
37                        Bound::NegInf
38                    }
39                }
40            },
41            (Bound::PosInf, Bound::NegInf) | (Bound::NegInf, Bound::PosInf) => Bound::NegInf,
42            (Bound::PosInf, _) | (_, Bound::PosInf) => Bound::PosInf,
43            (Bound::NegInf, _) | (_, Bound::NegInf) => Bound::NegInf,
44        }
45    }
46
47    fn sub(&self, other: &Bound) -> Bound {
48        match (self, other) {
49            (Bound::Finite(a), Bound::Finite(b)) => match a.checked_sub(*b) {
50                Some(r) => Bound::Finite(r),
51                None => {
52                    if *a > 0 {
53                        Bound::PosInf
54                    } else {
55                        Bound::NegInf
56                    }
57                }
58            },
59            (Bound::PosInf, Bound::PosInf) | (Bound::NegInf, Bound::NegInf) => Bound::NegInf,
60            (Bound::PosInf, _) | (_, Bound::NegInf) => Bound::PosInf,
61            (Bound::NegInf, _) | (_, Bound::PosInf) => Bound::NegInf,
62        }
63    }
64
65    fn mul(&self, other: &Bound) -> Bound {
66        // An exact-zero endpoint annihilates: every product with it is 0
67        // (this keeps `0 * [c, +inf]` at 0 rather than collapsing to top).
68        if matches!(self, Bound::Finite(0)) || matches!(other, Bound::Finite(0)) {
69            return Bound::Finite(0);
70        }
71        if let (Bound::Finite(a), Bound::Finite(b)) = (self, other) {
72            return match a.checked_mul(*b) {
73                Some(r) => Bound::Finite(r),
74                None => {
75                    if (*a > 0) == (*b > 0) {
76                        Bound::PosInf
77                    } else {
78                        Bound::NegInf
79                    }
80                }
81            };
82        }
83        // At least one infinite, neither zero — the result's sign is the
84        // product of the operands' signs.
85        let positive = |x: &Bound| match x {
86            Bound::PosInf => true,
87            Bound::NegInf => false,
88            Bound::Finite(v) => *v > 0,
89        };
90        if positive(self) == positive(other) {
91            Bound::PosInf
92        } else {
93            Bound::NegInf
94        }
95    }
96
97    /// Truncating division by a nonzero constant `k` (toward zero, matching
98    /// Rust `i64` `/`). An infinite endpoint divided by a finite divisor stays
99    /// infinite, its sign flipping when `k < 0`.
100    fn div_by(&self, k: i64) -> Bound {
101        match self {
102            Bound::Finite(a) => Bound::Finite(a / k),
103            Bound::NegInf => {
104                if k > 0 {
105                    Bound::NegInf
106                } else {
107                    Bound::PosInf
108                }
109            }
110            Bound::PosInf => {
111                if k > 0 {
112                    Bound::PosInf
113                } else {
114                    Bound::NegInf
115                }
116            }
117        }
118    }
119
120    /// Arithmetic right shift by a constant `k ∈ [0, 63]` — floor-division by
121    /// `2^k`, MONOTONE non-decreasing, so an interval's endpoints map straight
122    /// through. Infinite endpoints stay infinite (their magnitude only shrinks).
123    fn shr_by(&self, k: u32) -> Bound {
124        match self {
125            Bound::Finite(a) => Bound::Finite(a >> k),
126            Bound::NegInf => Bound::NegInf,
127            Bound::PosInf => Bound::PosInf,
128        }
129    }
130
131    fn cmp_bound(&self, other: &Self) -> std::cmp::Ordering {
132        match (self, other) {
133            (Bound::NegInf, Bound::NegInf) => std::cmp::Ordering::Equal,
134            (Bound::NegInf, _) => std::cmp::Ordering::Less,
135            (_, Bound::NegInf) => std::cmp::Ordering::Greater,
136            (Bound::PosInf, Bound::PosInf) => std::cmp::Ordering::Equal,
137            (Bound::PosInf, _) => std::cmp::Ordering::Greater,
138            (_, Bound::PosInf) => std::cmp::Ordering::Less,
139            (Bound::Finite(a), Bound::Finite(b)) => a.cmp(b),
140        }
141    }
142
143    /// How `self` orders against `other` for every integer the two bounds stand for, when that is decided. An
144    /// infinite bound stands for integers past the word on its side — an endpoint that overflowed i64 is one — so
145    /// two of the same sign are not ordered by their bounds.
146    fn decided(&self, other: &Self) -> Option<std::cmp::Ordering> {
147        match (self, other) {
148            (Bound::PosInf, Bound::PosInf) | (Bound::NegInf, Bound::NegInf) => None,
149            _ => Some(self.cmp_bound(other)),
150        }
151    }
152
153    fn min_bound(a: &Bound, b: &Bound) -> Bound {
154        if a.cmp_bound(b) == std::cmp::Ordering::Less {
155            a.clone()
156        } else {
157            b.clone()
158        }
159    }
160
161    fn max_bound(a: &Bound, b: &Bound) -> Bound {
162        if a.cmp_bound(b) == std::cmp::Ordering::Greater {
163            a.clone()
164        } else {
165            b.clone()
166        }
167    }
168}
169
170/// A bounded lattice with the operations abstract interpretation needs.
171///
172/// Each abstract domain of the Oracle (intervals, types, collection shapes,
173/// nullability, aliasing) implements this. The product lattice combines them
174/// componentwise. `widen` accelerates ascending chains to a fixpoint so loop
175/// analysis terminates; `leq` is the lattice order `⊑` (more precise ⊑ less
176/// precise, i.e. `γ`-subset).
177trait AbstractDomain: Clone {
178    /// Greatest element `⊤` — "no information".
179    fn top() -> Self;
180    /// Least element `⊥` — "unreachable / empty".
181    fn bottom() -> Self;
182    /// Least upper bound `⊔` (merge at control-flow joins).
183    fn join(&self, other: &Self) -> Self;
184    /// Greatest lower bound `⊓` (refine under a known fact).
185    fn meet(&self, other: &Self) -> Self;
186    /// Widening `▽` — over-approximates the join to force loop convergence.
187    fn widen(&self, other: &Self) -> Self;
188    /// Lattice order: `self ⊑ other`.
189    fn leq(&self, other: &Self) -> bool;
190}
191
192#[derive(Clone, Debug)]
193struct Interval {
194    lo: Bound,
195    hi: Bound,
196}
197
198impl Interval {
199    fn exact(n: i64) -> Self {
200        Interval {
201            lo: Bound::Finite(n),
202            hi: Bound::Finite(n),
203        }
204    }
205
206    fn top() -> Self {
207        Interval {
208            lo: Bound::NegInf,
209            hi: Bound::PosInf,
210        }
211    }
212
213    fn non_negative() -> Self {
214        Interval {
215            lo: Bound::Finite(0),
216            hi: Bound::PosInf,
217        }
218    }
219
220    fn is_exact(&self) -> Option<i64> {
221        if let (Bound::Finite(a), Bound::Finite(b)) = (&self.lo, &self.hi) {
222            if a == b {
223                return Some(*a);
224            }
225        }
226        None
227    }
228
229    /// The empty interval `⊥`. Represented as `lo > hi`, which no reachable
230    /// program point ever constructs, so it is unambiguous.
231    fn bottom() -> Self {
232        Interval {
233            lo: Bound::PosInf,
234            hi: Bound::NegInf,
235        }
236    }
237
238    fn is_bottom(&self) -> bool {
239        self.lo.cmp_bound(&self.hi) == std::cmp::Ordering::Greater
240    }
241
242    fn join(&self, other: &Interval) -> Interval {
243        if self.is_bottom() {
244            return other.clone();
245        }
246        if other.is_bottom() {
247            return self.clone();
248        }
249        Interval {
250            lo: Bound::min_bound(&self.lo, &other.lo),
251            hi: Bound::max_bound(&self.hi, &other.hi),
252        }
253    }
254
255    /// Intersection `⊓`. Disjoint inputs collapse to `⊥`.
256    fn meet(&self, other: &Interval) -> Interval {
257        if self.is_bottom() || other.is_bottom() {
258            return Interval::bottom();
259        }
260        let r = Interval {
261            lo: Bound::max_bound(&self.lo, &other.lo),
262            hi: Bound::min_bound(&self.hi, &other.hi),
263        };
264        if r.is_bottom() {
265            Interval::bottom()
266        } else {
267            r
268        }
269    }
270
271    /// Widening `self ▽ other` (self = old, other = new). An unstable bound is
272    /// thrown to the corresponding infinity so ascending chains converge.
273    fn widen(&self, other: &Interval) -> Interval {
274        if self.is_bottom() {
275            return other.clone();
276        }
277        if other.is_bottom() {
278            return self.clone();
279        }
280        // EXODIA's threshold ladder: an unstable bound snaps to the next
281        // rung before falling off to ±∞ — loop counters converge to finite
282        // bounds (e.g. `While i < 10` keeps i ⊑ [entry, 10ish]) instead of
283        // instantly losing all precision. Still a finite ascent → terminates.
284        const WIDENING_THRESHOLDS: &[i64] = &[-1000, -100, -10, -1, 0, 1, 10, 100, 1000];
285        let lo = if other.lo.cmp_bound(&self.lo) == std::cmp::Ordering::Less {
286            match other.lo {
287                Bound::Finite(v) => WIDENING_THRESHOLDS
288                    .iter()
289                    .rev()
290                    .find(|&&t| t <= v)
291                    .map(|&t| Bound::Finite(t))
292                    .unwrap_or(Bound::NegInf),
293                _ => Bound::NegInf,
294            }
295        } else {
296            self.lo.clone()
297        };
298        let hi = if other.hi.cmp_bound(&self.hi) == std::cmp::Ordering::Greater {
299            match other.hi {
300                Bound::Finite(v) => WIDENING_THRESHOLDS
301                    .iter()
302                    .find(|&&t| t >= v)
303                    .map(|&t| Bound::Finite(t))
304                    .unwrap_or(Bound::PosInf),
305                _ => Bound::PosInf,
306            }
307        } else {
308            self.hi.clone()
309        };
310        Interval { lo, hi }
311    }
312
313    /// Narrowing `self △ other` (self = the widened post-fixpoint bound, other =
314    /// the body transfer recomputed from it). Only an INFINITE bound is replaced,
315    /// by the recomputed value; a finite bound is kept. Descending from a
316    /// post-fixpoint (`self ⊒ lfp`, so `other = F(self) ⊒ lfp`) every result stays
317    /// a sound over-approximation, and each step fills at least one ±∞ — so a
318    /// bounded run terminates. This is what recovers a modulo-clamped
319    /// accumulator's finite bound (`b = (a + b) % M` re-clamps `b` to `[0, M-1]`
320    /// even though the widener threw its upper to `+∞`): the license the raw-i64
321    /// arithmetic lowering needs to drop the overflow guard.
322    fn narrow(&self, other: &Interval) -> Interval {
323        if self.is_bottom() || other.is_bottom() {
324            return self.clone();
325        }
326        let lo = match self.lo {
327            Bound::NegInf => other.lo.clone(),
328            _ => self.lo.clone(),
329        };
330        let hi = match self.hi {
331            Bound::PosInf => other.hi.clone(),
332            _ => self.hi.clone(),
333        };
334        Interval { lo, hi }
335    }
336
337    /// Lattice order `self ⊑ other`, i.e. `self ⊆ other` as concrete sets.
338    fn leq(&self, other: &Interval) -> bool {
339        if self.is_bottom() {
340            return true;
341        }
342        if other.is_bottom() {
343            return false;
344        }
345        other.lo.cmp_bound(&self.lo) != std::cmp::Ordering::Greater
346            && self.hi.cmp_bound(&other.hi) != std::cmp::Ordering::Greater
347    }
348
349    fn add(&self, other: &Interval) -> Interval {
350        Interval {
351            lo: self.lo.add(&other.lo),
352            hi: self.hi.add(&other.hi),
353        }
354    }
355
356    fn sub(&self, other: &Interval) -> Interval {
357        Interval {
358            lo: self.lo.sub(&other.hi),
359            hi: self.hi.sub(&other.lo),
360        }
361    }
362
363    fn mul(&self, other: &Interval) -> Interval {
364        // Standard interval product: the extremes lie at the four corner
365        // products. With the `0 * inf = 0` convention in `Bound::mul`, this
366        // stays precise for sign-definite operands (e.g. `i * i` with `i >= 2`
367        // gives `[4, +inf)`, not top).
368        let corners = [
369            self.lo.mul(&other.lo),
370            self.lo.mul(&other.hi),
371            self.hi.mul(&other.lo),
372            self.hi.mul(&other.hi),
373        ];
374        let mut lo = corners[0].clone();
375        let mut hi = corners[0].clone();
376        for c in &corners[1..] {
377            lo = Bound::min_bound(&lo, c);
378            hi = Bound::max_bound(&hi, c);
379        }
380        Interval { lo, hi }
381    }
382
383    fn div(&self, other: &Interval) -> Interval {
384        if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
385            if b != 0 {
386                // `wrapping_div` matches the runtime (semantics/arith.rs) and
387                // avoids the `i64::MIN / -1` overflow panic of raw `/`.
388                return Interval::exact(a.wrapping_div(b));
389            }
390        }
391        // Constant nonzero divisor, arbitrary dividend range. Truncating
392        // division (toward zero, matching Rust `/`) is monotone in the dividend
393        // for a positive divisor, so both bounds map through; a negative divisor
394        // additionally swaps them. This generalizes the exact/exact case so a
395        // fixpoint can bound `seed / 65536`, `hi / 2`, etc.
396        if let Some(k) = other.is_exact() {
397            if k > 0 {
398                return Interval {
399                    lo: self.lo.div_by(k),
400                    hi: self.hi.div_by(k),
401                };
402            } else if k < 0 {
403                return Interval {
404                    lo: self.hi.div_by(k),
405                    hi: self.lo.div_by(k),
406                };
407            }
408        }
409        Interval::top()
410    }
411
412    fn modulo(&self, other: &Interval) -> Interval {
413        if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
414            if b != 0 {
415                // `wrapping_rem` matches the runtime (semantics/arith.rs) and
416                // avoids the `i64::MIN % -1` overflow panic of raw `%`.
417                return Interval::exact(a.wrapping_rem(b));
418            }
419        }
420        // Constant nonzero divisor, arbitrary dividend range. LOGOS `%` is the
421        // TRUNCATED remainder: `|x % k| <= |k| - 1` and the sign follows the
422        // DIVIDEND. So a provably non-negative dividend gives `[0, |k|-1]`
423        // (the counting_sort / LCG case: `seed % 2147483648 ∈ [0, 2^31-1]`,
424        // `(seed/65536) % 1000 ∈ [0, 999]`), a non-positive one `[-(|k|-1), 0]`,
425        // and a sign-spanning one `[-(|k|-1), |k|-1]`.
426        if let Some(k) = other.is_exact() {
427            if k != 0 {
428                let m = k.checked_abs().unwrap_or(i64::MAX).saturating_sub(1).max(0);
429                let nonneg = matches!(self.lo, Bound::Finite(v) if v >= 0);
430                let nonpos = matches!(self.hi, Bound::Finite(v) if v <= 0);
431                let lo = if nonneg {
432                    Bound::Finite(0)
433                } else {
434                    Bound::Finite(-m)
435                };
436                let hi = if nonpos {
437                    Bound::Finite(0)
438                } else {
439                    Bound::Finite(m)
440                };
441                return Interval { lo, hi };
442            }
443        }
444        // VARIABLE (or otherwise non-constant) divisor. The truncated
445        // remainder's SIGN still follows the dividend, so a provably
446        // non-negative dividend yields a non-negative result (magnitude
447        // unbounded without a concrete divisor) — the `x % n >= 0` element
448        // LOWER bound the symbolic prover pairs with the symbolic upper
449        // `x % n <= n - 1` (graph_bfs: `adj` filled with `(...) % n`). A
450        // zero divisor errors at runtime, so the result's range is moot.
451        let nonneg = matches!(self.lo, Bound::Finite(v) if v >= 0);
452        let nonpos = matches!(self.hi, Bound::Finite(v) if v <= 0);
453        if nonneg {
454            return Interval::non_negative();
455        }
456        if nonpos {
457            return Interval {
458                lo: Bound::NegInf,
459                hi: Bound::Finite(0),
460            };
461        }
462        Interval::top()
463    }
464
465    /// Arithmetic right shift `x >> k`. For a constant, in-range amount this is
466    /// floor(x / 2^k): monotone non-decreasing in `x`, so both endpoints map
467    /// straight through (mirrors `div` by a positive power of two). Keeps
468    /// value/element bounds alive across the e-graph's strength reduction
469    /// `x / 2^k → x >> k` — e.g. `(seed >> 16) % 1000 ∈ [0, 999]` survives,
470    /// exactly as `(seed / 65536) % 1000` did.
471    fn shr(&self, other: &Interval) -> Interval {
472        if let Some(k) = other.is_exact() {
473            if (0..64).contains(&k) {
474                let k = k as u32;
475                return Interval {
476                    lo: self.lo.shr_by(k),
477                    hi: self.hi.shr_by(k),
478                };
479            }
480        }
481        Interval::top()
482    }
483
484    /// The finite non-negative `[lo, hi]` this interval is, if it is one.
485    fn natural(&self) -> Option<(i64, i64)> {
486        match (&self.lo, &self.hi) {
487            (Bound::Finite(lo), Bound::Finite(hi)) if *lo >= 0 && lo <= hi => Some((*lo, *hi)),
488            _ => None,
489        }
490    }
491
492    /// `x & y`. A non-negative operand bounds the result to `[0, it]`, whatever the other: on two words the
493    /// result has no sign bit and no bit the non-negative one lacks, and a big integer takes a mask only when it
494    /// is not negative, leaving its low bits — any other big operand is refused, giving no value at all.
495    fn bitand(&self, other: &Interval) -> Interval {
496        if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
497            return Interval::exact(a & b);
498        }
499        let cap = |i: &Interval| match (&i.lo, &i.hi) {
500            (Bound::Finite(lo), hi) if *lo >= 0 => Some(hi.clone()),
501            _ => None,
502        };
503        match (cap(self), cap(other)) {
504            (Some(a), Some(b)) => Interval {
505                lo: Bound::Finite(0),
506                hi: Bound::min_bound(&a, &b),
507            },
508            (Some(hi), None) | (None, Some(hi)) => Interval {
509                lo: Bound::Finite(0),
510                hi,
511            },
512            (None, None) => Interval::top(),
513        }
514    }
515
516    /// `x | y` and `x ^ y` on two non-negative words: below the next power of two past both, and for `|` at
517    /// least the larger. A big operand is refused, so it gives no value.
518    fn bitor_or_xor(&self, other: &Interval, or: bool) -> Interval {
519        let (Some((al, ah)), Some((bl, bh))) = (self.natural(), other.natural()) else {
520            return Interval::top();
521        };
522        let width = 64 - (ah.max(bh) as u64).leading_zeros();
523        let ceiling = ((1u128 << width) - 1) as i64;
524        Interval {
525            lo: Bound::Finite(if or { al.max(bl) } else { 0 }),
526            hi: Bound::Finite(ceiling),
527        }
528    }
529
530    /// `x << s` for a constant `s`: the shift is by `s mod 64` (`i64::wrapping_shl`), which is the product by
531    /// `2^(s mod 64)` exactly when no endpoint's product leaves the word; otherwise it wraps, and nothing is known.
532    fn shl(&self, other: &Interval) -> Interval {
533        let (Some(s), Bound::Finite(lo), Bound::Finite(hi)) = (other.is_exact(), &self.lo, &self.hi) else {
534            return Interval::top();
535        };
536        let k = (s as u32) & 63;
537        let scale = |v: i64| i64::try_from((v as i128) << k).ok();
538        match (scale(*lo), scale(*hi)) {
539            (Some(lo), Some(hi)) => Interval {
540                lo: Bound::Finite(lo),
541                hi: Bound::Finite(hi),
542            },
543            _ => Interval::top(),
544        }
545    }
546
547    fn definitely_gt(&self, other: &Interval) -> Option<bool> {
548        use std::cmp::Ordering::{Equal, Greater, Less};
549        if self.lo.decided(&other.hi) == Some(Greater) {
550            return Some(true);
551        }
552        if matches!(self.hi.decided(&other.lo), Some(Less | Equal)) {
553            return Some(false);
554        }
555        None
556    }
557
558    fn definitely_lt(&self, other: &Interval) -> Option<bool> {
559        use std::cmp::Ordering::{Equal, Greater, Less};
560        if self.hi.decided(&other.lo) == Some(Less) {
561            return Some(true);
562        }
563        if matches!(self.lo.decided(&other.hi), Some(Greater | Equal)) {
564            return Some(false);
565        }
566        None
567    }
568
569    fn definitely_gteq(&self, other: &Interval) -> Option<bool> {
570        use std::cmp::Ordering::{Equal, Greater, Less};
571        if matches!(self.lo.decided(&other.hi), Some(Greater | Equal)) {
572            return Some(true);
573        }
574        if self.hi.decided(&other.lo) == Some(Less) {
575            return Some(false);
576        }
577        None
578    }
579
580    fn definitely_lteq(&self, other: &Interval) -> Option<bool> {
581        use std::cmp::Ordering::{Equal, Greater, Less};
582        if matches!(self.hi.decided(&other.lo), Some(Less | Equal)) {
583            return Some(true);
584        }
585        if self.lo.decided(&other.hi) == Some(Greater) {
586            return Some(false);
587        }
588        None
589    }
590
591    fn definitely_eq(&self, other: &Interval) -> Option<bool> {
592        if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
593            return Some(a == b);
594        }
595        None
596    }
597
598    fn definitely_neq(&self, other: &Interval) -> Option<bool> {
599        if self.hi.decided(&other.lo) == Some(std::cmp::Ordering::Less)
600            || self.lo.decided(&other.hi) == Some(std::cmp::Ordering::Greater)
601        {
602            return Some(true);
603        }
604        if let (Some(a), Some(b)) = (self.is_exact(), other.is_exact()) {
605            return Some(a != b);
606        }
607        None
608    }
609}
610
611impl AbstractDomain for Interval {
612    fn top() -> Self {
613        Interval::top()
614    }
615    fn bottom() -> Self {
616        Interval::bottom()
617    }
618    fn join(&self, other: &Self) -> Self {
619        Interval::join(self, other)
620    }
621    fn meet(&self, other: &Self) -> Self {
622        Interval::meet(self, other)
623    }
624    fn widen(&self, other: &Self) -> Self {
625        Interval::widen(self, other)
626    }
627    fn leq(&self, other: &Self) -> bool {
628        Interval::leq(self, other)
629    }
630}
631
632/// Concrete runtime type of a value, the atoms of the type lattice. Mirrors the
633/// scalar/temporal arms of `RuntimeValue`; aggregate/struct tags are added as the
634/// transfer functions that produce them land.
635#[derive(Clone, Debug, PartialEq, Eq, Hash)]
636enum TypeTag {
637    Int,
638    Float,
639    Bool,
640    Text,
641    Char,
642    Nothing,
643    Duration,
644    Date,
645    Moment,
646    Span,
647    Time,
648}
649
650/// The type domain: a value is exactly one type (`Concrete`), one of several
651/// (`Union`), unknown (`Top`), or unreachable (`Bottom`). Equality is by the
652/// canonical tag-set, so `Union({Int})` and `Concrete(Int)` compare equal.
653#[derive(Clone, Debug)]
654enum TypeAbstraction {
655    Bottom,
656    Concrete(TypeTag),
657    Union(std::collections::HashSet<TypeTag>),
658    Top,
659}
660
661impl TypeAbstraction {
662    /// Maximum union cardinality before collapsing to `Top` — keeps the lattice
663    /// finite-height so `widen` (= `join` here) always converges.
664    const UNION_CAP: usize = 6;
665
666    /// Canonical view: `None` is `Top`; `Some(set)` is the set of possible tags
667    /// (`Bottom` → empty set, `Concrete(t)` → `{t}`).
668    fn tag_set(&self) -> Option<std::collections::HashSet<TypeTag>> {
669        match self {
670            TypeAbstraction::Top => None,
671            TypeAbstraction::Bottom => Some(std::collections::HashSet::new()),
672            TypeAbstraction::Concrete(t) => {
673                let mut s = std::collections::HashSet::new();
674                s.insert(t.clone());
675                Some(s)
676            }
677            TypeAbstraction::Union(s) => Some(s.clone()),
678        }
679    }
680
681    fn from_tags(s: std::collections::HashSet<TypeTag>) -> Self {
682        if s.is_empty() {
683            TypeAbstraction::Bottom
684        } else if s.len() == 1 {
685            TypeAbstraction::Concrete(s.into_iter().next().unwrap())
686        } else if s.len() > Self::UNION_CAP {
687            TypeAbstraction::Top
688        } else {
689            TypeAbstraction::Union(s)
690        }
691    }
692}
693
694impl PartialEq for TypeAbstraction {
695    fn eq(&self, other: &Self) -> bool {
696        self.tag_set() == other.tag_set()
697    }
698}
699
700impl AbstractDomain for TypeAbstraction {
701    fn top() -> Self {
702        TypeAbstraction::Top
703    }
704    fn bottom() -> Self {
705        TypeAbstraction::Bottom
706    }
707
708    fn join(&self, other: &Self) -> Self {
709        match (self.tag_set(), other.tag_set()) {
710            (None, _) | (_, None) => TypeAbstraction::Top,
711            (Some(a), Some(b)) => TypeAbstraction::from_tags(a.union(&b).cloned().collect()),
712        }
713    }
714
715    fn meet(&self, other: &Self) -> Self {
716        match (self.tag_set(), other.tag_set()) {
717            (None, _) => other.clone(),
718            (_, None) => self.clone(),
719            (Some(a), Some(b)) => TypeAbstraction::from_tags(a.intersection(&b).cloned().collect()),
720        }
721    }
722
723    // Finite-height lattice (union capped at UNION_CAP): widening is just join.
724    fn widen(&self, other: &Self) -> Self {
725        self.join(other)
726    }
727
728    fn leq(&self, other: &Self) -> bool {
729        match (self.tag_set(), other.tag_set()) {
730            (_, None) => true,        // everything ⊑ Top
731            (None, Some(_)) => false, // Top ⊑ only Top
732            (Some(a), Some(b)) => a.is_subset(&b),
733        }
734    }
735}
736
737fn literal_type(lit: &Literal) -> TypeTag {
738    match lit {
739        Literal::Number(_) => TypeTag::Int,
740        Literal::Float(_) => TypeTag::Float,
741        Literal::Text(_) => TypeTag::Text,
742        Literal::Boolean(_) => TypeTag::Bool,
743        Literal::Nothing => TypeTag::Nothing,
744        Literal::Char(_) => TypeTag::Char,
745        Literal::Duration(_) => TypeTag::Duration,
746        Literal::Date(_) => TypeTag::Date,
747        Literal::Moment(_) => TypeTag::Moment,
748        Literal::Span { .. } => TypeTag::Span,
749        Literal::Time(_) => TypeTag::Time,
750    }
751}
752
753fn binop_type(op: BinaryOpKind, l: &TypeAbstraction, r: &TypeAbstraction) -> TypeAbstraction {
754    use BinaryOpKind::*;
755    let conc = |t: TypeTag| TypeAbstraction::Concrete(t);
756    let is = |a: &TypeAbstraction, t: TypeTag| matches!(a, TypeAbstraction::Concrete(x) if *x == t);
757    match op {
758        // Relational and equality always yield Bool.
759        Lt | Gt | LtEq | GtEq | Eq | NotEq | ApproxEq => conc(TypeTag::Bool),
760        // Bitwise on ints; on Sets these are set ops — Top keeps them out of
761        // numeric reductions.
762        BitAnd | BitOr => TypeAbstraction::Top,
763        // Explicit concatenation is always Text.
764        Concat => conc(TypeTag::Text),
765        // Sequence concatenation yields a sequence — `Top` keeps it out of numeric reductions.
766        SeqConcat => TypeAbstraction::Top,
767        Add => {
768            if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
769                conc(TypeTag::Int)
770            } else if is(l, TypeTag::Float) && is(r, TypeTag::Float) {
771                conc(TypeTag::Float)
772            } else if is(l, TypeTag::Text) || is(r, TypeTag::Text) {
773                conc(TypeTag::Text)
774            } else {
775                TypeAbstraction::Top
776            }
777        }
778        // ExactDivide produces a Rational, never a known Int — `Top` keeps a
779        // Rational-derived value out of the integer-only strength reductions.
780        // Pow can promote to BigInt (or a Float) — `Top` likewise.
781        ExactDivide | Pow => TypeAbstraction::Top,
782        Subtract | Multiply | Divide | FloorDivide | Modulo => {
783            if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
784                conc(TypeTag::Int)
785            } else if is(l, TypeTag::Float) && is(r, TypeTag::Float) {
786                conc(TypeTag::Float)
787            } else {
788                TypeAbstraction::Top
789            }
790        }
791        And | Or => {
792            if is(l, TypeTag::Bool) && is(r, TypeTag::Bool) {
793                conc(TypeTag::Bool)
794            } else if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
795                conc(TypeTag::Int)
796            } else {
797                TypeAbstraction::Top
798            }
799        }
800        BitXor | Shl | Shr => {
801            if is(l, TypeTag::Int) && is(r, TypeTag::Int) {
802                conc(TypeTag::Int)
803            } else {
804                TypeAbstraction::Top
805            }
806        }
807    }
808}
809
810fn eval_type(
811    expr: &Expr,
812    types: &HashMap<Symbol, TypeAbstraction>,
813    fn_returns: &HashMap<Symbol, TypeTag>,
814    elem_type: &HashMap<Symbol, TypeAbstraction>,
815) -> TypeAbstraction {
816    match expr {
817        Expr::Literal(lit) => TypeAbstraction::Concrete(literal_type(lit)),
818        Expr::Identifier(sym) => types.get(sym).cloned().unwrap_or(TypeAbstraction::Top),
819        Expr::BinaryOp { op, left, right } => {
820            let l = eval_type(left, types, fn_returns, elem_type);
821            let r = eval_type(right, types, fn_returns, elem_type);
822            binop_type(*op, &l, &r)
823        }
824        Expr::Not { operand } => match eval_type(operand, types, fn_returns, elem_type) {
825            TypeAbstraction::Concrete(TypeTag::Bool) => TypeAbstraction::Concrete(TypeTag::Bool),
826            TypeAbstraction::Concrete(TypeTag::Int) => TypeAbstraction::Concrete(TypeTag::Int),
827            _ => TypeAbstraction::Top,
828        },
829        Expr::Length { .. } => TypeAbstraction::Concrete(TypeTag::Int),
830        Expr::Contains { .. } => TypeAbstraction::Concrete(TypeTag::Bool),
831        // A capacity is an allocation hint, not part of the value's type.
832        // Keep every type-driven optimization identical to the unhinted form.
833        Expr::WithCapacity { value, .. } => eval_type(value, types, fn_returns, elem_type),
834        // A call's DECLARED primitive return type is a sound fact: the
835        // kernel enforces it dynamically, native signatures statically.
836        Expr::Call { function, .. } => fn_returns
837            .get(function)
838            .map(|t| TypeAbstraction::Concrete(t.clone()))
839            .unwrap_or(TypeAbstraction::Top),
840        // A read `item k of arr` carries `arr`'s proven ELEMENT TYPE — the join
841        // over every value written into it. Sound because every element IS one
842        // of those written values, so they all satisfy the join. Gated OFF by
843        // default (`Top`, the prior behaviour) for byte-identical A/B.
844        Expr::Index {
845            collection: Expr::Identifier(sym),
846            ..
847        } if elem_type_enabled() => {
848            let t = elem_type.get(sym).cloned().unwrap_or(TypeAbstraction::Top);
849            if !matches!(t, TypeAbstraction::Top) {
850                crate::optimize::mark_fired(crate::optimization::Opt::ElemType);
851            }
852            t
853        }
854        _ => TypeAbstraction::Top,
855    }
856}
857
858/// The collection-size domain — an interval over the (non-negative) length of a
859/// collection, named for the cases that drive guard elimination. Equality and
860/// the lattice ops work on the canonical `(lo, hi)` size bounds, so e.g.
861/// `KnownSize(1)` and `Singleton` are the same element.
862#[derive(Clone, Debug)]
863enum CollectionShape {
864    /// Unreachable — the `⊥` of the lattice.
865    Bottom,
866    /// length == 0
867    Empty,
868    /// length == 1
869    Singleton,
870    /// length == n
871    KnownSize(u64),
872    /// length ∈ [lo, hi]
873    SizeRange(u64, u64),
874    /// length >= 1
875    NonEmpty,
876    /// length >= 0 — the `⊤` of the lattice.
877    Top,
878}
879
880impl CollectionShape {
881    /// A freshly constructed (`a new Seq/Set/Map`) collection is empty.
882    fn empty_collection() -> Self {
883        CollectionShape::Empty
884    }
885
886    /// Canonical size bounds `(lo, hi)`; `hi == None` is unbounded above,
887    /// `None` overall is `Bottom`.
888    fn bounds(&self) -> Option<(u64, Option<u64>)> {
889        match self {
890            CollectionShape::Bottom => None,
891            CollectionShape::Empty => Some((0, Some(0))),
892            CollectionShape::Singleton => Some((1, Some(1))),
893            CollectionShape::KnownSize(n) => Some((*n, Some(*n))),
894            CollectionShape::SizeRange(lo, hi) => Some((*lo, Some(*hi))),
895            CollectionShape::NonEmpty => Some((1, None)),
896            CollectionShape::Top => Some((0, None)),
897        }
898    }
899
900    /// Reconstruct the most specific named shape from size bounds. An unbounded
901    /// lower bound `>= 2` is sound-but-lossily folded to `NonEmpty`.
902    fn from_bounds(lo: u64, hi: Option<u64>) -> Self {
903        match hi {
904            Some(h) if lo > h => CollectionShape::Bottom,
905            Some(0) => CollectionShape::Empty,
906            Some(1) if lo == 1 => CollectionShape::Singleton,
907            Some(h) if lo == h => CollectionShape::KnownSize(h),
908            Some(h) => CollectionShape::SizeRange(lo, h),
909            None if lo == 0 => CollectionShape::Top,
910            None => CollectionShape::NonEmpty,
911        }
912    }
913
914    /// Effect of `Push` — size grows by one.
915    fn pushed(&self) -> Self {
916        match self.bounds() {
917            None => CollectionShape::Bottom,
918            Some((lo, hi)) => CollectionShape::from_bounds(lo + 1, hi.map(|h| h + 1)),
919        }
920    }
921
922    /// Effect of `Pop`/`Remove` — size shrinks by one (saturating at 0).
923    fn popped(&self) -> Self {
924        match self.bounds() {
925            None => CollectionShape::Bottom,
926            Some((lo, hi)) => {
927                CollectionShape::from_bounds(lo.saturating_sub(1), hi.map(|h| h.saturating_sub(1)))
928            }
929        }
930    }
931
932    fn is_definitely_nonempty(&self) -> bool {
933        matches!(self.bounds(), Some((lo, _)) if lo >= 1)
934    }
935
936    fn is_definitely_empty(&self) -> bool {
937        matches!(self.bounds(), Some((_, Some(0))))
938    }
939}
940
941impl PartialEq for CollectionShape {
942    fn eq(&self, other: &Self) -> bool {
943        self.bounds() == other.bounds()
944    }
945}
946
947impl AbstractDomain for CollectionShape {
948    fn top() -> Self {
949        CollectionShape::Top
950    }
951    fn bottom() -> Self {
952        CollectionShape::Bottom
953    }
954
955    fn join(&self, other: &Self) -> Self {
956        match (self.bounds(), other.bounds()) {
957            (None, _) => other.clone(),
958            (_, None) => self.clone(),
959            (Some((l1, h1)), Some((l2, h2))) => {
960                let lo = l1.min(l2);
961                let hi = match (h1, h2) {
962                    (Some(a), Some(b)) => Some(a.max(b)),
963                    _ => None,
964                };
965                CollectionShape::from_bounds(lo, hi)
966            }
967        }
968    }
969
970    fn meet(&self, other: &Self) -> Self {
971        match (self.bounds(), other.bounds()) {
972            (None, _) | (_, None) => CollectionShape::Bottom,
973            (Some((l1, h1)), Some((l2, h2))) => {
974                let lo = l1.max(l2);
975                let hi = match (h1, h2) {
976                    (Some(a), Some(b)) => Some(a.min(b)),
977                    (Some(a), None) => Some(a),
978                    (None, Some(b)) => Some(b),
979                    (None, None) => None,
980                };
981                CollectionShape::from_bounds(lo, hi)
982            }
983        }
984    }
985
986    fn widen(&self, other: &Self) -> Self {
987        match (self.bounds(), other.bounds()) {
988            (None, _) => other.clone(),
989            (_, None) => self.clone(),
990            (Some((l1, h1)), Some((l2, h2))) => {
991                let lo = if l2 < l1 { 0 } else { l1 };
992                let hi = match (h1, h2) {
993                    (Some(a), Some(b)) if b <= a => Some(a),
994                    _ => None,
995                };
996                CollectionShape::from_bounds(lo, hi)
997            }
998        }
999    }
1000
1001    fn leq(&self, other: &Self) -> bool {
1002        match (self.bounds(), other.bounds()) {
1003            (None, _) => true,
1004            (_, None) => false,
1005            (Some((l1, h1)), Some((l2, h2))) => {
1006                let lo_ok = l2 <= l1;
1007                let hi_ok = match (h1, h2) {
1008                    (_, None) => true,
1009                    (None, Some(_)) => false,
1010                    (Some(a), Some(b)) => a <= b,
1011                };
1012                lo_ok && hi_ok
1013            }
1014        }
1015    }
1016}
1017
1018/// The nullability domain: is an (optional-typed) value definitely present,
1019/// definitely `nothing`, or unknown. A diamond lattice
1020/// `Bottom ⊏ {Definite, Null} ⊏ Maybe`. Used to drop `nothing`-checks the Oracle
1021/// can prove can never fail.
1022#[derive(Clone, Debug, PartialEq, Eq)]
1023enum Nullability {
1024    /// Unreachable — the `⊥` of the lattice.
1025    Bottom,
1026    /// Definitely present (not `nothing`).
1027    Definite,
1028    /// Definitely `nothing`.
1029    Null,
1030    /// Unknown — the `⊤` of the lattice.
1031    Maybe,
1032}
1033
1034impl Nullability {
1035    /// The nullability a literal establishes.
1036    fn for_literal(lit: &Literal) -> Nullability {
1037        match lit {
1038            Literal::Nothing => Nullability::Null,
1039            _ => Nullability::Definite,
1040        }
1041    }
1042
1043    /// Inside a concrete-variant `Inspect` arm (and for its field bindings) the
1044    /// matched value is present — the fact that retires the unwrap guard.
1045    fn for_matched_variant() -> Nullability {
1046        Nullability::Definite
1047    }
1048}
1049
1050impl AbstractDomain for Nullability {
1051    fn top() -> Self {
1052        Nullability::Maybe
1053    }
1054    fn bottom() -> Self {
1055        Nullability::Bottom
1056    }
1057
1058    fn join(&self, other: &Self) -> Self {
1059        use Nullability::*;
1060        match (self, other) {
1061            (Bottom, x) | (x, Bottom) => x.clone(),
1062            (Maybe, _) | (_, Maybe) => Maybe,
1063            (Definite, Definite) => Definite,
1064            (Null, Null) => Null,
1065            (Definite, Null) | (Null, Definite) => Maybe,
1066        }
1067    }
1068
1069    fn meet(&self, other: &Self) -> Self {
1070        use Nullability::*;
1071        match (self, other) {
1072            (Maybe, x) | (x, Maybe) => x.clone(),
1073            (Bottom, _) | (_, Bottom) => Bottom,
1074            (Definite, Definite) => Definite,
1075            (Null, Null) => Null,
1076            (Definite, Null) | (Null, Definite) => Bottom,
1077        }
1078    }
1079
1080    // Four-element lattice → widening is join.
1081    fn widen(&self, other: &Self) -> Self {
1082        self.join(other)
1083    }
1084
1085    fn leq(&self, other: &Self) -> bool {
1086        *self == Nullability::Bottom || *other == Nullability::Maybe || self == other
1087    }
1088}
1089
1090/// The aliasing domain (a may-alias set). LOGOS collections are
1091/// `Rc<RefCell<_>>`, so `Let a be items.` makes `a` and `items` two names for
1092/// one allocation: a mutation through either must invalidate facts about both.
1093/// `Unique` (aliases nobody) `⊏ MayAlias(set) ⊏ Top` (aliases anything).
1094#[derive(Clone, Debug)]
1095enum AliasInfo {
1096    /// Unreachable — the `⊥` of the lattice.
1097    Bottom,
1098    /// No other name refers to this allocation — may-alias `∅`.
1099    Unique,
1100    /// May share its allocation with any of these variables.
1101    MayAlias(HashSet<Symbol>),
1102    /// May alias anything — the `⊤` of the lattice.
1103    Top,
1104}
1105
1106/// Canonical three-state view of an `AliasInfo` (`Bottom` / finite may-set / `⊤`).
1107enum AliasReach {
1108    Bottom,
1109    Finite(HashSet<Symbol>),
1110    Anything,
1111}
1112
1113impl AliasInfo {
1114    fn reach(&self) -> AliasReach {
1115        match self {
1116            AliasInfo::Bottom => AliasReach::Bottom,
1117            AliasInfo::Unique => AliasReach::Finite(HashSet::new()),
1118            AliasInfo::MayAlias(s) => AliasReach::Finite(s.clone()),
1119            AliasInfo::Top => AliasReach::Anything,
1120        }
1121    }
1122
1123    fn from_reach(r: AliasReach) -> Self {
1124        match r {
1125            AliasReach::Bottom => AliasInfo::Bottom,
1126            AliasReach::Anything => AliasInfo::Top,
1127            AliasReach::Finite(s) => {
1128                if s.is_empty() {
1129                    AliasInfo::Unique
1130                } else {
1131                    AliasInfo::MayAlias(s)
1132                }
1133            }
1134        }
1135    }
1136}
1137
1138impl PartialEq for AliasInfo {
1139    fn eq(&self, other: &Self) -> bool {
1140        match (self.reach(), other.reach()) {
1141            (AliasReach::Bottom, AliasReach::Bottom) => true,
1142            (AliasReach::Anything, AliasReach::Anything) => true,
1143            (AliasReach::Finite(a), AliasReach::Finite(b)) => a == b,
1144            _ => false,
1145        }
1146    }
1147}
1148
1149impl AbstractDomain for AliasInfo {
1150    fn top() -> Self {
1151        AliasInfo::Top
1152    }
1153    fn bottom() -> Self {
1154        AliasInfo::Bottom
1155    }
1156
1157    fn join(&self, other: &Self) -> Self {
1158        match (self.reach(), other.reach()) {
1159            (AliasReach::Bottom, _) => other.clone(),
1160            (_, AliasReach::Bottom) => self.clone(),
1161            (AliasReach::Anything, _) | (_, AliasReach::Anything) => AliasInfo::Top,
1162            (AliasReach::Finite(a), AliasReach::Finite(b)) => {
1163                AliasInfo::from_reach(AliasReach::Finite(a.union(&b).cloned().collect()))
1164            }
1165        }
1166    }
1167
1168    fn meet(&self, other: &Self) -> Self {
1169        match (self.reach(), other.reach()) {
1170            (AliasReach::Bottom, _) | (_, AliasReach::Bottom) => AliasInfo::Bottom,
1171            (AliasReach::Anything, _) => other.clone(),
1172            (_, AliasReach::Anything) => self.clone(),
1173            (AliasReach::Finite(a), AliasReach::Finite(b)) => {
1174                AliasInfo::from_reach(AliasReach::Finite(a.intersection(&b).cloned().collect()))
1175            }
1176        }
1177    }
1178
1179    // May-alias sets are bounded by the program's variables → widen is join.
1180    fn widen(&self, other: &Self) -> Self {
1181        self.join(other)
1182    }
1183
1184    fn leq(&self, other: &Self) -> bool {
1185        match (self.reach(), other.reach()) {
1186            (AliasReach::Bottom, _) => true,
1187            (_, AliasReach::Anything) => true,
1188            (AliasReach::Anything, _) => false,
1189            (_, AliasReach::Bottom) => false,
1190            (AliasReach::Finite(a), AliasReach::Finite(b)) => a.is_subset(&b),
1191        }
1192    }
1193}
1194
1195/// The may-alias relation over a scope: an undirected graph whose connected
1196/// components are sets of variables that share one `Rc<RefCell<_>>`. A mutation
1197/// through any vertex invalidates abstract facts for its whole component.
1198///
1199/// `tainted` marks handles of UNKNOWN PROVENANCE — produced by calls,
1200/// extracted from containers (Index/Slice/FieldAccess/Pop/Repeat/Inspect
1201/// bindings), or received as function parameters. A tainted handle may alias
1202/// anything; only a fresh rebinding clears the mark. The invariant the
1203/// distinctness query rests on: an UNtainted handle's component is a
1204/// complete account of its possible aliases.
1205#[derive(Clone, Default)]
1206struct AliasGraph {
1207    edges: HashMap<Symbol, HashSet<Symbol>>,
1208    tainted: HashSet<Symbol>,
1209}
1210
1211impl AliasGraph {
1212    fn new() -> Self {
1213        AliasGraph::default()
1214    }
1215
1216    /// `Let a be b.` / `Set a to b.` where `b` is an identifier: `a` and `b`
1217    /// alias the same allocation.
1218    fn link(&mut self, a: Symbol, b: Symbol) {
1219        if a == b {
1220            return;
1221        }
1222        self.edges.entry(a).or_default().insert(b);
1223        self.edges.entry(b).or_default().insert(a);
1224        // Aliasing a tainted handle spreads its unknown provenance.
1225        if self.tainted.contains(&a) {
1226            self.tainted.insert(b);
1227        }
1228        if self.tainted.contains(&b) {
1229            self.tainted.insert(a);
1230        }
1231    }
1232
1233    /// Mark `a` as a handle of unknown provenance.
1234    fn taint(&mut self, a: Symbol) {
1235        self.tainted.insert(a);
1236    }
1237
1238    /// Union the edges and taint of `other` into `self`; true if anything grew.
1239    fn union_from(&mut self, other: &AliasGraph) -> bool {
1240        let mut grew = false;
1241        for (k, ns) in &other.edges {
1242            let e = self.edges.entry(*k).or_default();
1243            for n in ns {
1244                if e.insert(*n) {
1245                    grew = true;
1246                }
1247            }
1248        }
1249        for t in &other.tainted {
1250            if self.tainted.insert(*t) {
1251                grew = true;
1252            }
1253        }
1254        grew
1255    }
1256
1257    /// PROOF of distinctness: both handles have fully tracked provenance and
1258    /// their components do not meet. Anything tainted refuses.
1259    fn definitely_distinct(&self, a: Symbol, b: Symbol) -> bool {
1260        if a == b || self.tainted.contains(&a) || self.tainted.contains(&b) {
1261            return false;
1262        }
1263        !self.may_alias(a).contains(&b)
1264    }
1265
1266    /// Every variable that may alias `v` (its connected component, including `v`).
1267    fn may_alias(&self, v: Symbol) -> HashSet<Symbol> {
1268        let mut seen = HashSet::new();
1269        let mut stack = vec![v];
1270        while let Some(x) = stack.pop() {
1271            if seen.insert(x) {
1272                if let Some(ns) = self.edges.get(&x) {
1273                    for &n in ns {
1274                        if !seen.contains(&n) {
1275                            stack.push(n);
1276                        }
1277                    }
1278                }
1279            }
1280        }
1281        seen
1282    }
1283
1284    /// The facts to invalidate when a mutation flows through `v`.
1285    fn invalidated_by_mutation(&self, v: Symbol) -> HashSet<Symbol> {
1286        self.may_alias(v)
1287    }
1288
1289    /// Rebinding `a` to a fresh allocation severs its old alias edges and
1290    /// clears its taint: the new value's provenance is known again.
1291    fn unlink(&mut self, a: Symbol) {
1292        if let Some(ns) = self.edges.remove(&a) {
1293            for n in ns {
1294                if let Some(s) = self.edges.get_mut(&n) {
1295                    s.remove(&a);
1296                }
1297            }
1298        }
1299        self.tainted.remove(&a);
1300    }
1301}
1302
1303#[derive(Clone)]
1304struct AbstractState {
1305    /// What any call in this program may write — shared by every state cloned from the entry.
1306    globals: std::rc::Rc<CalleeGlobals>,
1307    vars: HashMap<Symbol, Interval>,
1308    lengths: HashMap<Symbol, Interval>,
1309    /// Per-collection ELEMENT interval: a bound satisfied by EVERY element of
1310    /// the collection, joined over the values written into it. Lets a read
1311    /// `item k of arr` carry a value range (`(seed/65536) % 1000 ∈ [0,999]`
1312    /// pushed into `arr` ⟹ `item i of arr ∈ [0,999]`), which in turn proves a
1313    /// scatter index `counts[v+1]` in bounds. `None`/absent = unknown (`top`).
1314    elem: HashMap<Symbol, Interval>,
1315}
1316
1317impl AbstractState {
1318    fn new() -> Self {
1319        AbstractState::with_globals(std::rc::Rc::default())
1320    }
1321
1322    fn with_globals(globals: std::rc::Rc<CalleeGlobals>) -> Self {
1323        AbstractState {
1324            globals,
1325            vars: HashMap::new(),
1326            lengths: HashMap::new(),
1327            elem: HashMap::new(),
1328        }
1329    }
1330
1331    /// What `stmt` may write, with the program's callee-written globals folded in when it calls.
1332    fn effects_of(&self, stmt: &Stmt) -> WriteSet {
1333        WriteSet::of_stmt(stmt).with_callee_globals(&self.globals)
1334    }
1335
1336    /// What EVALUATING `expr` may write (through the calls it makes).
1337    fn effects_of_expr(&self, expr: &Expr) -> WriteSet {
1338        WriteSet::of_expr(expr).with_callee_globals(&self.globals)
1339    }
1340
1341    /// Forget every fact a statement with these effects may have made stale: the written variables
1342    /// and lengths go to `top` — everything, after foreign code.
1343    fn forget(&mut self, effects: &WriteSet) {
1344        if effects.is_opaque() {
1345            self.forget_all();
1346            return;
1347        }
1348        for sym in effects.symbols() {
1349            self.set_var(sym, Interval::top());
1350            self.set_length(sym, Interval::top());
1351        }
1352    }
1353
1354    fn forget_all(&mut self) {
1355        self.vars.clear();
1356        self.lengths.clear();
1357        self.elem.clear();
1358    }
1359
1360    fn get_var(&self, sym: &Symbol) -> Interval {
1361        self.vars.get(sym).cloned().unwrap_or(Interval::top())
1362    }
1363
1364    fn set_var(&mut self, sym: Symbol, range: Interval) {
1365        self.vars.insert(sym, range);
1366    }
1367
1368    fn get_length(&self, sym: &Symbol) -> Interval {
1369        self.lengths
1370            .get(sym)
1371            .cloned()
1372            .unwrap_or(Interval::non_negative())
1373    }
1374
1375    fn set_length(&mut self, sym: Symbol, range: Interval) {
1376        self.lengths.insert(sym, range);
1377    }
1378
1379    /// The proven element interval of a collection, or `top` if unknown.
1380    fn get_elem(&self, sym: &Symbol) -> Interval {
1381        self.elem.get(sym).cloned().unwrap_or(Interval::top())
1382    }
1383
1384    /// Record an element written into `sym`: JOIN with the existing element
1385    /// bound (every element must satisfy the union). Absent means "no element
1386    /// yet" — the first write seeds it exactly.
1387    fn observe_elem(&mut self, sym: Symbol, range: Interval) {
1388        let joined = match self.elem.get(&sym) {
1389            Some(existing) => existing.join(&range),
1390            None => range,
1391        };
1392        self.elem.insert(sym, joined);
1393    }
1394
1395    /// Forget the element bound (collection rebound, aliased, or written with
1396    /// an unknown value).
1397    fn clear_elem(&mut self, sym: &Symbol) {
1398        self.elem.remove(sym);
1399    }
1400}
1401
1402fn eval_expr(expr: &Expr, state: &AbstractState) -> Interval {
1403    match expr {
1404        Expr::Literal(Literal::Number(n)) => Interval::exact(*n),
1405        Expr::Literal(Literal::Boolean(_)) => Interval::top(),
1406        Expr::Literal(Literal::Float(_)) => Interval::top(),
1407        Expr::Identifier(sym) => state.get_var(sym),
1408        Expr::BinaryOp { op, left, right } => {
1409            let l = eval_expr(left, state);
1410            let r = eval_expr(right, state);
1411            match op {
1412                BinaryOpKind::Add => l.add(&r),
1413                BinaryOpKind::Subtract => l.sub(&r),
1414                BinaryOpKind::Multiply => l.mul(&r),
1415                BinaryOpKind::Divide => l.div(&r),
1416                // ExactDivide yields a Rational — it has NO integer interval, so report
1417                // `top`. This is also the defense that keeps a Rational-derived value
1418                // from being "proven Int": the integer-only division strength reductions
1419                // (MagicDivU / DivPow2) require a proven non-negative Int and so never
1420                // misfire on it.
1421                BinaryOpKind::ExactDivide => Interval::top(),
1422                BinaryOpKind::Modulo => l.modulo(&r),
1423                BinaryOpKind::Shr => l.shr(&r),
1424                BinaryOpKind::Shl => l.shl(&r),
1425                BinaryOpKind::BitAnd => l.bitand(&r),
1426                BinaryOpKind::BitOr => l.bitor_or_xor(&r, true),
1427                BinaryOpKind::BitXor => l.bitor_or_xor(&r, false),
1428                _ => Interval::top(),
1429            }
1430        }
1431        Expr::Length { collection } => {
1432            if let Expr::Identifier(sym) = collection {
1433                state.get_length(sym)
1434            } else {
1435                Interval::non_negative()
1436            }
1437        }
1438        // A read `item k of arr` carries `arr`'s proven ELEMENT interval — the
1439        // value-range-through-memory step that turns an element into a usable
1440        // scatter index (`item i of arr ∈ [0,999]` ⟹ `counts[that + 1]` in
1441        // bounds). Unknown element bound ⟹ `top`, exactly as before.
1442        Expr::Index { collection, .. } => {
1443            if let Expr::Identifier(sym) = collection {
1444                state.get_elem(sym)
1445            } else {
1446                Interval::top()
1447            }
1448        }
1449        _ => Interval::top(),
1450    }
1451}
1452
1453fn eval_condition(cond: &Expr, state: &AbstractState) -> Option<bool> {
1454    match cond {
1455        Expr::Literal(Literal::Boolean(b)) => Some(*b),
1456        Expr::BinaryOp { op, left, right } => {
1457            let l = eval_expr(left, state);
1458            let r = eval_expr(right, state);
1459            match op {
1460                BinaryOpKind::Gt => l.definitely_gt(&r),
1461                BinaryOpKind::Lt => l.definitely_lt(&r),
1462                BinaryOpKind::GtEq => l.definitely_gteq(&r),
1463                BinaryOpKind::LtEq => l.definitely_lteq(&r),
1464                BinaryOpKind::Eq => l.definitely_eq(&r),
1465                BinaryOpKind::NotEq => l.definitely_neq(&r),
1466                _ => None,
1467            }
1468        }
1469        Expr::Not { operand } => eval_condition(operand, state).map(|b| !b),
1470        _ => None,
1471    }
1472}
1473
1474fn narrow_state(cond: &Expr, state: &mut AbstractState) {
1475    narrow_by_comparison(cond, state, false);
1476}
1477
1478fn narrow_state_negated(cond: &Expr, state: &mut AbstractState) {
1479    narrow_by_comparison(cond, state, true);
1480}
1481
1482/// Narrow the names a comparison compares by what its holding (or, `negated`, its failing) says, over intervals. The
1483/// relation that holds is put as `small < big` or `small <= big`: a name on the small side is at most the big side's
1484/// largest value (one less when strict), a name on the big side at least the small side's smallest (one more when
1485/// strict), and an equality that holds puts each name inside the other side's interval. Sound whatever the other
1486/// side's interval is, since a fact that holds only discards values it excludes: `j <= limit` bounds `j` by `limit`'s
1487/// own bound, where only a constant `limit` used to.
1488fn narrow_by_comparison(cond: &Expr, state: &mut AbstractState, negated: bool) {
1489    let Expr::BinaryOp { op, left, right } = cond else {
1490        return;
1491    };
1492    let holds = match (op, negated) {
1493        (BinaryOpKind::Lt, false) | (BinaryOpKind::GtEq, true) => BinaryOpKind::Lt,
1494        (BinaryOpKind::LtEq, false) | (BinaryOpKind::Gt, true) => BinaryOpKind::LtEq,
1495        (BinaryOpKind::Gt, false) | (BinaryOpKind::LtEq, true) => BinaryOpKind::Gt,
1496        (BinaryOpKind::GtEq, false) | (BinaryOpKind::Lt, true) => BinaryOpKind::GtEq,
1497        (BinaryOpKind::Eq, false) | (BinaryOpKind::NotEq, true) => BinaryOpKind::Eq,
1498        _ => return,
1499    };
1500    let (l, r) = (eval_expr(left, state), eval_expr(right, state));
1501    let cap = |state: &mut AbstractState, e: &Expr, hi: &Bound| {
1502        if let Expr::Identifier(sym) = e {
1503            let cur = state.get_var(sym);
1504            state.set_var(
1505                *sym,
1506                Interval {
1507                    lo: cur.lo.clone(),
1508                    hi: Bound::min_bound(&cur.hi, hi),
1509                },
1510            );
1511        }
1512    };
1513    let floor = |state: &mut AbstractState, e: &Expr, lo: &Bound| {
1514        if let Expr::Identifier(sym) = e {
1515            let cur = state.get_var(sym);
1516            state.set_var(
1517                *sym,
1518                Interval {
1519                    lo: Bound::max_bound(&cur.lo, lo),
1520                    hi: cur.hi.clone(),
1521                },
1522            );
1523        }
1524    };
1525    // A strict bound moves by one; at the very edge of i64 there is no such value, and nothing is narrowed.
1526    let step = |b: &Bound, by: i64| -> Option<Bound> {
1527        match b {
1528            Bound::Finite(n) => n.checked_add(by).map(Bound::Finite),
1529            other => Some(other.clone()),
1530        }
1531    };
1532    let (small, big, small_iv, big_iv, strict) = match holds {
1533        BinaryOpKind::Lt => (left, right, &l, &r, true),
1534        BinaryOpKind::LtEq => (left, right, &l, &r, false),
1535        BinaryOpKind::Gt => (right, left, &r, &l, true),
1536        BinaryOpKind::GtEq => (right, left, &r, &l, false),
1537        _ => {
1538            cap(state, left, &r.hi);
1539            floor(state, left, &r.lo);
1540            cap(state, right, &l.hi);
1541            floor(state, right, &l.lo);
1542            return;
1543        }
1544    };
1545    let by = if strict { 1 } else { 0 };
1546    if let Some(hi) = step(&big_iv.hi, -by) {
1547        cap(state, small, &hi);
1548    }
1549    if let Some(lo) = step(&small_iv.lo, by) {
1550        floor(state, big, &lo);
1551    }
1552}
1553
1554pub fn abstract_interp_stmts<'a>(
1555    stmts: Vec<Stmt<'a>>,
1556    expr_arena: &'a Arena<Expr<'a>>,
1557    stmt_arena: &'a Arena<Stmt<'a>>,
1558) -> Vec<Stmt<'a>> {
1559    let mut state =
1560        AbstractState::with_globals(std::rc::Rc::new(CalleeGlobals::of_program(&stmts)));
1561    interp_block(stmts, &mut state, expr_arena, stmt_arena)
1562}
1563
1564fn interp_block<'a>(
1565    stmts: Vec<Stmt<'a>>,
1566    state: &mut AbstractState,
1567    expr_arena: &'a Arena<Expr<'a>>,
1568    stmt_arena: &'a Arena<Stmt<'a>>,
1569) -> Vec<Stmt<'a>> {
1570    let mut result = Vec::with_capacity(stmts.len());
1571
1572    for stmt in stmts {
1573        // Everything this statement may write — its nested blocks and the globals its calls reach included.
1574        let effects = state.effects_of(&stmt);
1575        match stmt {
1576            Stmt::Let {
1577                var,
1578                ty,
1579                value,
1580                mutable,
1581            } => {
1582                // A call in the value runs before `var` takes it: what it may write is unknown from here on.
1583                let value_effects = state.effects_of_expr(value);
1584                state.forget(&value_effects);
1585                let range = eval_expr(value, state);
1586                state.set_var(var, range);
1587                if matches!(value, Expr::New { .. }) {
1588                    state.set_length(var, Interval::exact(0));
1589                }
1590                result.push(Stmt::Let {
1591                    var,
1592                    ty,
1593                    value,
1594                    mutable,
1595                });
1596            }
1597
1598            Stmt::Set { target, value } => {
1599                let value_effects = state.effects_of_expr(value);
1600                state.forget(&value_effects);
1601                let range = eval_expr(value, state);
1602                state.set_var(target, range);
1603                result.push(Stmt::Set { target, value });
1604            }
1605
1606            Stmt::Push { value, collection } => {
1607                let value_effects = state.effects_of_expr(value);
1608                state.forget(&value_effects);
1609                if let Expr::Identifier(sym) = collection {
1610                    let cur_len = state.get_length(sym);
1611                    state.set_length(*sym, cur_len.add(&Interval::exact(1)));
1612                }
1613                result.push(Stmt::Push { value, collection });
1614            }
1615
1616            Stmt::If {
1617                cond,
1618                then_block,
1619                else_block,
1620            } => {
1621                let cond_effects = state.effects_of_expr(cond);
1622                state.forget(&cond_effects);
1623                if let Some(val) = eval_condition(cond, state) {
1624                    let new_cond = expr_arena.alloc(Expr::Literal(Literal::Boolean(val)));
1625                    if val {
1626                        let mut then_state = state.clone();
1627                        narrow_state(cond, &mut then_state);
1628                        let new_then = interp_nested_block(
1629                            then_block,
1630                            &mut then_state,
1631                            expr_arena,
1632                            stmt_arena,
1633                        );
1634                        *state = then_state;
1635                        result.push(Stmt::If {
1636                            cond: new_cond,
1637                            then_block: new_then,
1638                            else_block: None,
1639                        });
1640                    } else {
1641                        if let Some(eb) = else_block {
1642                            let mut else_state = state.clone();
1643                            narrow_state_negated(cond, &mut else_state);
1644                            let new_else =
1645                                interp_nested_block(eb, &mut else_state, expr_arena, stmt_arena);
1646                            *state = else_state;
1647                            result.push(Stmt::If {
1648                                cond: new_cond,
1649                                then_block: stmt_arena.alloc_slice(vec![]),
1650                                else_block: Some(new_else),
1651                            });
1652                        } else {
1653                            result.push(Stmt::If {
1654                                cond: new_cond,
1655                                then_block: stmt_arena.alloc_slice(vec![]),
1656                                else_block: None,
1657                            });
1658                        }
1659                    }
1660                } else {
1661                    let mut then_state = state.clone();
1662                    narrow_state(cond, &mut then_state);
1663                    let new_then =
1664                        interp_nested_block(then_block, &mut then_state, expr_arena, stmt_arena);
1665
1666                    let (new_else, else_state) = if let Some(eb) = else_block {
1667                        let mut es = state.clone();
1668                        narrow_state_negated(cond, &mut es);
1669                        let ne = interp_nested_block(eb, &mut es, expr_arena, stmt_arena);
1670                        (Some(ne), Some(es))
1671                    } else {
1672                        (None, None)
1673                    };
1674
1675                    if let Some(es) = else_state {
1676                        join_states(state, &then_state, &es);
1677                    } else {
1678                        let orig = state.clone();
1679                        join_states(state, &then_state, &orig);
1680                    }
1681
1682                    result.push(Stmt::If {
1683                        cond,
1684                        then_block: new_then,
1685                        else_block: new_else,
1686                    });
1687                }
1688            }
1689
1690            Stmt::While {
1691                cond,
1692                body,
1693                decreasing,
1694            } => {
1695                let mut loop_state = state.clone();
1696
1697                // Widen everything the loop may write — variables (the counter included), lengths, and
1698                // the globals any call in it reaches — to their full range before analyzing the body: a
1699                // loop carries them across iterations, so every pre-loop fact about them is stale from
1700                // the first iteration on (the Oracle must not fold a `(length of xs) > 0` guard against
1701                // a stale pre-loop length). Foreign code in the body forgets everything.
1702                loop_state.forget(&effects);
1703
1704                // Now narrow the loop state based on the condition.
1705                // For the bounded variable (counter), this gives it the range
1706                // from its initial value (widened to top above) narrowed by the
1707                // condition, resulting in [-inf, bound].
1708                narrow_state(cond, &mut loop_state);
1709
1710                let new_body = interp_nested_block(body, &mut loop_state, expr_arena, stmt_arena);
1711
1712                // After the loop: whatever it may have written holds what its last iteration left, so it is
1713                // unknown here; and the loop ended because its condition failed, unless a `Break` of its own
1714                // ended it with the condition still holding.
1715                state.forget(&effects);
1716                if !crate::loop_shape::leaves_by_break(body) {
1717                    narrow_state_negated(cond, state);
1718                }
1719
1720                result.push(Stmt::While {
1721                    cond,
1722                    body: new_body,
1723                    decreasing,
1724                });
1725            }
1726
1727            Stmt::Repeat {
1728                pattern,
1729                iterable,
1730                body,
1731            } => {
1732                let mut loop_state = state.clone();
1733
1734                if let Pattern::Identifier(var) = &pattern {
1735                    loop_state.set_var(*var, Interval::top());
1736                }
1737
1738                loop_state.forget(&effects);
1739
1740                let new_body = interp_nested_block(body, &mut loop_state, expr_arena, stmt_arena);
1741
1742                state.forget(&effects);
1743
1744                result.push(Stmt::Repeat {
1745                    pattern,
1746                    iterable,
1747                    body: new_body,
1748                });
1749            }
1750
1751            Stmt::FunctionDef {
1752                name,
1753                params,
1754                generics,
1755                body,
1756                return_type,
1757                is_native,
1758                native_path,
1759                is_exported,
1760                export_target,
1761                opt_flags,
1762            } => {
1763                let mut func_state = AbstractState::with_globals(state.globals.clone());
1764                let new_body = interp_nested_block(body, &mut func_state, expr_arena, stmt_arena);
1765                result.push(Stmt::FunctionDef {
1766                    name,
1767                    params,
1768                    generics,
1769                    body: new_body,
1770                    return_type,
1771                    is_native,
1772                    native_path,
1773                    is_exported,
1774                    export_target,
1775                    opt_flags,
1776                });
1777            }
1778
1779            Stmt::Inspect {
1780                target,
1781                arms,
1782                has_otherwise,
1783            } => {
1784                let new_arms: Vec<_> = arms
1785                    .into_iter()
1786                    .map(|arm| {
1787                        let mut arm_state = state.clone();
1788                        let new_body =
1789                            interp_nested_block(arm.body, &mut arm_state, expr_arena, stmt_arena);
1790                        crate::ast::stmt::MatchArm {
1791                            enum_name: arm.enum_name,
1792                            variant: arm.variant,
1793                            bindings: arm.bindings,
1794                            body: new_body,
1795                        }
1796                    })
1797                    .collect();
1798                // Whatever any arm may have written is unknown after the `Inspect`.
1799                state.forget(&effects);
1800                result.push(Stmt::Inspect {
1801                    target,
1802                    arms: new_arms,
1803                    has_otherwise,
1804                });
1805            }
1806
1807            Stmt::Zone { .. } => {
1808                // Don't analyze inside zones — zone-scoped bindings must be
1809                // preserved for escape analysis (same as propagation pass).
1810                state.forget(&effects);
1811                result.push(stmt);
1812            }
1813
1814            Stmt::Concurrent { tasks } => {
1815                let mut sub_state = state.clone();
1816                let new_tasks = interp_nested_block(tasks, &mut sub_state, expr_arena, stmt_arena);
1817                state.forget(&effects);
1818                result.push(Stmt::Concurrent { tasks: new_tasks });
1819            }
1820
1821            Stmt::Parallel { tasks } => {
1822                let mut sub_state = state.clone();
1823                let new_tasks = interp_nested_block(tasks, &mut sub_state, expr_arena, stmt_arena);
1824                state.forget(&effects);
1825                result.push(Stmt::Parallel { tasks: new_tasks });
1826            }
1827
1828            // Every other statement passes through; whatever it may write is unknown afterwards.
1829            other => {
1830                state.forget(&effects);
1831                result.push(other);
1832            }
1833        }
1834    }
1835
1836    result
1837}
1838
1839fn interp_nested_block<'a>(
1840    block: &'a [Stmt<'a>],
1841    state: &mut AbstractState,
1842    expr_arena: &'a Arena<Expr<'a>>,
1843    stmt_arena: &'a Arena<Stmt<'a>>,
1844) -> &'a [Stmt<'a>] {
1845    let stmts: Vec<Stmt<'a>> = block.iter().cloned().collect();
1846    let result = interp_block(stmts, state, expr_arena, stmt_arena);
1847    stmt_arena.alloc_slice(result)
1848}
1849
1850fn join_states(out: &mut AbstractState, a: &AbstractState, b: &AbstractState) {
1851    let mut all_keys: std::collections::HashSet<Symbol> = a.vars.keys().cloned().collect();
1852    all_keys.extend(b.vars.keys().cloned());
1853
1854    for key in all_keys {
1855        let a_range = a.vars.get(&key).cloned().unwrap_or(Interval::top());
1856        let b_range = b.vars.get(&key).cloned().unwrap_or(Interval::top());
1857        out.set_var(key, a_range.join(&b_range));
1858    }
1859
1860    let mut len_keys: std::collections::HashSet<Symbol> = a.lengths.keys().cloned().collect();
1861    len_keys.extend(b.lengths.keys().cloned());
1862
1863    for key in len_keys {
1864        let a_len = a
1865            .lengths
1866            .get(&key)
1867            .cloned()
1868            .unwrap_or(Interval::non_negative());
1869        let b_len = b
1870            .lengths
1871            .get(&key)
1872            .cloned()
1873            .unwrap_or(Interval::non_negative());
1874        out.set_length(key, a_len.join(&b_len));
1875    }
1876
1877    // Element bounds: absent means UNKNOWN (`top`), so a key tracked on only
1878    // one path joins to `top` (sound — the other path could hold anything). An
1879    // EMPTY fresh collection is seeded `⊥` (no elements), so the 0-iteration
1880    // branch of a build loop's exit join preserves the filled branch's bound.
1881    let mut el_keys: std::collections::HashSet<Symbol> = a.elem.keys().cloned().collect();
1882    el_keys.extend(b.elem.keys().cloned());
1883    for key in el_keys {
1884        let a_el = a.get_elem(&key);
1885        let b_el = b.get_elem(&key);
1886        out.elem.insert(key, a_el.join(&b_el));
1887    }
1888}
1889
1890// ============================================================================
1891// The Oracle: product lattice + rich, fact-returning analysis (EXODIA Phase 1).
1892//
1893// `abstract_interp_stmts` above transforms the program (interval-driven dead
1894// branch elimination). `rich_abstract_interp_stmts` below is additive: it leaves
1895// the program unchanged and hands back the five-domain abstract facts the VM and
1896// copy-and-patch JIT consult to choose typed stencils and drop guards.
1897// ============================================================================
1898
1899/// The product abstract value — the five domains combined componentwise.
1900#[derive(Clone, Debug)]
1901pub(crate) struct AbstractValue {
1902    interval: Interval,
1903    ty: TypeAbstraction,
1904    shape: CollectionShape,
1905    nullability: Nullability,
1906    alias: AliasInfo,
1907}
1908
1909impl AbstractDomain for AbstractValue {
1910    fn top() -> Self {
1911        AbstractValue {
1912            interval: Interval::top(),
1913            ty: TypeAbstraction::Top,
1914            shape: CollectionShape::Top,
1915            nullability: Nullability::Maybe,
1916            alias: AliasInfo::Top,
1917        }
1918    }
1919
1920    fn bottom() -> Self {
1921        AbstractValue {
1922            interval: Interval::bottom(),
1923            ty: TypeAbstraction::Bottom,
1924            shape: CollectionShape::Bottom,
1925            nullability: Nullability::Bottom,
1926            alias: AliasInfo::Bottom,
1927        }
1928    }
1929
1930    fn join(&self, o: &Self) -> Self {
1931        AbstractValue {
1932            interval: self.interval.join(&o.interval),
1933            ty: self.ty.join(&o.ty),
1934            shape: self.shape.join(&o.shape),
1935            nullability: self.nullability.join(&o.nullability),
1936            alias: self.alias.join(&o.alias),
1937        }
1938    }
1939
1940    fn meet(&self, o: &Self) -> Self {
1941        AbstractValue {
1942            interval: self.interval.meet(&o.interval),
1943            ty: self.ty.meet(&o.ty),
1944            shape: self.shape.meet(&o.shape),
1945            nullability: self.nullability.meet(&o.nullability),
1946            alias: self.alias.meet(&o.alias),
1947        }
1948    }
1949
1950    fn widen(&self, o: &Self) -> Self {
1951        AbstractValue {
1952            interval: self.interval.widen(&o.interval),
1953            ty: self.ty.widen(&o.ty),
1954            shape: self.shape.widen(&o.shape),
1955            nullability: self.nullability.widen(&o.nullability),
1956            alias: self.alias.widen(&o.alias),
1957        }
1958    }
1959
1960    fn leq(&self, o: &Self) -> bool {
1961        self.interval.leq(&o.interval)
1962            && self.ty.leq(&o.ty)
1963            && self.shape.leq(&o.shape)
1964            && self.nullability.leq(&o.nullability)
1965            && self.alias.leq(&o.alias)
1966    }
1967}
1968
1969/// The Oracle's per-program-point state: every domain tracked per variable, plus
1970/// the may-alias relation. `value_of` assembles the product fact on demand.
1971#[derive(Clone)]
1972pub(crate) struct RichAbstractState {
1973    intervals: AbstractState,
1974    types: HashMap<Symbol, TypeAbstraction>,
1975    shapes: HashMap<Symbol, CollectionShape>,
1976    nullability: HashMap<Symbol, Nullability>,
1977    aliases: AliasGraph,
1978    /// Variables PROVEN collection-kinded (created as collections). Kind
1979    /// is binding-level: pushes, pops and callees resize a collection but
1980    /// can never rebind it to a scalar — only reassignment removes a
1981    /// variable here. Size widening (shapes → Top) does NOT erase kind.
1982    coll_vars: std::collections::HashSet<Symbol>,
1983    /// DECLARED primitive return types per function — calls produce facts.
1984    fn_returns: std::rc::Rc<HashMap<Symbol, TypeTag>>,
1985    /// What any call in this program may write — the names a `Call` makes unknown.
1986    callee_globals: std::rc::Rc<CalleeGlobals>,
1987    /// Symbolic length LOWER bound per collection: `arr -> (n, off)` means
1988    /// `length(arr) >= n + off`, where `n` is a program variable. Established
1989    /// by a counted build loop (`while c < n: push to arr` once per iteration
1990    /// from an empty array — the standard allocation-size fact) and consumed
1991    /// by the relational bounds recognizer to prove `item i of arr` reads
1992    /// whose guard bounds `i` by the SAME variable `n`. Invalidated when the
1993    /// array is resized/rebound or when `n` is reassigned.
1994    length_def: HashMap<Symbol, (Symbol, i64)>,
1995    /// Function-PARAMETER collections (`arr: Seq of Int`): their length is
1996    /// fundamentally unknown, so they are the targets of SPECULATIVE
1997    /// region-entry hoisting (a locally-built array, by contrast, has a
1998    /// statically determinable length and is left to the static path).
1999    param_colls: std::collections::HashSet<Symbol>,
2000    /// Affine scalar DEFINITIONS: `X -> linear(E)` for a binding `Let X be E`
2001    /// whose value is affine over other variables (`Let cols be capacity + 1`).
2002    /// Fed to the kernel LIA prover as an EQUALITY `X = E` so a multi-variable
2003    /// bounds proof can relate a length variable to a loop bound (knapsack:
2004    /// `length(prev) = cols = capacity + 1`, guard `w <= capacity`). Invalidated
2005    /// when `X` or any variable in `E` is reassigned.
2006    scalar_def: HashMap<Symbol, super::affine::LinExpr>,
2007    /// SYMBOLIC scalar UPPER bound: `X -> L` means `X <= L` for a linear `L`
2008    /// over program variables. The variable-divisor sibling of the concrete
2009    /// interval upper — `Let neighbor be (...) % n` records `neighbor <= n - 1`,
2010    /// which no concrete `Interval` can hold (`n` is symbolic). Flows into the
2011    /// per-collection element upper through a store and back out through a read,
2012    /// then feeds the Fourier–Motzkin prover so `dist[u]` (u an element of a
2013    /// `% n`-filled array) proves in bounds. Invalidated like `scalar_def`.
2014    scalar_upper: HashMap<Symbol, super::affine::LinExpr>,
2015    /// SYMBOLIC per-collection ELEMENT upper bound: `A -> L` means EVERY element
2016    /// of `A` is `<= L`. Absent means ⊤ (unknown) when the concrete element
2017    /// interval is non-⊥, or ⊥ (fresh, no elements) when it is — the concrete
2018    /// `is_bottom()` disambiguates, exactly as the fixpoint's freshness test
2019    /// does. Seeded by stores/pushes whose value carries a `scalar_upper`, read
2020    /// back as a `scalar_upper` on `Let u be item _ of A`.
2021    elem_upper: HashMap<Symbol, super::affine::LinExpr>,
2022    /// Per-collection ELEMENT TYPE: `A -> T` means EVERY element of `A` is of
2023    /// scalar type `T` (the join over every value written into `A`). The type
2024    /// sibling of the concrete `elem` interval — seeded by the first
2025    /// store/push, joined on every later one, and read back as the proven type
2026    /// of `item k of A`. Lets a read of a homogeneously-typed collection carry
2027    /// a concrete scalar kind (`item k of dp ∈ Int` when `dp` is built only
2028    /// from `Int` writes), which the magic-reciprocal modulo gate needs to fire
2029    /// on `(... + ...) % c`. Absent means ⊤ (unknown) when the concrete `elem`
2030    /// interval is non-⊥, or ⊥ (fresh, no elements) when it is — the same
2031    /// `is_bottom()` freshness test the `elem`/`elem_upper` siblings use.
2032    elem_type: HashMap<Symbol, TypeAbstraction>,
2033    /// SYMBOLIC scalar LOWER bound — the mirror of `scalar_upper`, the relation
2034    /// that makes `dist[u+1]`'s LOWER half (`u >= 0`) provable when `u`'s raw
2035    /// interval is widened to ⊤ (a loop-local read variable's undefined entry
2036    /// value floods the fixpoint join). Captured at bind time from the source's
2037    /// proven lower — an element read of `A` carries `A`'s concrete element
2038    /// interval lower; a `(...) % n` of a non-negative dividend carries `0`.
2039    /// Sound for a MUTATED scalar (re-established by its in-body `Let`).
2040    scalar_lower: HashMap<Symbol, super::affine::LinExpr>,
2041    /// AOT-only: this state belongs to a function body analyzed for the
2042    /// `largo build` codegen, which emits the recursive-1-based-partition entry
2043    /// precondition guard (`assert!(lo >= 1 && hi <= len)`). Only then is it
2044    /// sound to (a) seed that precondition as a fact and (b) propagate a
2045    /// `length_def` across an alias bind — both rest on a runtime check the VM/
2046    /// JIT bytecode path does NOT emit, so they stay OFF for it. Set by
2047    /// [`oracle_analyze_with_entry_guards`]; copied by `clone()` into branch
2048    /// states, so it survives the whole body walk.
2049    aot_entry_guard: bool,
2050    /// The entry-guarded function's precondition lower bounds `(param, lb)` — `lo>=1`,
2051    /// `hi>=1`, which `codegen::entry_guard`'s `assert!` enforces at runtime. Carried
2052    /// ON THE STATE (like `aot_entry_guard`) so it reaches EVERY proof context: the
2053    /// loop fixpoint's `inside = st.clone()` copies it into the loop's record-state,
2054    /// where a thread-local was empty. Injected into every affine proof system; sound
2055    /// because the runtime guard aborts if a caller violates the precondition.
2056    entry_guard_lowers: Vec<(Symbol, i64)>,
2057    /// The affine equalities among the function's integers and sequence lengths here ([`super::karr`]).
2058    karr: super::karr::AffineSpace,
2059    /// Names bound to a sequence (`a new Seq`, a list literal, a sequence parameter, a copy of one, or a call that
2060    /// returns one as long as its argument): the collections `karr` tracks a length for, since a store into a
2061    /// sequence keeps its length and a store into a map may not.
2062    seq_vars: std::collections::HashSet<Symbol>,
2063    /// The type names `a new …` builds a sequence from, when the walk has an interner.
2064    seq_types: std::rc::Rc<std::collections::HashSet<Symbol>>,
2065    /// Functions that return a sequence as long as the one handed to them at a parameter position
2066    /// ([`length_preserving_functions`]).
2067    len_summaries: std::rc::Rc<HashMap<Symbol, usize>>,
2068}
2069
2070impl RichAbstractState {
2071    fn new() -> Self {
2072        RichAbstractState {
2073            intervals: AbstractState::new(),
2074            types: HashMap::new(),
2075            shapes: HashMap::new(),
2076            nullability: HashMap::new(),
2077            aliases: AliasGraph::new(),
2078            coll_vars: std::collections::HashSet::new(),
2079            fn_returns: std::rc::Rc::new(HashMap::new()),
2080            callee_globals: std::rc::Rc::new(CalleeGlobals::default()),
2081            length_def: HashMap::new(),
2082            param_colls: std::collections::HashSet::new(),
2083            scalar_def: HashMap::new(),
2084            scalar_upper: HashMap::new(),
2085            elem_upper: HashMap::new(),
2086            elem_type: HashMap::new(),
2087            scalar_lower: HashMap::new(),
2088            aot_entry_guard: false,
2089            entry_guard_lowers: Vec::new(),
2090            karr: super::karr::AffineSpace::top(),
2091            seq_vars: std::collections::HashSet::new(),
2092            seq_types: std::rc::Rc::new(std::collections::HashSet::new()),
2093            len_summaries: std::rc::Rc::new(HashMap::new()),
2094        }
2095    }
2096
2097    /// Every equality through `sym`'s value or its length is gone.
2098    fn karr_forget(&mut self, sym: Symbol) {
2099        self.karr.forget(super::affine::var_index(sym));
2100        self.karr.forget(super::affine::len_index(sym));
2101    }
2102
2103    /// The collection `c` may have changed length: what any other name for its allocation says about its own length
2104    /// is gone. The names for one allocation are the alias graph's linked names (as the length intervals take them,
2105    /// [`rich_grow`]); a resize through a handle of unknown provenance reaches every other such handle too.
2106    fn karr_resized(&mut self, c: Symbol) {
2107        let names = self.aliases.may_alias(c);
2108        let tainted = &self.aliases.tainted;
2109        let unknown = tainted.contains(&c);
2110        let stale: Vec<i64> = self
2111            .karr
2112            .tracked()
2113            .iter()
2114            .copied()
2115            .filter(|&d| {
2116                super::affine::len_owner(d).is_some_and(|a| {
2117                    a != c && (names.contains(&a) || (unknown && tainted.contains(&a)))
2118                })
2119            })
2120            .collect();
2121        for d in stale {
2122            self.karr.forget(d);
2123        }
2124    }
2125
2126    /// `sym` may hold anything now, a collection of any length sharing any allocation it shared: nothing `karr`
2127    /// says through it holds.
2128    fn karr_unknown(&mut self, sym: Symbol) {
2129        self.karr_resized(sym);
2130        self.karr_forget(sym);
2131        self.seq_vars.remove(&sym);
2132    }
2133
2134    /// The product fact known about `sym` at this point.
2135    pub(crate) fn value_of(&self, sym: Symbol) -> AbstractValue {
2136        let mut others = self.aliases.may_alias(sym);
2137        others.remove(&sym);
2138        let alias = if others.is_empty() {
2139            AliasInfo::Unique
2140        } else {
2141            AliasInfo::MayAlias(others)
2142        };
2143        AbstractValue {
2144            interval: self.intervals.get_var(&sym),
2145            ty: self
2146                .types
2147                .get(&sym)
2148                .cloned()
2149                .unwrap_or(TypeAbstraction::Top),
2150            shape: self
2151                .shapes
2152                .get(&sym)
2153                .cloned()
2154                .unwrap_or(CollectionShape::Top),
2155            nullability: self
2156                .nullability
2157                .get(&sym)
2158                .cloned()
2159                .unwrap_or(Nullability::Maybe),
2160            alias,
2161        }
2162    }
2163
2164    /// Forget every scalar fact about `sym` (used when its value is overwritten
2165    /// or produced by an operation we do not model). Rebinding can change
2166    /// KIND too, so the collection proof drops with it.
2167    /// A call ran: every global some callee assigns is unknown now (everything is, if a callee holds
2168    /// raw foreign code).
2169    fn forget_callee_globals(&mut self) {
2170        let globals = self.callee_globals.clone();
2171        if globals.opaque {
2172            self.forget_everything();
2173            return;
2174        }
2175        for g in &globals.symbols {
2176            self.karr_unknown(*g);
2177            self.invalidate_var(*g);
2178            self.aliases.unlink(*g);
2179            self.intervals.set_length(*g, Interval::non_negative());
2180            self.length_def.remove(g);
2181        }
2182    }
2183
2184    /// Raw foreign code ran: no fact about any name survives. Declared function return types, the
2185    /// parameter-collection set, and the entry-guard mode are structural and stay.
2186    fn forget_everything(&mut self) {
2187        self.intervals.forget_all();
2188        self.types.clear();
2189        self.shapes.clear();
2190        self.nullability.clear();
2191        self.aliases = AliasGraph::new();
2192        self.coll_vars.clear();
2193        self.length_def.clear();
2194        self.scalar_def.clear();
2195        self.scalar_upper.clear();
2196        self.elem_upper.clear();
2197        self.elem_type.clear();
2198        self.scalar_lower.clear();
2199        self.entry_guard_lowers.clear();
2200        self.karr = super::karr::AffineSpace::top();
2201        self.seq_vars.clear();
2202    }
2203
2204    /// Nothing this state says about the names in `written` holds any longer: each may hold anything, alias
2205    /// anything, have any length, and no affine definition names or mentions it.
2206    fn forget_written(&mut self, written: &[Symbol]) {
2207        for &m in written {
2208            self.karr_unknown(m);
2209            self.invalidate_var(m);
2210            self.aliases.unlink(m);
2211            self.intervals.set_length(m, Interval::non_negative());
2212            self.length_def.remove(&m);
2213            let mi = m.index() as i64;
2214            self.scalar_def.remove(&m);
2215            self.scalar_def
2216                .retain(|_, e| !e.coefficients.contains_key(&mi));
2217        }
2218    }
2219
2220    fn invalidate_var(&mut self, sym: Symbol) {
2221        self.karr_forget(sym);
2222        self.seq_vars.remove(&sym);
2223        self.intervals.set_var(sym, Interval::top());
2224        self.types.insert(sym, TypeAbstraction::Top);
2225        self.shapes.insert(sym, CollectionShape::Top);
2226        self.nullability.insert(sym, Nullability::Maybe);
2227        self.coll_vars.remove(&sym);
2228        self.intervals.clear_elem(&sym);
2229        let si = sym.index() as i64;
2230        self.scalar_upper.remove(&sym);
2231        self.scalar_upper
2232            .retain(|_, e| !e.coefficients.contains_key(&si));
2233        self.elem_upper.remove(&sym);
2234        self.elem_upper
2235            .retain(|_, e| !e.coefficients.contains_key(&si));
2236        self.elem_type.remove(&sym);
2237        self.scalar_lower.remove(&sym);
2238        self.scalar_lower
2239            .retain(|_, e| !e.coefficients.contains_key(&si));
2240    }
2241}
2242
2243/// Run the Oracle's rich abstract interpretation, returning the (unchanged)
2244/// statements together with the per-variable abstract facts.
2245/// The scalar kinds downstream consumers (typed bytecode, JIT guard
2246/// elision) act on.
2247#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2248pub enum ScalarKind {
2249    Int,
2250    Float,
2251    Bool,
2252    Text,
2253}
2254
2255/// A variable's program-wide PROVEN facts — the statically-verified summary the
2256/// debugger shows beside its live value (distinct from the dynamic, observed-this-run
2257/// invariants). All fields are sound over-approximations: present ⇒ proven.
2258#[derive(Clone, Debug, Default, PartialEq)]
2259pub struct VarProvenFacts {
2260    /// Proven scalar type, if concrete across the program.
2261    pub scalar: Option<ScalarKind>,
2262    /// Proven finite integer range `[lo, hi]` (the value was in it at every occurrence).
2263    pub int_range: Option<(i64, i64)>,
2264    /// Proven non-negative everywhere (even if unbounded above).
2265    pub nonneg: bool,
2266}
2267
2268/// EXODIA Phase 1's DELIVERY layer: a product fact for every expression
2269/// occurrence at its program point, keyed by ARENA ADDRESS (stable for the
2270/// analyzed snapshot — record facts immediately before consuming them, and
2271/// never across a pass that re-allocates expressions). Shared subtrees that
2272/// appear at several program points JOIN their facts (sound; precision is
2273/// lost exactly where sharing occurs).
2274#[derive(Default)]
2275pub struct OracleFacts {
2276    /// How many loop fixpoints are open on the current walk — [`rich_walk_loop`] bounds the nesting
2277    /// at which a loop still gets its own fixpoint.
2278    loop_depth: usize,
2279    exprs: HashMap<usize, AbstractValue>,
2280    /// Length interval of the collection an Identifier expression denotes,
2281    /// at that occurrence — the bounds-elision query's other half.
2282    lengths: HashMap<usize, Interval>,
2283    /// Identifier occurrences PROVEN collection-kinded (binding-level —
2284    /// kind survives growth and callees; only rebinding erases it).
2285    collections: std::collections::HashSet<usize>,
2286    /// Converged loop-invariant alias graphs, keyed by the While/Repeat
2287    /// statement's arena address. Borrow hoisting's distinctness queries
2288    /// read these; loops the fixpoint never converged on (or that run under
2289    /// concurrent blocks) have no entry and refuse.
2290    loop_aliases: HashMap<usize, AliasGraph>,
2291    /// When set, per-expression facts (`exprs`/`lengths`/`collections`) are
2292    /// NOT recorded, but state updates and `loop_aliases` snapshots still
2293    /// are. Used to walk Zone interiors for borrow hoisting's alias
2294    /// snapshots WITHOUT feeding new expr facts to the EXODIA VM/JIT region
2295    /// compiler — whose pinned-chain emitter assumes the oracle records
2296    /// nothing inside zones.
2297    suppress_exprs: bool,
2298    /// `index` sub-expression addresses of `item i of arr` reads PROVEN
2299    /// in bounds by RELATIONAL induction-variable reasoning (V8/LLVM SCEV
2300    /// style): a loop guard `i </<= length(arr)` with `i >= 1` and `arr`
2301    /// not resized in the body bounds the index by the array's length — a
2302    /// relation the interval domain cannot represent. `index_provably_in_
2303    /// bounds` consults this in addition to the interval check.
2304    relational_inbounds: std::collections::HashSet<usize>,
2305    /// `index` addresses proven in bounds only SPECULATIVELY — they rely on a
2306    /// region-entry runtime check (`hoist_descs`). Kept SEPARATE from
2307    /// `relational_inbounds` so the compiler elides them ONLY when it actually
2308    /// emits the matching `RegionBoundsGuard` (elision ⟺ guard ⟺ VM check).
2309    speculative_inbounds: std::collections::HashSet<usize>,
2310    /// Per-loop region-entry bounds hoists (V8 loop bound-check elimination),
2311    /// keyed by the `While`/`Repeat` statement's arena address. When a loop's
2312    /// array length cannot be proven statically (e.g. a function parameter),
2313    /// but the induction is monotone, the bound loop-invariant, and the array
2314    /// stable, the covered accesses are recorded in `relational_inbounds`
2315    /// (speculatively) and one descriptor here justifies them with a runtime
2316    /// check the bytecode compiler lowers to `RegionBoundsGuard`.
2317    hoist_descs: HashMap<usize, Vec<HoistDesc>>,
2318    /// Per-access POSITIVITY guards: an `index` (by `*const Expr`) elided only
2319    /// because a `% m` element bound `m - 1` closed the proof carries the
2320    /// divisors `m` whose `m >= 1` precondition the codegen must discharge with
2321    /// a (nonemptiness-guarded, invariant-hoisted) `assert!(m > 0)` at the
2322    /// access. Keeps the lenient symbolic element join sound for ALL inputs:
2323    /// `m <= 0` panics before the would-be out-of-bounds read instead of UB.
2324    positivity_guards: HashMap<usize, Vec<Symbol>>,
2325    /// `Map of Int to Int` locals declared `… with capacity CAP` whose capacity is
2326    /// an affine expression of program-INVARIANT variables — stored as a kernel
2327    /// `LinearExpr` so the dense-key bound proof can relate a key to it. Keyed by
2328    /// the map symbol. The invariance check (no capacity variable is ever
2329    /// reassigned) is what makes the stored expression equal the runtime
2330    /// allocation size at every key site. Populated once, before the loop walks.
2331    map_caps: HashMap<Symbol, super::affine::LinExpr>,
2332    /// `key` sub-expression addresses (insert/get/contains) PROVEN to satisfy
2333    /// `0 <= key <= capacity(map)` under the loop guards, mapped to the map they
2334    /// were proven against. The dense gate lowers a `Map of Int to Int` to a
2335    /// direct-addressed array iff EVERY one of its key sites appears here for it.
2336    dense_map_key_proven: HashMap<usize, Symbol>,
2337    /// `Map of Int to Int` locals whose SINGLE insert loop provably writes EVERY
2338    /// integer in a contiguous range `[A, B]` (unit-stride induction variable,
2339    /// unconditional `Set item iv of m`), keyed to that range as `(A, B)` kernel
2340    /// `LinearExpr`s. The precondition for presence elision: a key proven inside
2341    /// `[A, B]` was definitely inserted, so `get` can skip its presence check.
2342    map_insert_cover: HashMap<Symbol, (super::affine::LinExpr, super::affine::LinExpr)>,
2343    /// `key` addresses additionally PROVEN inside their map's fully-covered insert
2344    /// range `[A, B]` (so the key was definitely written). When every key site of
2345    /// a dense map is here, the map needs no presence bitset (`…NoPresence`).
2346    map_key_covered: HashMap<usize, Symbol>,
2347    /// The affine equalities ([`super::karr`]) holding where each index expression (by address) is evaluated,
2348    /// joined over every recorded visit: what relates a store's index to the lengths around it.
2349    karr_at: HashMap<usize, super::karr::AffineSpace>,
2350    /// While a function is walked for its length summary ([`length_preserving_functions`]): each `Return`
2351    /// statement's address, the name it returns, and the equalities where it returns.
2352    return_probe: Option<Vec<(usize, Option<Symbol>, super::karr::AffineSpace)>>,
2353}
2354
2355/// A region-entry bounds hoist in SYMBOL terms (the compiler maps to
2356/// registers): `length(array) >= bound + add_max` and `iv + add_min >= 1`.
2357#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2358pub struct HoistDesc {
2359    pub array: Symbol,
2360    pub bound: Symbol,
2361    pub iv: Symbol,
2362    pub add_max: i32,
2363    pub add_min: i32,
2364}
2365
2366impl OracleFacts {
2367    /// Region-entry bounds hoists for the loop at `loop_ptr` (the `While`/
2368    /// `Repeat` statement's arena address). The compiler lowers each to a
2369    /// `RegionBoundsGuard` at the loop head.
2370    pub fn hoist_descs_for(&self, loop_ptr: usize) -> &[HoistDesc] {
2371        self.hoist_descs
2372            .get(&loop_ptr)
2373            .map_or(&[], |v| v.as_slice())
2374    }
2375
2376    /// Is this `index` sub-expression proven in bounds only SPECULATIVELY
2377    /// (needs a region-entry guard)? The compiler elides it solely when it
2378    /// emitted that guard.
2379    pub fn index_is_speculative(&self, index: &Expr) -> bool {
2380        self.speculative_inbounds
2381            .contains(&(index as *const Expr as usize))
2382    }
2383
2384    fn record(&mut self, e: &Expr, av: AbstractValue) {
2385        if self.suppress_exprs {
2386            return;
2387        }
2388        let key = e as *const Expr as usize;
2389        match self.exprs.get_mut(&key) {
2390            None => {
2391                self.exprs.insert(key, av);
2392            }
2393            Some(prev) => *prev = prev.join(&av),
2394        }
2395    }
2396
2397    fn record_length(&mut self, e: &Expr, len: Interval) {
2398        if self.suppress_exprs {
2399            return;
2400        }
2401        let key = e as *const Expr as usize;
2402        match self.lengths.get_mut(&key) {
2403            None => {
2404                self.lengths.insert(key, len);
2405            }
2406            Some(prev) => *prev = prev.join(&len),
2407        }
2408    }
2409
2410    /// The proven scalar kind of this expression occurrence, if concrete.
2411    pub fn expr_scalar(&self, e: &Expr) -> Option<ScalarKind> {
2412        let av = self.exprs.get(&(e as *const Expr as usize))?;
2413        match &av.ty {
2414            TypeAbstraction::Concrete(TypeTag::Int) => Some(ScalarKind::Int),
2415            TypeAbstraction::Concrete(TypeTag::Float) => Some(ScalarKind::Float),
2416            TypeAbstraction::Concrete(TypeTag::Bool) => Some(ScalarKind::Bool),
2417            TypeAbstraction::Concrete(TypeTag::Text) => Some(ScalarKind::Text),
2418            _ => None,
2419        }
2420    }
2421
2422    /// The finite integer range proven for this occurrence, if both bounds
2423    /// are finite.
2424    pub fn expr_int_range(&self, e: &Expr) -> Option<(i64, i64)> {
2425        self.expr_int_range_addr(e as *const Expr as usize)
2426    }
2427
2428    /// Is this occurrence PROVEN non-negative — its abstract interval's LOWER
2429    /// bound is a finite `>= 0`? Unlike [`Self::expr_int_range`] this ignores
2430    /// the upper bound, so it holds even when the value's magnitude is unbounded
2431    /// above (the LCG `seed * 1103515245 + 12345` dividend: both factors
2432    /// non-negative, so `lo = 0`, but the product's `hi` may saturate). This is
2433    /// the soundness gate for `x % 2^k → x & (2^k - 1)`, whose identity needs
2434    /// only `x >= 0`, not a finite ceiling.
2435    pub fn expr_proven_nonneg(&self, e: &Expr) -> bool {
2436        self.expr_proven_at_least(e, 0)
2437    }
2438
2439    /// Is this occurrence's proven LOWER bound a finite `>= k`, whatever its upper bound? A 1-based index proven
2440    /// `>= 1` names its item from the front.
2441    pub fn expr_proven_at_least(&self, e: &Expr, k: i64) -> bool {
2442        match self.exprs.get(&(e as *const Expr as usize)) {
2443            Some(av) => matches!(av.interval.lo, Bound::Finite(v) if v >= k),
2444            None => false,
2445        }
2446    }
2447
2448    /// As [`Self::expr_int_range`], keyed by the expression's arena address (the
2449    /// form the i32-narrowing gate collects its key/value sites in).
2450    pub fn expr_int_range_addr(&self, addr: usize) -> Option<(i64, i64)> {
2451        let av = self.exprs.get(&addr)?;
2452        match (&av.interval.lo, &av.interval.hi) {
2453            (Bound::Finite(lo), Bound::Finite(hi)) if lo <= hi => Some((*lo, *hi)),
2454            _ => None,
2455        }
2456    }
2457
2458    /// **Debugger-only** by-name rollup: walk `stmts` and JOIN every `Identifier(sym)`
2459    /// occurrence's already-recorded abstract value into one proven summary per variable.
2460    /// Sound by construction (joining widens), so a returned `int_range` of `[0, 9]` means
2461    /// the variable was within it at *every* use — a program-wide proven invariant.
2462    ///
2463    /// This re-reads the facts that the production walk already computed; it adds NOTHING
2464    /// to `record_expr`/`oracle_analyze`, so it is **zero cost** unless the debugger calls
2465    /// it (no production path does). Reused from the same module so it can read `exprs`.
2466    pub fn summarize_variables(&self, stmts: &[Stmt]) -> Vec<(Symbol, VarProvenFacts)> {
2467        let mut by_sym: HashMap<Symbol, AbstractValue> = HashMap::new();
2468        collect_idents_block(stmts, &mut |sym, addr| {
2469            if let Some(av) = self.exprs.get(&addr) {
2470                match by_sym.get_mut(&sym) {
2471                    None => {
2472                        by_sym.insert(sym, av.clone());
2473                    }
2474                    Some(prev) => *prev = prev.join(av),
2475                }
2476            }
2477        });
2478        by_sym
2479            .into_iter()
2480            .map(|(sym, av)| {
2481                let int_range = match (&av.interval.lo, &av.interval.hi) {
2482                    (Bound::Finite(lo), Bound::Finite(hi)) if lo <= hi => Some((*lo, *hi)),
2483                    _ => None,
2484                };
2485                let scalar = match &av.ty {
2486                    TypeAbstraction::Concrete(TypeTag::Int) => Some(ScalarKind::Int),
2487                    TypeAbstraction::Concrete(TypeTag::Float) => Some(ScalarKind::Float),
2488                    TypeAbstraction::Concrete(TypeTag::Bool) => Some(ScalarKind::Bool),
2489                    TypeAbstraction::Concrete(TypeTag::Text) => Some(ScalarKind::Text),
2490                    _ => None,
2491                };
2492                let nonneg = matches!(av.interval.lo, Bound::Finite(v) if v >= 0);
2493                (
2494                    sym,
2495                    VarProvenFacts {
2496                        scalar,
2497                        int_range,
2498                        nonneg,
2499                    },
2500                )
2501            })
2502            .collect()
2503    }
2504
2505    /// Does this `Map of Int to Int` have a recorded invariant affine capacity
2506    /// (the precondition for any dense-key proof against it)?
2507    pub fn has_dense_map_capacity(&self, map: Symbol) -> bool {
2508        self.map_caps.contains_key(&map)
2509    }
2510
2511    /// The recorded invariant affine capacity for a dense map — the bound every
2512    /// key was proven `<= cap` against. Codegen renders it (see [`lin_to_rust`])
2513    /// to size the direct-addressed array `with_bounds(0, cap + 1)`.
2514    pub fn map_cap_lin(&self, map: Symbol) -> Option<&super::affine::LinExpr> {
2515        self.map_caps.get(&map)
2516    }
2517
2518    /// Was this key occurrence PROVEN within `[0, capacity(map)]` (so a
2519    /// direct-addressed array of `capacity + 1` slots indexes it safely)?
2520    pub fn dense_map_key_proven(&self, key: &Expr, map: Symbol) -> bool {
2521        self.dense_map_key_proven_addr(key as *const Expr as usize, map)
2522    }
2523
2524    /// As [`Self::dense_map_key_proven`], keyed by the expression's arena address
2525    /// directly (the form the dense gate collects its key sites in).
2526    pub fn dense_map_key_proven_addr(&self, key_addr: usize, map: Symbol) -> bool {
2527        self.dense_map_key_proven.get(&key_addr) == Some(&map)
2528    }
2529
2530    /// Does this dense map's single insert loop provably cover a contiguous range
2531    /// fully (the structural precondition for presence elision)?
2532    pub fn dense_map_has_full_coverage(&self, map: Symbol) -> bool {
2533        self.map_insert_cover.contains_key(&map)
2534    }
2535
2536    /// Was this key occurrence PROVEN inside its map's fully-covered insert range
2537    /// (so the key was definitely written, and `get` may skip the presence bit)?
2538    pub fn dense_key_covered_addr(&self, key_addr: usize, map: Symbol) -> bool {
2539        self.map_key_covered.get(&key_addr) == Some(&map)
2540    }
2541
2542    /// Is this occurrence PROVEN collection-kinded? Seeded at collection
2543    /// creations and preserved through growth, shrinkage and calls —
2544    /// kind is a binding-level fact only rebinding can erase.
2545    pub fn expr_is_tracked_collection(&self, e: &Expr) -> bool {
2546        self.collections.contains(&(e as *const Expr as usize))
2547    }
2548
2549    /// PROOF that two handles denote distinct allocations at every iteration
2550    /// of `loop_stmt` (a While/Repeat analyzed to convergence). This is the
2551    /// soundness gate for borrow hoisting: `true` only when both handles
2552    /// have fully tracked provenance and their may-alias components do not
2553    /// meet at the loop invariant — including loop-CARRIED edges. Anything
2554    /// else (tainted handle, non-converged loop, unknown statement,
2555    /// concurrent context) refuses.
2556    pub fn loop_handles_definitely_distinct(&self, loop_stmt: &Stmt, a: Symbol, b: Symbol) -> bool {
2557        let key = loop_stmt as *const Stmt as usize;
2558        match self.loop_aliases.get(&key) {
2559            Some(g) => g.definitely_distinct(a, b),
2560            None => false,
2561        }
2562    }
2563
2564    /// Finite proven LENGTH bounds for this collection occurrence.
2565    pub fn expr_len_range(&self, e: &Expr) -> Option<(i64, i64)> {
2566        let iv = self.lengths.get(&(e as *const Expr as usize))?;
2567        match (&iv.lo, &iv.hi) {
2568            (Bound::Finite(lo), Bound::Finite(hi)) if lo <= hi => Some((*lo, *hi)),
2569            _ => None,
2570        }
2571    }
2572
2573    /// True when `index` is proven in bounds RELATIONALLY (multi-variable LIA /
2574    /// SCEV / entry-guard), as opposed to a plain interval bound. The swap
2575    /// peephole uses this to keep partition swaps (quicksort's `i`/`j`, related
2576    /// by `i <= j < hi <= len`) as the unchecked indexed form instead of
2577    /// downgrading them to a bounds-checked `.swap()`; literal-index swaps
2578    /// (interval-proven) still become `.swap()`/`__swap_tmp`.
2579    pub fn index_proven_relational(&self, index: &Expr) -> bool {
2580        self.relational_inbounds
2581            .contains(&(index as *const Expr as usize))
2582    }
2583
2584    /// The guard-elision query (EXODIA 1.3): is `index` PROVABLY within the
2585    /// 1-based bounds of `collection` at this program point? True only when
2586    /// the index interval sits inside [1, len.lo].
2587    pub fn index_provably_in_bounds(&self, collection: &Expr, index: &Expr) -> bool {
2588        // Relational induction-variable bound (SCEV-style): the loop guard
2589        // already proved `1 <= index <= length(collection)` for this exact
2590        // read. Intervals alone cannot express it.
2591        if self
2592            .relational_inbounds
2593            .contains(&(index as *const Expr as usize))
2594        {
2595            return true;
2596        }
2597        // Non-relational interval check: a concrete index interval inside
2598        // `[1, proven-minimum-length]`.
2599        let Some(len) = self.lengths.get(&(collection as *const Expr as usize)) else {
2600            return false;
2601        };
2602        let Some((ilo, ihi)) = self.expr_int_range(index) else {
2603            return false;
2604        };
2605        let len_lo = match len.lo {
2606            Bound::Finite(v) => v,
2607            _ => return false,
2608        };
2609        ilo >= 1 && ihi <= len_lo
2610    }
2611
2612    /// The `% m` divisors whose `m >= 1` precondition an elision of this exact
2613    /// `index` relied on (empty for a purely affine/interval elision). Codegen
2614    /// emits `assert!(m > 0)` for each at the access, discharging the symbolic
2615    /// element bound's precondition so the elision is sound for every input.
2616    pub fn index_positivity_guards(&self, index: &Expr) -> &[Symbol] {
2617        self.positivity_guards
2618            .get(&(index as *const Expr as usize))
2619            .map_or(&[], |v| v.as_slice())
2620    }
2621
2622    /// Whether `index` names an item of `collection` on EVERY run: a construct of
2623    /// the compile proved it (`super::facts::Fact::InBounds`), or
2624    /// [`Self::index_provably_in_bounds`] holds with no precondition. The one
2625    /// question an access that nothing checks rests on.
2626    pub fn index_always_in_bounds(&self, collection: &Expr, index: &Expr) -> bool {
2627        super::facts::holds_expr(super::facts::Fact::InBounds, index)
2628            || (self.index_provably_in_bounds(collection, index)
2629                && self.index_positivity_guards(index).is_empty())
2630    }
2631}
2632
2633/// Record the equalities holding where the index expression `index` is evaluated, joined with any visit recorded
2634/// before.
2635fn record_karr(index: &Expr, st: &RichAbstractState, facts: &mut OracleFacts) {
2636    if facts.suppress_exprs {
2637        return;
2638    }
2639    let key = index as *const Expr as usize;
2640    match facts.karr_at.entry(key) {
2641        std::collections::hash_map::Entry::Occupied(mut e) => {
2642            let joined = e.get().join(&st.karr);
2643            e.insert(joined);
2644        }
2645        std::collections::hash_map::Entry::Vacant(v) => {
2646            v.insert(st.karr.clone());
2647        }
2648    }
2649}
2650
2651/// Compute a bottom-up product fact for `e` and every subexpression, at the
2652/// state `st` (the pre-state of the statement that contains it).
2653fn record_expr(e: &Expr, st: &RichAbstractState, facts: &mut OracleFacts) {
2654    use crate::ast::stmt::StringPart;
2655    match e {
2656        Expr::BinaryOp { left, right, .. }
2657        | Expr::Union { left, right }
2658        | Expr::Intersection { left, right }
2659        | Expr::Range {
2660            start: left,
2661            end: right,
2662        } => {
2663            record_expr(left, st, facts);
2664            record_expr(right, st, facts);
2665        }
2666        Expr::Not { operand } => record_expr(operand, st, facts),
2667        Expr::Call { args, .. } => {
2668            for a in args {
2669                record_expr(a, st, facts);
2670            }
2671        }
2672        Expr::CallExpr { callee, args } => {
2673            record_expr(callee, st, facts);
2674            for a in args {
2675                record_expr(a, st, facts);
2676            }
2677        }
2678        Expr::Index { collection, index } => {
2679            record_expr(collection, st, facts);
2680            record_expr(index, st, facts);
2681            record_karr(index, st, facts);
2682        }
2683        Expr::Slice {
2684            collection,
2685            start,
2686            end,
2687        } => {
2688            record_expr(collection, st, facts);
2689            record_expr(start, st, facts);
2690            record_expr(end, st, facts);
2691        }
2692        Expr::Copy { expr } => record_expr(expr, st, facts),
2693        Expr::Give { value } => record_expr(value, st, facts),
2694        Expr::Length { collection } => record_expr(collection, st, facts),
2695        Expr::Contains { collection, value } => {
2696            record_expr(collection, st, facts);
2697            record_expr(value, st, facts);
2698        }
2699        Expr::List(items) | Expr::Tuple(items) => {
2700            for i in items {
2701                record_expr(i, st, facts);
2702            }
2703        }
2704        Expr::FieldAccess { object, .. } => record_expr(object, st, facts),
2705        Expr::New { init_fields, .. } => {
2706            for (_, fe) in init_fields {
2707                record_expr(fe, st, facts);
2708            }
2709        }
2710        Expr::NewVariant { fields, .. } => {
2711            for (_, fe) in fields {
2712                record_expr(fe, st, facts);
2713            }
2714        }
2715        Expr::OptionSome { value } => record_expr(value, st, facts),
2716        Expr::WithCapacity { value, capacity } => {
2717            record_expr(value, st, facts);
2718            record_expr(capacity, st, facts);
2719        }
2720        Expr::InterpolatedString(parts) => {
2721            for p in parts {
2722                if let StringPart::Expr { value, .. } = p {
2723                    record_expr(value, st, facts);
2724                }
2725            }
2726        }
2727        _ => {}
2728    }
2729    let av = AbstractValue {
2730        interval: eval_expr(e, &st.intervals),
2731        ty: eval_type(e, &st.types, &st.fn_returns, &st.elem_type),
2732        shape: match e {
2733            Expr::Identifier(sym) => st.shapes.get(sym).cloned().unwrap_or(CollectionShape::Top),
2734            _ => CollectionShape::Top,
2735        },
2736        nullability: nullability_of_expr(e, st),
2737        alias: AliasInfo::top(),
2738    };
2739    facts.record(e, av);
2740    if let Expr::Identifier(sym) = e {
2741        facts.record_length(e, st.intervals.get_length(sym));
2742        if !facts.suppress_exprs && st.coll_vars.contains(sym) {
2743            facts.collections.insert(e as *const Expr as usize);
2744        }
2745    }
2746}
2747
2748/// **Debugger-only** traversal: invoke `f(sym, addr)` for every `Identifier(sym)`
2749/// occurrence in `stmts`, mirroring the production walk's coverage so the addresses
2750/// line up with the recorded `exprs`. Never called on a production compile path —
2751/// only [`OracleFacts::summarize_variables`] uses it. Incompleteness here would only
2752/// narrow the debugger's summary (still sound), never affect codegen.
2753fn collect_idents_block(stmts: &[Stmt], f: &mut dyn FnMut(Symbol, usize)) {
2754    for s in stmts {
2755        collect_idents_stmt(s, f);
2756    }
2757}
2758
2759fn collect_idents_stmt(stmt: &Stmt, f: &mut dyn FnMut(Symbol, usize)) {
2760    use crate::ast::stmt::ReadSource;
2761    // Direct expressions a statement holds (mirror `record_stmt_exprs`).
2762    match stmt {
2763        Stmt::Let { value, .. } | Stmt::Set { value, .. } => collect_idents_expr(value, f),
2764        Stmt::Return { value: Some(e) } => collect_idents_expr(e, f),
2765        Stmt::Call { args, .. } => {
2766            for a in args {
2767                collect_idents_expr(a, f);
2768            }
2769        }
2770        Stmt::If { cond, .. } | Stmt::While { cond, .. } => collect_idents_expr(cond, f),
2771        Stmt::Repeat { iterable, .. } => collect_idents_expr(iterable, f),
2772        Stmt::Show { object, .. } | Stmt::Give { object, .. } => collect_idents_expr(object, f),
2773        Stmt::Push { value, collection }
2774        | Stmt::Add { value, collection }
2775        | Stmt::Remove { value, collection } => {
2776            collect_idents_expr(value, f);
2777            collect_idents_expr(collection, f);
2778        }
2779        Stmt::SetIndex {
2780            collection,
2781            index,
2782            value,
2783        } => {
2784            collect_idents_expr(collection, f);
2785            collect_idents_expr(index, f);
2786            collect_idents_expr(value, f);
2787        }
2788        Stmt::SetField { object, value, .. } => {
2789            collect_idents_expr(object, f);
2790            collect_idents_expr(value, f);
2791        }
2792        Stmt::Inspect { target, .. } => collect_idents_expr(target, f),
2793        Stmt::RuntimeAssert { condition, .. } => collect_idents_expr(condition, f),
2794        Stmt::Sleep { milliseconds } => collect_idents_expr(milliseconds, f),
2795        Stmt::ReadFrom {
2796            source: ReadSource::File(p),
2797            ..
2798        } => collect_idents_expr(p, f),
2799        _ => {}
2800    }
2801    // Nested blocks (mirror the block recursion the production walk does).
2802    match stmt {
2803        Stmt::If {
2804            then_block,
2805            else_block,
2806            ..
2807        } => {
2808            collect_idents_block(then_block, f);
2809            if let Some(eb) = else_block {
2810                collect_idents_block(eb, f);
2811            }
2812        }
2813        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => collect_idents_block(body, f),
2814        Stmt::FunctionDef { body, .. } => collect_idents_block(body, f),
2815        Stmt::Inspect { arms, .. } => {
2816            for arm in arms {
2817                collect_idents_block(arm.body, f);
2818            }
2819        }
2820        Stmt::Zone { body, .. } => collect_idents_block(body, f),
2821        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => collect_idents_block(tasks, f),
2822        _ => {}
2823    }
2824}
2825
2826fn collect_idents_expr(e: &Expr, f: &mut dyn FnMut(Symbol, usize)) {
2827    use crate::ast::stmt::StringPart;
2828    if let Expr::Identifier(sym) = e {
2829        f(*sym, e as *const Expr as usize);
2830    }
2831    match e {
2832        Expr::BinaryOp { left, right, .. }
2833        | Expr::Union { left, right }
2834        | Expr::Intersection { left, right }
2835        | Expr::Range {
2836            start: left,
2837            end: right,
2838        } => {
2839            collect_idents_expr(left, f);
2840            collect_idents_expr(right, f);
2841        }
2842        Expr::Not { operand } => collect_idents_expr(operand, f),
2843        Expr::Call { args, .. } => {
2844            for a in args {
2845                collect_idents_expr(a, f);
2846            }
2847        }
2848        Expr::CallExpr { callee, args } => {
2849            collect_idents_expr(callee, f);
2850            for a in args {
2851                collect_idents_expr(a, f);
2852            }
2853        }
2854        Expr::Index { collection, index } => {
2855            collect_idents_expr(collection, f);
2856            collect_idents_expr(index, f);
2857        }
2858        Expr::Slice {
2859            collection,
2860            start,
2861            end,
2862        } => {
2863            collect_idents_expr(collection, f);
2864            collect_idents_expr(start, f);
2865            collect_idents_expr(end, f);
2866        }
2867        Expr::Copy { expr } => collect_idents_expr(expr, f),
2868        Expr::Give { value } => collect_idents_expr(value, f),
2869        Expr::Length { collection } => collect_idents_expr(collection, f),
2870        Expr::Contains { collection, value } => {
2871            collect_idents_expr(collection, f);
2872            collect_idents_expr(value, f);
2873        }
2874        Expr::List(items) | Expr::Tuple(items) => {
2875            for i in items {
2876                collect_idents_expr(i, f);
2877            }
2878        }
2879        Expr::FieldAccess { object, .. } => collect_idents_expr(object, f),
2880        Expr::New { init_fields, .. } => {
2881            for (_, fe) in init_fields {
2882                collect_idents_expr(fe, f);
2883            }
2884        }
2885        Expr::NewVariant { fields, .. } => {
2886            for (_, fe) in fields {
2887                collect_idents_expr(fe, f);
2888            }
2889        }
2890        Expr::OptionSome { value } => collect_idents_expr(value, f),
2891        Expr::WithCapacity { value, capacity } => {
2892            collect_idents_expr(value, f);
2893            collect_idents_expr(capacity, f);
2894        }
2895        Expr::InterpolatedString(parts) => {
2896            for p in parts {
2897                if let StringPart::Expr { value, .. } = p {
2898                    collect_idents_expr(value, f);
2899                }
2900            }
2901        }
2902        _ => {}
2903    }
2904}
2905
2906/// What a loop guard bounds an induction variable by.
2907enum IvBound {
2908    /// `length of arr`.
2909    LenOf(Symbol),
2910    /// A program variable `n` (related to an array length by a build-loop fact
2911    /// `length(arr) >= n + off`), optionally minus a provably-nonnegative
2912    /// amount: the guard is `iv <op> n - headroom_or_more`, so `iv` clears the
2913    /// length by at least `headroom` — extra room for a positive affine offset
2914    /// (e.g. `j <= n - 1 - i` lets `item (j + 1) of arr` stay in bounds).
2915    Var { var: Symbol, headroom: i64 },
2916}
2917
2918/// A loop guard `iv </<= bound` bounding the induction variable from above.
2919struct IvGuard {
2920    iv: Symbol,
2921    bound: IvBound,
2922    /// `true` for `<` (so `iv <= bound - 1`), `false` for `<=`.
2923    strict: bool,
2924    /// Proven lower bound of `iv` at the loop body (its 1-based start).
2925    iv_lo: i64,
2926}
2927
2928/// RELATIONAL induction-variable bound elimination (V8 TurboFan / LLVM SCEV).
2929///
2930/// The interval domain proves `iv ∈ [lo, …]` but cannot represent the
2931/// relation `iv <= length(arr)` a loop guard establishes between two
2932/// variables. This recognizer reconstructs it: from a guard `iv </<= B`
2933/// (where `B` is `length of arr` directly, or a variable `n` tied to the
2934/// array's length by a build-loop fact `length(arr) >= n + off`), every
2935/// in-body read `item E of arr` with `E = iv + k` affine in `iv` is proven
2936/// `1 <= E <= length(arr)` — exactly what V8/LLVM hoist. Each proven read's
2937/// `index` address is recorded so the bytecode compiler emits
2938/// `IndexUnchecked` and the JIT drops the bounds branch.
2939fn record_loop_index_bounds(
2940    cond: &Expr,
2941    body: &[Stmt],
2942    state: &RichAbstractState,
2943    facts: &mut OracleFacts,
2944) {
2945    let mut guards: Vec<IvGuard> = Vec::new();
2946    collect_iv_guards(cond, state, &mut guards);
2947    if guards.is_empty() {
2948        return;
2949    }
2950    // A call (a callee may resize) or any unmodeled statement could change a
2951    // length or alias an array — refuse the whole proof. Resizes of SPECIFIC
2952    // arrays are tolerated: those arrays start clobbered, so their own reads
2953    // stay checked, while a stable array read alongside them still elides.
2954    if !body_is_index_proof_safe(body) {
2955        return;
2956    }
2957    let mut clobbered: std::collections::HashSet<Symbol> = std::collections::HashSet::new();
2958    collect_resized_arrays(body, &mut clobbered);
2959    record_proven_reads(
2960        body,
2961        &guards,
2962        &state.length_def,
2963        &mut clobbered,
2964        facts,
2965        &state.callee_globals,
2966    );
2967}
2968
2969// ===================================================================
2970// GENERAL multi-variable bounds elision via the kernel LIA prover.
2971//
2972// Where the single-variable recognizer above proves `item (iv+k) of arr` and
2973// the interval check proves a constant index into a constant-length array,
2974// this proves ANY affine index `item E of arr` whose `1 <= E <= length(arr)`
2975// follows from the enclosing loop guard, the path guards on the way in, the
2976// loop-invariant scalar ranges (INCLUDING element bounds reached through
2977// `Let v be item k of B` — A2), the affine scalar definitions (`cols =
2978// capacity + 1`), and a symbolic length lower bound. Each `1 <= E` and
2979// `E <= length` obligation is discharged by `logicaffeine_kernel::lia`
2980// (Fourier–Motzkin) and recorded into `relational_inbounds`, shared with the
2981// single-var path and consumed by codegen and the VM. Knapsack's
2982// `prev[w-wi+1]` (guard `w <= capacity`, path guard `w >= wi`, `length(prev) =
2983// cols = capacity + 1`, element bound `wi ∈ [1,50]`) is the canonical case.
2984// ===================================================================
2985
2986/// The affine fact context threaded down a loop nest: the kernel constraints
2987/// in scope (loop and path guards, monotone-IV lower bounds) plus the symbols
2988/// they mention, so a proof can pull in those variables' interval bounds and
2989/// scalar definitions.
2990#[derive(Default, Clone)]
2991struct AffineFacts {
2992    constraints: Vec<super::affine::Constraint>,
2993    syms: Vec<Symbol>,
2994    /// The sequences a guard may read `length of` from: tracked sequences the loop neither resizes nor rebinds, so
2995    /// the length a guard reads at the loop head is the length at every point of the body.
2996    lengths: std::rc::Rc<HashSet<Symbol>>,
2997    /// The walk that proves accesses from the equalities recorded where they are evaluated
2998    /// ([`try_prove_affine_karr`]), which runs once the loop body's record pass has recorded them; the other proofs
2999    /// run on the walk before it.
3000    karr_pass: bool,
3001}
3002
3003fn record_affine_index_bounds(
3004    cond: &Expr,
3005    body: &[Stmt],
3006    state: &RichAbstractState,
3007    entry: &RichAbstractState,
3008    facts: &mut OracleFacts,
3009    karr_pass: bool,
3010) {
3011    if !body_is_index_proof_safe(body) {
3012        return;
3013    }
3014    let mut clobbered: std::collections::HashSet<Symbol> = std::collections::HashSet::new();
3015    collect_resized_arrays(body, &mut clobbered);
3016    let mutated: std::collections::HashSet<Symbol> =
3017        collect_mutations_in(body, &state.callee_globals)
3018            .into_iter()
3019            .collect();
3020    // The loop fixpoint merges `scalar_upper`/`scalar_lower` across the back-edge
3021    // but NOT `scalar_def`, so a mid-body `Let complement be target - x` is gone
3022    // by the record state. Re-establish the body's TOP-LEVEL affine definitions
3023    // (their RHS is straight-line before every later use, and the bound var is not
3024    // reassigned), so a key proof can follow the chain `complement -> target - x
3025    // -> x`'s element bounds`. Sound: each added equality holds at every use site.
3026    let state = {
3027        let mut st = state.clone();
3028        // The entry-guard precondition lowers (`lo>=1`,`hi>=1`) hold throughout the
3029        // entry-guarded function body, but the loop's record-state may not carry them
3030        // through the fixpoint — copy them from the loop-ENTRY state, which does.
3031        if st.entry_guard_lowers.is_empty() {
3032            st.entry_guard_lowers = entry.entry_guard_lowers.clone();
3033        }
3034        augment_body_scalar_defs(body, &mut st);
3035        st
3036    };
3037    let inits: HashMap<Symbol, i64> = HashMap::new();
3038    let mut amb = AffineFacts {
3039        lengths: std::rc::Rc::new(
3040            state
3041                .seq_vars
3042                .iter()
3043                .copied()
3044                .filter(|c| !clobbered.contains(c) && !mutated.contains(c))
3045                .collect(),
3046        ),
3047        karr_pass,
3048        ..AffineFacts::default()
3049    };
3050    affine_add_loop_guards(cond, body, &state, Some(entry), &inits, &mut amb);
3051    affine_walk(
3052        body, body, &state, &clobbered, &mutated, &amb, &inits, facts,
3053    );
3054}
3055
3056/// Re-establish the body's TOP-LEVEL affine scalar definitions into a proof
3057/// state. Only straight-line `Let v be <affine>` where `v` is not reassigned in
3058/// the body (so the equality holds at every later use in the iteration) and the
3059/// RHS is variable-bearing and non-self-referential — exactly the form the LIA
3060/// prover consumes. Conditional (nested-block) defs are skipped: their equality
3061/// is not unconditional. Never overwrites an existing `scalar_def`.
3062fn augment_body_scalar_defs(body: &[Stmt], st: &mut RichAbstractState) {
3063    // Scalars reassigned via `Set` anywhere in the body: a def naming any of them
3064    // (as the bound var OR in its RHS) is not a stable iteration invariant.
3065    let reassigned = reassigned_scalars(body, &st.callee_globals);
3066    // Only a single, unshadowed top-level `Let` has an unambiguous definition.
3067    let mut let_count: HashMap<Symbol, u32> = HashMap::new();
3068    for s in body {
3069        if let Stmt::Let { var, .. } = s {
3070            *let_count.entry(*var).or_insert(0) += 1;
3071        }
3072    }
3073    for s in body {
3074        if let Stmt::Let { var, value, .. } = s {
3075            if reassigned.contains(var)
3076                || let_count.get(var) != Some(&1)
3077                || st.scalar_def.contains_key(var)
3078            {
3079                continue;
3080            }
3081            if let Some(e) = super::affine::lin_of(value) {
3082                // Every RHS variable must be single-assignment within the body
3083                // (not `Set`-reassigned and not re-`Let`/shadowed) so its value is
3084                // fixed for the iteration — then `var = E` holds at every later use.
3085                // An outer variable (absent from `let_count`) is stable unless it is
3086                // reassigned in the body.
3087                let rhs_stable = e.coefficients.keys().all(|&i| {
3088                    let s = Symbol::from_index(i as usize);
3089                    !reassigned.contains(&s) && let_count.get(&s).map_or(true, |&c| c <= 1)
3090                });
3091                if rhs_stable
3092                    && !e.coefficients.is_empty()
3093                    && !e.coefficients.contains_key(&(var.index() as i64))
3094                {
3095                    st.scalar_def.insert(*var, e);
3096                }
3097            }
3098        }
3099    }
3100}
3101
3102/// Every scalar `body` may REASSIGN (`Set`, `Swap`, a global some callee it calls assigns) — the
3103/// names whose body-local definitions are not stable iteration invariants. After foreign code every
3104/// name the body binds or mentions is suspect.
3105fn reassigned_scalars(body: &[Stmt], globals: &CalleeGlobals) -> std::collections::HashSet<Symbol> {
3106    let writes = WriteSet::of_block(body).with_callee_globals(globals);
3107    if writes.is_opaque() {
3108        return collect_mutations_in(body, globals).into_iter().collect();
3109    }
3110    writes.assigned().clone()
3111}
3112
3113/// `a <op> b` (optionally negated) as a kernel constraint, when both sides are
3114/// affine.
3115fn affine_cmp(
3116    op: BinaryOpKind,
3117    a: &Expr,
3118    b: &Expr,
3119    negate: bool,
3120    lengths: &HashSet<Symbol>,
3121) -> Option<super::affine::Constraint> {
3122    use super::affine::{ge, gt, le, lin_of_with_lengths, lt};
3123    let fixed = |c: Symbol| lengths.contains(&c);
3124    let (la, lb) = (
3125        lin_of_with_lengths(a, &fixed)?,
3126        lin_of_with_lengths(b, &fixed)?,
3127    );
3128    Some(match (op, negate) {
3129        (BinaryOpKind::Lt, false) | (BinaryOpKind::GtEq, true) => lt(&la, &lb),
3130        (BinaryOpKind::LtEq, false) | (BinaryOpKind::Gt, true) => le(&la, &lb),
3131        (BinaryOpKind::Gt, false) | (BinaryOpKind::LtEq, true) => gt(&la, &lb),
3132        (BinaryOpKind::GtEq, false) | (BinaryOpKind::Lt, true) => ge(&la, &lb),
3133        _ => return None,
3134    })
3135}
3136
3137/// Add a comparison (and the symbols it mentions) to a fact set, descending
3138/// through `and`. A disjunctive (`or`) guard cannot be soundly negated
3139/// termwise, so a negated `or`/anything non-comparison is dropped.
3140fn affine_add_cmp(cond: &Expr, negate: bool, out: &mut AffineFacts) {
3141    match cond {
3142        Expr::BinaryOp {
3143            op: BinaryOpKind::And,
3144            left,
3145            right,
3146        } if !negate => {
3147            affine_add_cmp(left, false, out);
3148            affine_add_cmp(right, false, out);
3149        }
3150        Expr::BinaryOp {
3151            op: op @ (BinaryOpKind::Lt | BinaryOpKind::LtEq | BinaryOpKind::Gt | BinaryOpKind::GtEq),
3152            left,
3153            right,
3154        } => {
3155            if let Some(c) = affine_cmp(*op, left, right, negate, &out.lengths) {
3156                out.constraints.push(c);
3157                affine_collect_syms(left, &mut out.syms);
3158                affine_collect_syms(right, &mut out.syms);
3159            }
3160        }
3161        _ => {}
3162    }
3163}
3164
3165/// Collect the identifier symbols of an affine-shaped expression.
3166fn affine_collect_syms(e: &Expr, out: &mut Vec<Symbol>) {
3167    match e {
3168        Expr::Identifier(s) => {
3169            if !out.contains(s) {
3170                out.push(*s);
3171            }
3172        }
3173        Expr::BinaryOp { left, right, .. } => {
3174            affine_collect_syms(left, out);
3175            affine_collect_syms(right, out);
3176        }
3177        _ => {}
3178    }
3179}
3180
3181/// A write `Set iv to value` keeps `iv >= lo` (given the induction hypothesis
3182/// `iv >= lo` before it): an increment by a non-negative literal, a literal
3183/// `>= lo`, or assignment from a LOOP-INVARIANT variable whose interval lower
3184/// is `>= lo`. The loop-invariant requirement makes `state`'s interval for that
3185/// variable a sound bound (a body-mutated source could differ mid-iteration).
3186fn write_keeps_ge(
3187    value: &Expr,
3188    iv: Symbol,
3189    lo: i64,
3190    state: &RichAbstractState,
3191    mutated: &std::collections::HashSet<Symbol>,
3192) -> bool {
3193    match value {
3194        Expr::BinaryOp {
3195            op: BinaryOpKind::Add,
3196            left,
3197            right,
3198        } => {
3199            let is_iv = |e: &&Expr| matches!(e, Expr::Identifier(s) if *s == iv);
3200            let nonneg = |e: &&Expr| matches!(e, Expr::Literal(Literal::Number(n)) if *n >= 0);
3201            (is_iv(&left) && nonneg(&right)) || (nonneg(&left) && is_iv(&right))
3202        }
3203        Expr::Literal(Literal::Number(n)) => *n >= lo,
3204        Expr::Identifier(s) if !mutated.contains(s) => {
3205            matches!(state.intervals.get_var(s).lo, Bound::Finite(l) if l >= lo)
3206        }
3207        _ => false,
3208    }
3209}
3210
3211/// A SOUND lower bound for a loop variable throughout the body: its entry value
3212/// `lo`, provided every write to it keeps it `>= lo` (induction). The entry
3213/// value comes from an explicit init `Let j be 0` in the ENCLOSING body
3214/// (`inits`) when available — essential for a NESTED loop whose counter is
3215/// reset each outer iteration (so the outer state widens it to top) — else the
3216/// loop-invariant state interval. More general than pure monotonicity: it
3217/// survives the `Set j to needleLen` of a break loop (needleLen loop-invariant,
3218/// `>= 0`), where a strict increment-only check gives up.
3219fn iv_lower_bound(
3220    iv: Symbol,
3221    body: &[Stmt],
3222    state: &RichAbstractState,
3223    mutated: &std::collections::HashSet<Symbol>,
3224    inits: &HashMap<Symbol, i64>,
3225) -> Option<i64> {
3226    let lo = match inits.get(&iv) {
3227        Some(c) => *c,
3228        None => match state.intervals.get_var(&iv).lo {
3229            Bound::Finite(l) => l,
3230            _ => return None,
3231        },
3232    };
3233    fn preserved(
3234        iv: Symbol,
3235        stmts: &[Stmt],
3236        lo: i64,
3237        state: &RichAbstractState,
3238        mutated: &std::collections::HashSet<Symbol>,
3239    ) -> bool {
3240        stmts.iter().all(|s| match s {
3241            Stmt::Set { target, value } if *target == iv => {
3242                write_keeps_ge(value, iv, lo, state, mutated)
3243            }
3244            Stmt::Let { var, value, .. } if *var == iv => {
3245                write_keeps_ge(value, iv, lo, state, mutated)
3246            }
3247            Stmt::If {
3248                then_block,
3249                else_block,
3250                ..
3251            } => {
3252                preserved(iv, then_block, lo, state, mutated)
3253                    && else_block.map_or(true, |eb| preserved(iv, eb, lo, state, mutated))
3254            }
3255            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
3256                preserved(iv, body, lo, state, mutated)
3257            }
3258            _ => true,
3259        })
3260    }
3261    preserved(iv, body, lo, state, mutated).then_some(lo)
3262}
3263
3264/// Add a loop's guard constraints, plus a sound lower bound for each induction
3265/// variable, to the fact set. `inits` carries explicit counter initializations
3266/// from the enclosing body (`Let j be 0`) so a reset nested counter still gets
3267/// its entry lower bound.
3268/// `Set v to v + c` or `Set v to c + v` (literal `c`) → `Some(c)`.
3269pub(crate) fn self_increment(v: Symbol, value: &Expr) -> Option<i64> {
3270    if let Expr::BinaryOp {
3271        op: BinaryOpKind::Add,
3272        left,
3273        right,
3274    } = value
3275    {
3276        if let (Expr::Identifier(s), Expr::Literal(Literal::Number(c))) = (&**left, &**right) {
3277            if *s == v {
3278                return Some(*c);
3279            }
3280        }
3281        if let (Expr::Literal(Literal::Number(c)), Expr::Identifier(s)) = (&**left, &**right) {
3282            if *s == v {
3283                return Some(*c);
3284            }
3285        }
3286    }
3287    None
3288}
3289
3290/// `Set v to v - c` (literal `c >= 0`) → `Some(c)` — the decreasing counterpart of
3291/// [`self_increment`], used to recognize a monotonically-shrinking loop bound.
3292pub(crate) fn self_decrement(v: Symbol, value: &Expr) -> Option<i64> {
3293    if let Expr::BinaryOp {
3294        op: BinaryOpKind::Subtract,
3295        left,
3296        right,
3297    } = value
3298    {
3299        if let (Expr::Identifier(s), Expr::Literal(Literal::Number(c))) = (&**left, &**right) {
3300            if *s == v && *c >= 0 {
3301                return Some(*c);
3302            }
3303        }
3304    }
3305    None
3306}
3307
3308/// Variables that have a TOP-LEVEL (direct child of `body`, not nested in any
3309/// `If`/`While`) `Set v to v + dj` (`dj > 0`) that is `v`'s ONLY write in the
3310/// whole body — so each iteration increments `v` by exactly `dj`.
3311fn top_level_unconditional_incs(body: &[Stmt], globals: &CalleeGlobals) -> Vec<(Symbol, i64)> {
3312    let mut out = Vec::new();
3313    for s in body {
3314        if let Stmt::Set { target, value } = s {
3315            if let Some(c) = self_increment(*target, value) {
3316                if c > 0 && count_writes_of(body, *target, globals) == 1 {
3317                    out.push((*target, c));
3318                }
3319            }
3320        }
3321    }
3322    out
3323}
3324
3325/// Is every write to `v` in `stmts` a `Set v to v + ci` (`ci >= 0`), none inside
3326/// a nested loop, with the writes summing to `<= limit` and at least one present?
3327/// Such a `v` increases by at most `limit` per outer iteration.
3328fn monotone_inc_within(
3329    stmts: &[Stmt],
3330    v: Symbol,
3331    in_loop: bool,
3332    total: &mut i64,
3333    count: &mut usize,
3334) -> bool {
3335    for s in stmts {
3336        match s {
3337            Stmt::Set { target, value } if *target == v => match self_increment(v, value) {
3338                Some(c) if c >= 0 && !in_loop => {
3339                    *total += c;
3340                    *count += 1;
3341                }
3342                _ => return false,
3343            },
3344            Stmt::Let { var, .. } if *var == v => return false,
3345            Stmt::If {
3346                then_block,
3347                else_block,
3348                ..
3349            } => {
3350                if !monotone_inc_within(then_block, v, in_loop, total, count) {
3351                    return false;
3352                }
3353                if let Some(eb) = else_block {
3354                    if !monotone_inc_within(eb, v, in_loop, total, count) {
3355                        return false;
3356                    }
3357                }
3358            }
3359            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
3360                if !monotone_inc_within(body, v, true, total, count) {
3361                    return false;
3362                }
3363            }
3364            _ => {}
3365        }
3366    }
3367    true
3368}
3369
3370/// Candidate `i` variables for an `i <= j` invariant: monotone increments
3371/// summing to `<= limit`, at least one increment, none inside a nested loop.
3372fn monotone_inc_vars(body: &[Stmt], limit: i64) -> Vec<Symbol> {
3373    let mut cands: Vec<Symbol> = Vec::new();
3374    fn collect(stmts: &[Stmt], out: &mut Vec<Symbol>) {
3375        for s in stmts {
3376            match s {
3377                Stmt::Set { target, value } if self_increment(*target, value).is_some() => {
3378                    if !out.contains(target) {
3379                        out.push(*target);
3380                    }
3381                }
3382                Stmt::If {
3383                    then_block,
3384                    else_block,
3385                    ..
3386                } => {
3387                    collect(then_block, out);
3388                    if let Some(eb) = else_block {
3389                        collect(eb, out);
3390                    }
3391                }
3392                Stmt::While { body, .. } | Stmt::Repeat { body, .. } => collect(body, out),
3393                _ => {}
3394            }
3395        }
3396    }
3397    collect(body, &mut cands);
3398    cands
3399        .into_iter()
3400        .filter(|v| {
3401            let (mut total, mut count) = (0, 0);
3402            monotone_inc_within(body, *v, false, &mut total, &mut count)
3403                && count >= 1
3404                && total <= limit
3405        })
3406        .collect()
3407}
3408
3409/// Derive `i <= j` loop invariants (the quicksort/Lomuto partition shape).
3410///
3411/// `j` increments unconditionally by `dj` at the top of the body; `i`'s only
3412/// writes are `Set i to i + ci` (`ci >= 0`) summing to `<= dj`, none inside a
3413/// nested loop; and `i` and `j` start from the SAME value (equal `scalar_def` at
3414/// loop entry — covers `i=1,j=1` and `i=lo,j=lo` alike). Then `i0 = j0` and
3415/// `Δi <= Δj` each iteration, so `i <= j` holds at the loop head. `affine_walk`
3416/// drops the fact when `i` (or `j`) is mutated, so it only proves accesses
3417/// BEFORE the increment — exactly the partition's `item i of arr` read/store.
3418fn derive_iv_le_invariants(
3419    body: &[Stmt],
3420    entry: &RichAbstractState,
3421    state: &RichAbstractState,
3422    mutated: &std::collections::HashSet<Symbol>,
3423    inits: &HashMap<Symbol, i64>,
3424    amb: &mut AffineFacts,
3425) {
3426    use super::affine::{ge, konst, le, var};
3427    for (j, dj) in top_level_unconditional_incs(body, &entry.callee_globals) {
3428        for i in monotone_inc_vars(body, dj) {
3429            if i == j {
3430                continue;
3431            }
3432            // i0 == j0: `i` and `j` are defined by the same linear expression at
3433            // loop entry (constant or symbolic `lo`).
3434            let equal_start = match (entry.scalar_def.get(&i), entry.scalar_def.get(&j)) {
3435                (Some(a), Some(b)) => a == b,
3436                _ => false,
3437            };
3438            if !equal_start {
3439                continue;
3440            }
3441            amb.constraints.push(le(&var(i), &var(j)));
3442            // `1 <= i` obligation needs `i`'s sound lower bound (it is not a
3443            // guard variable, so the guard pass would not add it).
3444            if let Some(lo) = iv_lower_bound(i, body, state, mutated, inits) {
3445                amb.constraints.push(ge(&var(i), &konst(lo)));
3446            }
3447            // SYMBOLIC lower: `i`/`j` start at their shared entry def `U` (parameter
3448            // `lo`) and only INCREASE, so `i >= U`, `j >= U`. Chained with the
3449            // entry-guard's `scalar_lower[lo] >= 1` (pushed into the system for U's
3450            // symbols), this discharges `1 <= E` for a SYMBOLIC `lo` — the partition
3451            // swap's `item i`. Sound: a monotone-increasing var never drops below its
3452            // initial value. Add U's symbols so `1 <= lo` (its scalar_lower) enters.
3453            // `i`/`j` start at their shared entry def `U` (parameter `lo`) and only
3454            // INCREASE, so `i >= U`, `j >= U`. Chained with the function-wide entry-guard
3455            // ambient `lo >= 1` (injected in every proof system), this discharges
3456            // `1 <= i,j` for the partition swap. Sound: monotone-increasing from init.
3457            if let Some(u) = entry.scalar_def.get(&i) {
3458                amb.constraints.push(ge(&var(i), u));
3459                amb.constraints.push(ge(&var(j), u));
3460                for &si in u.coefficients.keys() {
3461                    let s = Symbol::from_index(si as usize);
3462                    if !amb.syms.contains(&s) {
3463                        amb.syms.push(s);
3464                    }
3465                }
3466            }
3467            for s in [i, j] {
3468                if !amb.syms.contains(&s) {
3469                    amb.syms.push(s);
3470                }
3471            }
3472        }
3473    }
3474}
3475
3476fn affine_add_loop_guards(
3477    cond: &Expr,
3478    body: &[Stmt],
3479    state: &RichAbstractState,
3480    entry: Option<&RichAbstractState>,
3481    inits: &HashMap<Symbol, i64>,
3482    amb: &mut AffineFacts,
3483) {
3484    affine_add_cmp(cond, false, amb);
3485    let mutated: std::collections::HashSet<Symbol> =
3486        collect_mutations_in(body, &state.callee_globals)
3487            .into_iter()
3488            .collect();
3489    let mut ivs: Vec<Symbol> = Vec::new();
3490    affine_collect_syms(cond, &mut ivs);
3491    for iv in ivs {
3492        if let Some(lo) = iv_lower_bound(iv, body, state, &mutated, inits) {
3493            amb.constraints.push(super::affine::ge(
3494                &super::affine::var(iv),
3495                &super::affine::konst(lo),
3496            ));
3497            if !amb.syms.contains(&iv) {
3498                amb.syms.push(iv);
3499            }
3500        }
3501    }
3502    // Two-induction-variable `i <= j` relations need the true loop-ENTRY state to
3503    // establish `i0 = j0`; only the top-level call threads it (nested loops pass
3504    // `None`, since the widened body state cannot witness the entry equality).
3505    if let Some(entry) = entry {
3506        derive_iv_le_invariants(body, entry, state, &mutated, inits, amb);
3507        derive_monotone_dec_invariants(body, entry, &mutated, amb);
3508    }
3509}
3510
3511/// A variable whose ONLY write in `body` is a single top-level `Set v to v - c`
3512/// (`c >= 0`) monotonically DECREASES, so `v <= v_entry` holds throughout the loop.
3513/// Its loop-entry def (`entry.scalar_def[v]` = `n - 1`, captured before the loop's
3514/// first decrement) then discharges the UPPER bound of an `item v of arr` access
3515/// when a length lower bound relates `arr` to that def (`len >= n`) — e.g.
3516/// heap_sort's main-phase `arr[end]` swap. The decreasing mirror of
3517/// [`derive_iv_le_invariants`]. SOUND: a value that only shrinks never exceeds its
3518/// loop-entry value, and the entry def is used only when its own variables are
3519/// loop-invariant (so it names the same fixed value at every access).
3520fn derive_monotone_dec_invariants(
3521    body: &[Stmt],
3522    entry: &RichAbstractState,
3523    mutated: &std::collections::HashSet<Symbol>,
3524    amb: &mut AffineFacts,
3525) {
3526    use super::affine::{le, var};
3527    for s in body {
3528        if let Stmt::Set { target, value } = s {
3529            if self_decrement(*target, value).is_some()
3530                && count_writes_of(body, *target, &entry.callee_globals) == 1
3531            {
3532                if let Some(e0) = entry.scalar_def.get(target) {
3533                    let e0_stable = e0
3534                        .coefficients
3535                        .keys()
3536                        .all(|&si| !mutated.contains(&Symbol::from_index(si as usize)));
3537                    if e0_stable {
3538                        amb.constraints.push(le(&var(*target), e0));
3539                        for &si in e0.coefficients.keys() {
3540                            let sym = Symbol::from_index(si as usize);
3541                            if !amb.syms.contains(&sym) {
3542                                amb.syms.push(sym);
3543                            }
3544                        }
3545                        if !amb.syms.contains(target) {
3546                            amb.syms.push(*target);
3547                        }
3548                    }
3549                }
3550            }
3551        }
3552    }
3553}
3554
3555/// Drop ambient facts mentioning any symbol in `set` (a write reaches earlier
3556/// reads across loop iterations, or a sequential reassignment invalidates a
3557/// guard).
3558fn affine_drop_mentioning(amb: &mut AffineFacts, set: &std::collections::HashSet<Symbol>) {
3559    amb.constraints.retain(|c| {
3560        !set.iter()
3561            .any(|s| c.expr.coefficients.contains_key(&(s.index() as i64)))
3562    });
3563    amb.syms.retain(|s| !set.contains(s));
3564}
3565
3566fn affine_drop_one(amb: &mut AffineFacts, sym: Symbol) {
3567    let k = sym.index() as i64;
3568    amb.constraints
3569        .retain(|c| !c.expr.coefficients.contains_key(&k));
3570    amb.syms.retain(|s| *s != sym);
3571}
3572
3573/// Prove every `Index` node in an expression in place (no ref storage —
3574/// avoids threading the arena lifetime through a collecting `Vec`).
3575fn affine_prove_in_expr(
3576    e: &Expr,
3577    body: &[Stmt],
3578    state: &RichAbstractState,
3579    clobbered: &std::collections::HashSet<Symbol>,
3580    mutated: &std::collections::HashSet<Symbol>,
3581    amb: &AffineFacts,
3582    facts: &mut OracleFacts,
3583) {
3584    if let Expr::Index { collection, index } = e {
3585        if amb.karr_pass {
3586            try_prove_affine_karr(collection, index, state, mutated, amb, facts);
3587        } else {
3588            // Dense `Map of Int to Int` get: `item k of m` → prove `0 <= k <= cap(m)`.
3589            if let Expr::Identifier(m) = collection {
3590                if facts.map_caps.contains_key(m) {
3591                    try_prove_dense_key(*m, index, state, mutated, amb, facts);
3592                }
3593            }
3594            try_prove_affine(
3595                collection, index, body, state, clobbered, mutated, amb, facts,
3596            );
3597        }
3598    }
3599    // Dense map membership: `m contains k` → prove `0 <= k <= cap(m)`.
3600    if let (Expr::Contains { collection, value }, false) = (e, amb.karr_pass) {
3601        if let Expr::Identifier(m) = collection {
3602            if facts.map_caps.contains_key(m) {
3603                try_prove_dense_key(*m, value, state, mutated, amb, facts);
3604            }
3605        }
3606    }
3607    match e {
3608        Expr::BinaryOp { left, right, .. }
3609        | Expr::Union { left, right }
3610        | Expr::Intersection { left, right }
3611        | Expr::Range {
3612            start: left,
3613            end: right,
3614        } => {
3615            affine_prove_in_expr(left, body, state, clobbered, mutated, amb, facts);
3616            affine_prove_in_expr(right, body, state, clobbered, mutated, amb, facts);
3617        }
3618        Expr::Not { operand } => {
3619            affine_prove_in_expr(operand, body, state, clobbered, mutated, amb, facts)
3620        }
3621        Expr::Contains { collection, value } => {
3622            affine_prove_in_expr(collection, body, state, clobbered, mutated, amb, facts);
3623            affine_prove_in_expr(value, body, state, clobbered, mutated, amb, facts);
3624        }
3625        Expr::Index { collection, index } => {
3626            affine_prove_in_expr(collection, body, state, clobbered, mutated, amb, facts);
3627            affine_prove_in_expr(index, body, state, clobbered, mutated, amb, facts);
3628        }
3629        Expr::Call { args, .. } => {
3630            for a in args {
3631                affine_prove_in_expr(a, body, state, clobbered, mutated, amb, facts);
3632            }
3633        }
3634        Expr::Length { collection } => {
3635            affine_prove_in_expr(collection, body, state, clobbered, mutated, amb, facts)
3636        }
3637        _ => {}
3638    }
3639}
3640
3641/// A symbolic LOWER bound on `length(arr)` (the `var(n) + off` from a counted
3642/// build loop, else a finite concrete length), with the variables it names.
3643fn affine_length_lb(
3644    arr: Symbol,
3645    state: &RichAbstractState,
3646) -> Option<(super::affine::LinExpr, Vec<Symbol>)> {
3647    use super::affine::{konst, var};
3648    if let Some((n, off)) = state.length_def.get(&arr) {
3649        return Some((var(*n).add(&konst(*off)), vec![*n]));
3650    }
3651    if let Bound::Finite(l) = state.intervals.get_length(&arr).lo {
3652        return Some((konst(l), vec![]));
3653    }
3654    None
3655}
3656
3657/// Walk a loop body in execution order, accumulating path guards and nested
3658/// loop guards, and prove each affine index access in scope.
3659fn affine_walk(
3660    stmts: &[Stmt],
3661    full_body: &[Stmt],
3662    state: &RichAbstractState,
3663    clobbered: &std::collections::HashSet<Symbol>,
3664    mutated: &std::collections::HashSet<Symbol>,
3665    ambient: &AffineFacts,
3666    inits: &HashMap<Symbol, i64>,
3667    facts: &mut OracleFacts,
3668) {
3669    let mut local = ambient.clone();
3670    let mut inits = inits.clone();
3671    for stmt in stmts {
3672        for_each_direct_expr(stmt, &mut |e| {
3673            affine_prove_in_expr(e, full_body, state, clobbered, mutated, &local, facts);
3674        });
3675        if let Stmt::SetIndex {
3676            collection, index, ..
3677        } = stmt
3678        {
3679            if local.karr_pass {
3680                try_prove_affine_karr(collection, index, state, mutated, &local, facts);
3681            } else {
3682                // Dense `Map of Int to Int` insert: `Set item k of m to v` → prove
3683                // `0 <= k <= cap(m)`.
3684                if let Expr::Identifier(m) = collection {
3685                    if facts.map_caps.contains_key(m) {
3686                        try_prove_dense_key(*m, index, state, mutated, &local, facts);
3687                    }
3688                }
3689                try_prove_affine(
3690                    collection, index, full_body, state, clobbered, mutated, &local, facts,
3691                );
3692            }
3693        }
3694        match stmt {
3695            Stmt::If {
3696                cond,
3697                then_block,
3698                else_block,
3699            } => {
3700                let mut then_facts = local.clone();
3701                affine_add_cmp(cond, false, &mut then_facts);
3702                affine_walk(
3703                    then_block,
3704                    full_body,
3705                    state,
3706                    clobbered,
3707                    mutated,
3708                    &then_facts,
3709                    &inits,
3710                    facts,
3711                );
3712                if let Some(eb) = else_block {
3713                    let mut else_facts = local.clone();
3714                    affine_add_cmp(cond, true, &mut else_facts);
3715                    affine_walk(
3716                        eb,
3717                        full_body,
3718                        state,
3719                        clobbered,
3720                        mutated,
3721                        &else_facts,
3722                        &inits,
3723                        facts,
3724                    );
3725                }
3726            }
3727            Stmt::While { cond, body, .. } => {
3728                // A nested loop's body may rewrite a variable an ambient fact
3729                // rests on (a later iteration reaching an earlier read), so drop
3730                // facts naming anything it mutates before adding its own guard.
3731                let nested: std::collections::HashSet<Symbol> =
3732                    collect_mutations_in(body, &state.callee_globals)
3733                        .into_iter()
3734                        .collect();
3735                let mut inner = local.clone();
3736                affine_drop_mentioning(&mut inner, &nested);
3737                affine_add_loop_guards(cond, body, state, None, &inits, &mut inner);
3738                affine_walk(
3739                    body, full_body, state, clobbered, mutated, &inner, &inits, facts,
3740                );
3741            }
3742            Stmt::Repeat { body, .. } => {
3743                affine_walk(
3744                    body, full_body, state, clobbered, mutated, &local, &inits, facts,
3745                );
3746            }
3747            _ => {}
3748        }
3749        // Track counter initializations (`Let j be 0`) so a following nested
3750        // loop sees the reset counter's true entry lower bound; a reassignment
3751        // to anything else clears it. Also drop ambient facts naming the target.
3752        match stmt {
3753            Stmt::Set { target, value } => {
3754                if let Expr::Literal(Literal::Number(n)) = value {
3755                    inits.insert(*target, *n);
3756                } else {
3757                    inits.remove(target);
3758                }
3759                affine_drop_one(&mut local, *target);
3760            }
3761            Stmt::Let { var, value, .. } => {
3762                if let Expr::Literal(Literal::Number(n)) = value {
3763                    inits.insert(*var, *n);
3764                } else {
3765                    inits.remove(var);
3766                }
3767                affine_drop_one(&mut local, *var);
3768            }
3769            _ => {}
3770        }
3771    }
3772}
3773
3774/// Discharge the index accesses a single TOP-LEVEL statement holds, at `st` (the
3775/// statement's pre-state) — the same affine proof `affine_walk` runs over a loop
3776/// body, applied to a statement OUTSIDE any loop. The entry-guarded partition's
3777/// post-loop pivot swap (`item i of arr`) rests on the loop-EXIT invariant
3778/// `lo <= i <= hi` that `rich_walk_loop` records into `st`; the function-wide
3779/// entry-guard lowers (`lo>=1`,`hi>=1`) reach the proof from `st.entry_guard_lowers`
3780/// inside `try_prove_affine`, so the ambient system is empty here. `body` is the
3781/// whole function body (the `sym_ge_lo`/`sym_le_sym` walk domain).
3782fn prove_toplevel_accesses(
3783    stmt: &Stmt,
3784    body: &[Stmt],
3785    st: &RichAbstractState,
3786    clobbered: &std::collections::HashSet<Symbol>,
3787    mutated: &std::collections::HashSet<Symbol>,
3788    facts: &mut OracleFacts,
3789) {
3790    let amb = AffineFacts::default();
3791    for_each_direct_expr(stmt, &mut |e| {
3792        affine_prove_in_expr(e, body, st, clobbered, mutated, &amb, facts);
3793    });
3794    if let Stmt::SetIndex {
3795        collection, index, ..
3796    } = stmt
3797    {
3798        try_prove_affine(collection, index, body, st, clobbered, mutated, &amb, facts);
3799    }
3800}
3801
3802/// Prove `value >= lo` under the assume-guarantee hypothesis that every symbol in
3803/// `assumed` is already `>= lo` at the point of assignment.
3804///
3805/// **Soundness (co-induction over the `>= lo` safety invariant).** The `assumed`
3806/// shortcut is the co-inductive hypothesis; it is sound because the invariant's BASE
3807/// holds: every LOGOS variable has a grounded first definition (use-before-def is
3808/// rejected by scope analysis *before* the optimizer runs), so every recursion
3809/// bottoms out in a literal, a parameter interval / entry-guard lower, or an
3810/// unconditional `>= lo` assignment not depending on the hypothesis. A variable is
3811/// proven `>= lo` only when EVERY value assigned to it in `body` is `>= lo`. The
3812/// index arithmetic stays overflow-CHECKED, so the runtime index equals this value
3813/// (or the program panics first) — sound for `get_unchecked`.
3814fn value_ge_lo(
3815    value: &Expr,
3816    lo: i64,
3817    body: &[Stmt],
3818    state: &RichAbstractState,
3819    mutated: &std::collections::HashSet<Symbol>,
3820    assumed: &std::collections::HashSet<Symbol>,
3821    fuel: u32,
3822) -> bool {
3823    if fuel == 0 {
3824        return false;
3825    }
3826    match value {
3827        Expr::Literal(Literal::Number(n)) => *n >= lo,
3828        Expr::Identifier(s) => {
3829            if assumed.contains(s) {
3830                return true;
3831            }
3832            if !mutated.contains(s) {
3833                if matches!(state.intervals.get_var(s).lo, Bound::Finite(l) if l >= lo) {
3834                    return true;
3835                }
3836            }
3837            if state
3838                .entry_guard_lowers
3839                .iter()
3840                .any(|(g, l)| g == s && *l >= lo)
3841            {
3842                return true;
3843            }
3844            let mut a2 = assumed.clone();
3845            a2.insert(*s);
3846            sym_ge_lo(*s, lo, body, state, mutated, &a2, fuel - 1)
3847        }
3848        Expr::BinaryOp {
3849            op: BinaryOpKind::Add,
3850            left,
3851            right,
3852        } => {
3853            (value_ge_lo(left, lo, body, state, mutated, assumed, fuel - 1)
3854                && value_ge_lo(right, 0, body, state, mutated, assumed, fuel - 1))
3855                || (value_ge_lo(left, 0, body, state, mutated, assumed, fuel - 1)
3856                    && value_ge_lo(right, lo, body, state, mutated, assumed, fuel - 1))
3857        }
3858        // `k * v` with both factors `>= 0` is `>= 0 >= lo` (only claimed for `lo <= 0`).
3859        Expr::BinaryOp {
3860            op: BinaryOpKind::Multiply,
3861            left,
3862            right,
3863        } => {
3864            lo <= 0
3865                && value_ge_lo(left, 0, body, state, mutated, assumed, fuel - 1)
3866                && value_ge_lo(right, 0, body, state, mutated, assumed, fuel - 1)
3867        }
3868        _ => false,
3869    }
3870}
3871
3872/// `sym >= lo` whenever it has at least one definition in `body` and EVERY value
3873/// assigned to it (its `Let` init and all `Set`s) is `>= lo` (via [`value_ge_lo`]).
3874fn sym_ge_lo(
3875    sym: Symbol,
3876    lo: i64,
3877    body: &[Stmt],
3878    state: &RichAbstractState,
3879    mutated: &std::collections::HashSet<Symbol>,
3880    assumed: &std::collections::HashSet<Symbol>,
3881    fuel: u32,
3882) -> bool {
3883    if fuel == 0 {
3884        return false;
3885    }
3886    fn walk(
3887        sym: Symbol,
3888        stmts: &[Stmt],
3889        lo: i64,
3890        body: &[Stmt],
3891        state: &RichAbstractState,
3892        mutated: &std::collections::HashSet<Symbol>,
3893        assumed: &std::collections::HashSet<Symbol>,
3894        fuel: u32,
3895        seen: &mut bool,
3896    ) -> bool {
3897        stmts.iter().all(|s| match s {
3898            Stmt::Set { target, value } if *target == sym => {
3899                *seen = true;
3900                value_ge_lo(value, lo, body, state, mutated, assumed, fuel)
3901            }
3902            Stmt::Let { var, value, .. } if *var == sym => {
3903                *seen = true;
3904                value_ge_lo(value, lo, body, state, mutated, assumed, fuel)
3905            }
3906            Stmt::If {
3907                then_block,
3908                else_block,
3909                ..
3910            } => {
3911                walk(
3912                    sym, then_block, lo, body, state, mutated, assumed, fuel, seen,
3913                ) && else_block.map_or(true, |eb| {
3914                    walk(sym, eb, lo, body, state, mutated, assumed, fuel, seen)
3915                })
3916            }
3917            Stmt::While { body: b, .. } | Stmt::Repeat { body: b, .. } => {
3918                walk(sym, b, lo, body, state, mutated, assumed, fuel, seen)
3919            }
3920            _ => true,
3921        })
3922    }
3923    let mut seen = false;
3924    let ok = walk(
3925        sym, body, lo, body, state, mutated, assumed, fuel, &mut seen,
3926    );
3927    ok && seen
3928}
3929
3930/// Prove `value <= bound_sym` under `base` plus the affine `path` guards enclosing
3931/// the assignment (each as `(cond, negate)`), plus the scalar definitions of the
3932/// value's own symbols (so `child = 2*root+1` reaches the loop guard `2*root+1 <=
3933/// end`). Path-sensitive: `Set s to child+1` inside `if child+1 <= end` uses that
3934/// guard.
3935fn prove_le_bound(
3936    value: &Expr,
3937    bound_sym: Symbol,
3938    base: &[super::affine::Constraint],
3939    path: &[(&Expr, bool)],
3940    state: &RichAbstractState,
3941    local_defs: &HashMap<Symbol, super::affine::LinExpr>,
3942) -> bool {
3943    use super::affine::{consistent, le, lin_of, prove, var};
3944    let Some(v_lin) = lin_of(value) else {
3945        return false;
3946    };
3947    let mut facts = AffineFacts {
3948        constraints: base.to_vec(),
3949        ..AffineFacts::default()
3950    };
3951    for &(c, neg) in path {
3952        affine_add_cmp(c, neg, &mut facts);
3953    }
3954    let mut vsyms = Vec::new();
3955    affine_collect_syms(value, &mut vsyms);
3956    for s in vsyms {
3957        // A body scalar-def (`cols = capacity + 1`) OR a loop-local single-`Let`
3958        // affine binding (`child = 2*root+1`). The latter is dropped from the
3959        // shared `scalar_def` when its RHS (`root`) is reassigned, but `child = E`
3960        // still holds at every use inside the iteration — and is SOUND here because
3961        // it only combines with the loop guard, which is itself dropped from `base`
3962        // once `root` is reassigned, so the pair is available only before the change.
3963        if let Some(def) = state.scalar_def.get(&s).or_else(|| local_defs.get(&s)) {
3964            facts.constraints.push(le(&var(s), def));
3965            facts.constraints.push(le(def, &var(s)));
3966        }
3967    }
3968    consistent(&facts.constraints) && prove(&facts.constraints, &var(bound_sym).sub(&v_lin))
3969}
3970
3971/// Single-`Let`, never-`Set` affine bindings of `body` (`child = 2*root+1`),
3972/// INCLUDING those whose RHS is later reassigned — sound for [`prove_le_bound`]'s
3973/// guard-gated use (see there). The permissive counterpart of
3974/// [`augment_body_scalar_defs`].
3975fn collect_local_affine_defs(
3976    body: &[Stmt],
3977    globals: &CalleeGlobals,
3978) -> HashMap<Symbol, super::affine::LinExpr> {
3979    let set_targets = reassigned_scalars(body, globals);
3980    let mut let_count: HashMap<Symbol, u32> = HashMap::new();
3981    fn count(stmts: &[Stmt], lc: &mut HashMap<Symbol, u32>) {
3982        for s in stmts {
3983            match s {
3984                Stmt::Let { var, .. } => *lc.entry(*var).or_insert(0) += 1,
3985                Stmt::If {
3986                    then_block,
3987                    else_block,
3988                    ..
3989                } => {
3990                    count(then_block, lc);
3991                    if let Some(e) = else_block {
3992                        count(e, lc);
3993                    }
3994                }
3995                Stmt::While { body, .. } | Stmt::Repeat { body, .. } => count(body, lc),
3996                _ => {}
3997            }
3998        }
3999    }
4000    count(body, &mut let_count);
4001    let mut defs: HashMap<Symbol, super::affine::LinExpr> = HashMap::new();
4002    fn walk(
4003        stmts: &[Stmt],
4004        set_targets: &std::collections::HashSet<Symbol>,
4005        let_count: &HashMap<Symbol, u32>,
4006        defs: &mut HashMap<Symbol, super::affine::LinExpr>,
4007    ) {
4008        for s in stmts {
4009            match s {
4010                Stmt::Let { var, value, .. }
4011                    if !set_targets.contains(var) && let_count.get(var) == Some(&1) =>
4012                {
4013                    if let Some(e) = super::affine::lin_of(value) {
4014                        if !e.coefficients.is_empty()
4015                            && !e.coefficients.contains_key(&(var.index() as i64))
4016                        {
4017                            defs.insert(*var, e);
4018                        }
4019                    }
4020                }
4021                Stmt::If {
4022                    then_block,
4023                    else_block,
4024                    ..
4025                } => {
4026                    walk(then_block, set_targets, let_count, defs);
4027                    if let Some(e) = else_block {
4028                        walk(e, set_targets, let_count, defs);
4029                    }
4030                }
4031                Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
4032                    walk(body, set_targets, let_count, defs)
4033                }
4034                _ => {}
4035            }
4036        }
4037    }
4038    walk(body, &set_targets, &let_count, &mut defs);
4039    defs
4040}
4041
4042/// `s <= bound_sym` when it has at least one definition and EVERY value assigned to
4043/// it is `<= bound_sym` under its enclosing path guards (via [`prove_le_bound`]).
4044/// The upper counterpart to [`sym_ge_lo`]; unlike the lower bound it needs no
4045/// co-induction because a heap index's assignments (`root`, `2*root+1`, `child+1`)
4046/// bound above by the loop / path guards, never by the index itself.
4047fn sym_le_sym(
4048    s: Symbol,
4049    bound_sym: Symbol,
4050    body: &[Stmt],
4051    base: &[super::affine::Constraint],
4052    state: &RichAbstractState,
4053) -> bool {
4054    #[allow(clippy::too_many_arguments)]
4055    fn walk<'a>(
4056        s: Symbol,
4057        stmts: &'a [Stmt<'a>],
4058        bound_sym: Symbol,
4059        base: &[super::affine::Constraint],
4060        state: &RichAbstractState,
4061        local_defs: &HashMap<Symbol, super::affine::LinExpr>,
4062        path: &mut Vec<(&'a Expr<'a>, bool)>,
4063        seen: &mut bool,
4064        fuel: &mut u32,
4065    ) -> bool {
4066        if *fuel == 0 {
4067            return false;
4068        }
4069        *fuel -= 1;
4070        stmts.iter().all(|stmt| match stmt {
4071            Stmt::Set { target, value } if *target == s => {
4072                *seen = true;
4073                prove_le_bound(value, bound_sym, base, path, state, local_defs)
4074            }
4075            Stmt::Let { var, value, .. } if *var == s => {
4076                *seen = true;
4077                prove_le_bound(value, bound_sym, base, path, state, local_defs)
4078            }
4079            Stmt::If {
4080                cond,
4081                then_block,
4082                else_block,
4083            } => {
4084                path.push((cond, false));
4085                let ok_t = walk(
4086                    s, then_block, bound_sym, base, state, local_defs, path, seen, fuel,
4087                );
4088                path.pop();
4089                let ok_e = else_block.map_or(true, |eb| {
4090                    path.push((cond, true));
4091                    let r = walk(s, eb, bound_sym, base, state, local_defs, path, seen, fuel);
4092                    path.pop();
4093                    r
4094                });
4095                ok_t && ok_e
4096            }
4097            Stmt::While { body: b, .. } | Stmt::Repeat { body: b, .. } => {
4098                walk(s, b, bound_sym, base, state, local_defs, path, seen, fuel)
4099            }
4100            _ => true,
4101        })
4102    }
4103    let local_defs = collect_local_affine_defs(body, &state.callee_globals);
4104    let mut path: Vec<(&Expr, bool)> = Vec::new();
4105    let mut seen = false;
4106    let mut fuel = 400u32;
4107    let ok = walk(
4108        s,
4109        body,
4110        bound_sym,
4111        base,
4112        state,
4113        &local_defs,
4114        &mut path,
4115        &mut seen,
4116        &mut fuel,
4117    );
4118    ok && seen
4119}
4120
4121/// Discharge `1 <= E <= length(arr)` for one access from the affine equalities holding where it is evaluated
4122/// ([`OracleFacts::karr_at`]) and the guards in scope, against the sequence's own length. A merge's store
4123/// `item k of result` is the case: `k = li + ri - 1` under `li <= length of left` and `ri <= length of right`, with
4124/// the builds before the loop making `length of left + length of right` equal to `length of result`. A name the body
4125/// writes keeps no header interval here; the guards and the equalities speak for it.
4126///
4127/// The equalities never reach the prover as pairs of inequalities: each one solves for a variable of its own
4128/// ([`super::karr::AffineSpace::solved`]), which is substituted out of the goal and every guard exactly. What is left
4129/// is narrowed to the constraints that share a variable, directly or through others, with the goal, and the prover
4130/// runs only on a system of at most [`KARR_MAX_CONSTRAINTS`] constraints over [`KARR_MAX_VARS`] variables:
4131/// Fourier-Motzkin can square its constraint count with each variable it eliminates, and a large generated program
4132/// holds dozens of equalities at one access. A system past the bound proves nothing, and the access keeps its check.
4133fn try_prove_affine_karr(
4134    collection: &Expr,
4135    index: &Expr,
4136    state: &RichAbstractState,
4137    mutated: &HashSet<Symbol>,
4138    amb: &AffineFacts,
4139    facts: &mut OracleFacts,
4140) {
4141    use super::affine::{
4142        consistent, konst, le, len_index, len_var, lin_of, prove, var, Constraint, LinExpr,
4143    };
4144    let Expr::Identifier(arr) = collection else {
4145        return;
4146    };
4147    let key = index as *const Expr as usize;
4148    if facts.relational_inbounds.contains(&key) {
4149        return;
4150    }
4151    let Some(karr) = facts.karr_at.get(&key) else {
4152        return;
4153    };
4154    if !karr.tracked().contains(&len_index(*arr)) {
4155        return;
4156    }
4157    let Some(e) = lin_of(index) else { return };
4158
4159    // The guards and the bounds of every name they or the goal mention.
4160    let mut system: Vec<Constraint> = amb.constraints.clone();
4161    let mut mentioned: std::collections::BTreeSet<i64> = e.coefficients.keys().copied().collect();
4162    mentioned.insert(len_index(*arr));
4163    for c in &system {
4164        mentioned.extend(c.expr.coefficients.keys().copied());
4165    }
4166    let solved = karr.solved();
4167    for (_, v) in &solved {
4168        mentioned.extend(v.coefficients.keys().copied());
4169    }
4170    for &(d, _) in &solved {
4171        mentioned.insert(d);
4172    }
4173    for &k in &mentioned {
4174        if k < 0 {
4175            system.push(le(&konst(0), &LinExpr::var(k)));
4176            continue;
4177        }
4178        let s = Symbol::from_index(k as usize);
4179        if !mutated.contains(&s) {
4180            let iv = state.intervals.get_var(&s);
4181            if let Bound::Finite(lo) = iv.lo {
4182                system.push(le(&konst(lo), &var(s)));
4183            }
4184            if let Bound::Finite(hi) = iv.hi {
4185                system.push(le(&var(s), &konst(hi)));
4186            }
4187        }
4188        if let Some(l) = state.scalar_lower.get(&s) {
4189            system.push(le(l, &var(s)));
4190        }
4191    }
4192    for &(s, lb) in &state.entry_guard_lowers {
4193        system.push(le(&konst(lb), &var(s)));
4194    }
4195
4196    // Substitute every solved equality out of the goals and the system.
4197    let substitute = |x: &LinExpr| -> LinExpr {
4198        let mut out = x.clone();
4199        for (d, v) in &solved {
4200            if let Some(c) = out.coefficients.remove(d) {
4201                out = out.add(&v.scale(&c));
4202            }
4203        }
4204        out
4205    };
4206    let low = substitute(&e.add(&konst(-1)));
4207    let high = substitute(&len_var(*arr).sub(&e));
4208    let system: Vec<Constraint> = system
4209        .iter()
4210        .map(|c| Constraint {
4211            expr: substitute(&c.expr),
4212            strict: c.strict,
4213        })
4214        .filter(|c| !c.expr.coefficients.is_empty() || !c.is_satisfied_constant())
4215        .collect();
4216
4217    // The constraints connected to the goals through shared variables.
4218    let mut reach: std::collections::BTreeSet<i64> = low.coefficients.keys().copied().collect();
4219    reach.extend(high.coefficients.keys().copied());
4220    let mut kept = vec![false; system.len()];
4221    loop {
4222        let mut grew = false;
4223        for (k, c) in system.iter().enumerate() {
4224            if kept[k] {
4225                continue;
4226            }
4227            if c.expr.coefficients.is_empty()
4228                || c.expr.coefficients.keys().any(|v| reach.contains(v))
4229            {
4230                kept[k] = true;
4231                reach.extend(c.expr.coefficients.keys().copied());
4232                grew = true;
4233            }
4234        }
4235        if !grew {
4236            break;
4237        }
4238    }
4239    let relevant: Vec<Constraint> = system
4240        .into_iter()
4241        .zip(kept)
4242        .filter_map(|(c, k)| k.then_some(c))
4243        .collect();
4244    if relevant.len() > KARR_MAX_CONSTRAINTS || reach.len() > KARR_MAX_VARS {
4245        return;
4246    }
4247    if consistent(&relevant) && prove(&relevant, &low) && prove(&relevant, &high) {
4248        facts.relational_inbounds.insert(key);
4249    }
4250}
4251
4252/// The most constraints the equality proof hands Fourier-Motzkin for one access.
4253const KARR_MAX_CONSTRAINTS: usize = 48;
4254
4255/// The most variables the equality proof's system may hold for one access.
4256const KARR_MAX_VARS: usize = 12;
4257
4258/// Discharge `1 <= E <= length(arr)` for a single access via the kernel LIA
4259/// prover, recording the index address on success.
4260fn try_prove_affine(
4261    collection: &Expr,
4262    index: &Expr,
4263    body: &[Stmt],
4264    state: &RichAbstractState,
4265    clobbered: &std::collections::HashSet<Symbol>,
4266    mutated: &std::collections::HashSet<Symbol>,
4267    amb: &AffineFacts,
4268    facts: &mut OracleFacts,
4269) {
4270    use super::affine::{ge, konst, le, lin_of, prove, var};
4271    let Expr::Identifier(arr) = collection else {
4272        return;
4273    };
4274    if clobbered.contains(arr) {
4275        return;
4276    }
4277    let key = index as *const Expr as usize;
4278    if facts.relational_inbounds.contains(&key) {
4279        return; // already proven (single-var path or a prior visit)
4280    }
4281    let Some(e_lin) = lin_of(index) else { return };
4282    let Some((len_lb, len_syms)) = affine_length_lb(*arr, state) else {
4283        return;
4284    };
4285
4286    let mut system = amb.constraints.clone();
4287    let mut syms = amb.syms.clone();
4288    affine_collect_syms(index, &mut syms);
4289    for s in len_syms {
4290        if !syms.contains(&s) {
4291            syms.push(s);
4292        }
4293    }
4294    for &s in &syms {
4295        // Affine scalar definition `s = E` (relates a length var to a loop
4296        // bound: `cols = capacity + 1`).
4297        if let Some(def) = state.scalar_def.get(&s) {
4298            let sv = var(s);
4299            system.push(le(&sv, def));
4300            system.push(le(def, &sv));
4301        }
4302        // Loop-invariant scalar's interval bounds (the element bound `wi ∈
4303        // [1,50]` reached through `Let wi be item _ of weights`). A MUTATED
4304        // variable's raw header interval is NOT sound mid-body — those get
4305        // bounds only from guards / monotone-IV lowers.
4306        if !mutated.contains(&s) {
4307            let iv = state.intervals.get_var(&s);
4308            if let Bound::Finite(lo) = iv.lo {
4309                system.push(le(&konst(lo), &var(s)));
4310            }
4311            if let Bound::Finite(hi) = iv.hi {
4312                system.push(le(&var(s), &konst(hi)));
4313            }
4314        }
4315        // Symbolic element-source UPPER bound: a scalar read from a `% n`-filled
4316        // array carries `s <= n - 1` — the variable-divisor relation no concrete
4317        // `Interval` can hold (`n` is symbolic). Unlike the raw header interval
4318        // above this is sound for a MUTATED `s`: the in-body `Let u be item _ of
4319        // adj` re-establishes it every iteration, so EACH value of `u` (not just
4320        // the entry one) satisfies it. The bound's own variables (`n`) reach the
4321        // system through the length lower bound that put them in `syms`.
4322        // The element LOWER bound (`u >= 0` for an element of a `% n`-filled
4323        // array) joins the BASE system: it holds regardless of the divisor's
4324        // sign (`X % n` of a non-negative dividend is `>= 0` for any `n != 0`),
4325        // so it needs NO positivity guard. Sound for a MUTATED `s`: a value
4326        // re-read from a fixed array each iteration lands in its proven range.
4327        if let Some(l) = state.scalar_lower.get(&s) {
4328            system.push(le(l, &var(s)));
4329        }
4330    }
4331
4332    // Entry-guarded function's precondition (`lo>=1`, `hi>=1`): a FUNCTION-WIDE
4333    // ambient fact, injected into every proof regardless of the per-state widening
4334    // that drops the header interval in the swap's recording pass. Enforced by the
4335    // `codegen::entry_guard` `assert!` at runtime, so sound at every access past the
4336    // base-case guard. This is what discharges `1 <= i,j` for the partition swap.
4337    for &(s, lb) in &state.entry_guard_lowers {
4338        system.push(le(&konst(lb), &var(s)));
4339    }
4340
4341    // Derived bounds for a conditionally-assigned index variable — a heap sift's
4342    // `swapIdx` (`Set swapIdx to root | child | child+1`) has no `scalar_def` and is
4343    // no loop IV, so nothing above bounds it. Add `s >= 0` (co-induction: every value
4344    // assigned to it is `>= 0`, grounded by the seeded counter lowers) and `s <=
4345    // <len-bound-sym>` (each assignment proven `<= end` under its path guards), both
4346    // SOUND, closing its `[0, end] ⊆ [0, len)` accesses. `base_system`
4347    // (pre-augmentation) is the fixed premise set for the upper proof — non-circular.
4348    let base_system = system.clone();
4349    let bound_sym = state.length_def.get(arr).map(|(b, _)| *b);
4350    for &s in &syms {
4351        if !mutated.contains(&s) || state.scalar_def.contains_key(&s) {
4352            continue;
4353        }
4354        let assumed = std::collections::HashSet::new();
4355        if sym_ge_lo(s, 0, body, state, mutated, &assumed, 64) {
4356            system.push(ge(&var(s), &konst(0)));
4357        }
4358        if let Some(b) = bound_sym {
4359            if s != b && sym_le_sym(s, b, body, &base_system, state) {
4360                system.push(le(&var(s), &var(b)));
4361            }
4362        }
4363    }
4364
4365    // Defensive: a contradictory fact set proves any goal. Never elide from
4366    // inconsistency — if a stale/false hypothesis poisoned the system, refuse.
4367    if !super::affine::consistent(&system) {
4368        return;
4369    }
4370    // 1-based bounds: lower `E - 1 >= 0` (E >= 1), upper `len_lb - E >= 0`.
4371    let lower = e_lin.add(&konst(-1));
4372    let upper = len_lb.sub(&e_lin);
4373    if !prove(&system, &lower) {
4374        return;
4375    }
4376    // A purely AFFINE upper carries no positivity obligation — try it first.
4377    if prove(&system, &upper) {
4378        facts.relational_inbounds.insert(key);
4379        return;
4380    }
4381    // The upper needs the symbolic element UPPER `u <= m - 1` (the variable-
4382    // divisor modulo bound a concrete interval cannot hold). Adding it closes
4383    // the proof under `m >= 1`; record the `% m` divisors so codegen discharges
4384    // that precondition with a nonemptiness-guarded `assert!(m > 0)`, keeping
4385    // the lenient symbolic element join sound for every input.
4386    let mut mod_divisors: Vec<Symbol> = Vec::new();
4387    for &s in &syms {
4388        if let Some(u) = state.scalar_upper.get(&s) {
4389            system.push(le(&var(s), u));
4390            if let Some(m) = mod_upper_divisor(u) {
4391                mod_divisors.push(m);
4392            }
4393        }
4394    }
4395    if super::affine::consistent(&system) && prove(&system, &upper) {
4396        facts.relational_inbounds.insert(key);
4397        if !mod_divisors.is_empty() {
4398            facts
4399                .positivity_guards
4400                .entry(key)
4401                .or_default()
4402                .extend(mod_divisors);
4403        }
4404    }
4405}
4406
4407/// Discharge `0 <= key <= capacity(map)` for one access on a `Map of Int to Int`
4408/// proven dense-eligible, via the SAME kernel LIA prover as `try_prove_affine`.
4409/// The map's capacity is an invariant affine expression captured at its
4410/// declaration (`facts.map_caps`); proving both bounds means a direct-addressed
4411/// array of `capacity + 1` slots indexes every key safely at offset 0
4412/// (`data[key]`), since `key ∈ [0, capacity]`. Records the key address on success;
4413/// the dense gate fires for a map only when EVERY key site is recorded for it.
4414fn try_prove_dense_key(
4415    map: Symbol,
4416    key: &Expr,
4417    state: &RichAbstractState,
4418    mutated: &std::collections::HashSet<Symbol>,
4419    amb: &AffineFacts,
4420    facts: &mut OracleFacts,
4421) {
4422    use super::affine::{consistent, konst, le, lin_of, prove, var};
4423    let key_addr = key as *const Expr as usize;
4424    if facts.dense_map_key_proven.contains_key(&key_addr) {
4425        return;
4426    }
4427    let Some(cap) = facts.map_caps.get(&map).cloned() else {
4428        return;
4429    };
4430    let Some(k_lin) = lin_of(key) else { return };
4431
4432    // Mirror `try_prove_affine`'s system: ambient loop/path guards plus each
4433    // mentioned symbol's sound scalar facts. Collection is TRANSITIVE over the
4434    // scalar-definition and symbolic-bound chains, so an element-derived key
4435    // (`complement = target - x`, `x = item i of arr`) pulls in `target`'s
4436    // definition (`= n`) and `x`'s symbolic element bounds (`0 <= x <= n-1`) —
4437    // closing `0 <= complement <= n`. Each added fact is individually sound, so
4438    // the (consistency-guarded) system only ever proves MORE, never unsoundly.
4439    let mut system = amb.constraints.clone();
4440    let mut syms = amb.syms.clone();
4441    affine_collect_syms(key, &mut syms);
4442    let mut reached: std::collections::HashSet<Symbol> = syms.iter().copied().collect();
4443    let mut w = 0;
4444    while w < syms.len() {
4445        let s = syms[w];
4446        w += 1;
4447        for chained in [
4448            state.scalar_def.get(&s),
4449            state.scalar_upper.get(&s),
4450            state.scalar_lower.get(&s),
4451        ] {
4452            if let Some(e) = chained {
4453                for &idx in e.coefficients.keys() {
4454                    let t = Symbol::from_index(idx as usize);
4455                    if reached.insert(t) {
4456                        syms.push(t);
4457                    }
4458                }
4459            }
4460        }
4461    }
4462    for &s in &syms {
4463        if let Some(def) = state.scalar_def.get(&s) {
4464            let sv = var(s);
4465            system.push(le(&sv, def));
4466            system.push(le(def, &sv));
4467        }
4468        if !mutated.contains(&s) {
4469            let iv = state.intervals.get_var(&s);
4470            if let Bound::Finite(lo) = iv.lo {
4471                system.push(le(&konst(lo), &var(s)));
4472            }
4473            if let Bound::Finite(hi) = iv.hi {
4474                system.push(le(&var(s), &konst(hi)));
4475            }
4476        }
4477        if let Some(l) = state.scalar_lower.get(&s) {
4478            system.push(le(l, &var(s)));
4479        }
4480        if let Some(u) = state.scalar_upper.get(&s) {
4481            system.push(le(&var(s), u));
4482        }
4483    }
4484
4485    // Never elide from an inconsistent system (a false hypothesis proves anything).
4486    if !consistent(&system) {
4487        return;
4488    }
4489    // Lower `key >= 0` and upper `capacity - key >= 0`.
4490    if prove(&system, &k_lin) && prove(&system, &cap.sub(&k_lin)) {
4491        facts.dense_map_key_proven.insert(key_addr, map);
4492        // Presence elision: if the map's inserts fully cover `[A, B]`, prove this
4493        // key is also inside `[A, B]` — then it was definitely written, so `get`
4494        // needs no presence check. `A <= key` and `key <= B`.
4495        if let Some((a, b)) = facts.map_insert_cover.get(&map).cloned() {
4496            if prove(&system, &k_lin.sub(&a)) && prove(&system, &b.sub(&k_lin)) {
4497                facts.map_key_covered.insert(key_addr, map);
4498            }
4499        }
4500    }
4501}
4502
4503/// Collect upper-bound induction guards from a loop condition, descending
4504/// through `and`: `iv </<= B` and the flipped `B >/>= iv`, where `B` is
4505/// `length of arr` or a plain variable. `iv`'s lower bound must be a known
4506/// constant (its loop-start value).
4507fn collect_iv_guards(cond: &Expr, state: &RichAbstractState, out: &mut Vec<IvGuard>) {
4508    match cond {
4509        Expr::BinaryOp {
4510            op: BinaryOpKind::And,
4511            left,
4512            right,
4513        } => {
4514            collect_iv_guards(left, state, out);
4515            collect_iv_guards(right, state, out);
4516        }
4517        Expr::BinaryOp { op, left, right } => {
4518            let (iv_e, bnd_e, strict): (&Expr, &Expr, bool) = match op {
4519                BinaryOpKind::Lt => (*left, *right, true),
4520                BinaryOpKind::LtEq => (*left, *right, false),
4521                BinaryOpKind::Gt => (*right, *left, true),
4522                BinaryOpKind::GtEq => (*right, *left, false),
4523                _ => return,
4524            };
4525            let Expr::Identifier(iv) = iv_e else { return };
4526            // A non-constant start (e.g. an induction var seeded from a
4527            // parameter) gives no static lower bound — `i64::MIN` makes the
4528            // STATIC proof fail closed, while the SPECULATIVE hoist (which
4529            // checks the lower bound at runtime) still collects the guard.
4530            let iv_lo = match state.intervals.get_var(iv).lo {
4531                Bound::Finite(lo) => lo,
4532                _ => i64::MIN,
4533            };
4534            let bound = match bnd_e {
4535                Expr::Length { collection } => match &**collection {
4536                    Expr::Identifier(arr) => IvBound::LenOf(*arr),
4537                    _ => return,
4538                },
4539                Expr::Identifier(v) => IvBound::Var {
4540                    var: *v,
4541                    headroom: 0,
4542                },
4543                // `n - t1 - t2 - …` with each subtracted term provably ≥ 0.
4544                _ => match var_minus_bound(bnd_e, state) {
4545                    Some((v, headroom)) => IvBound::Var { var: v, headroom },
4546                    None => return,
4547                },
4548            };
4549            out.push(IvGuard {
4550                iv: *iv,
4551                bound,
4552                strict,
4553                iv_lo,
4554            });
4555        }
4556        _ => {}
4557    }
4558}
4559
4560/// Recognize a bound expression `n - t1 - t2 - …` rooted at a variable `n`,
4561/// where every subtracted term is provably `>= 0`. Returns `(n, headroom)`
4562/// with `headroom = Σ lower-bounds of the subtracted terms` — a sound lower
4563/// bound on `n - bound`, i.e. how far the guard keeps `iv` below `n`.
4564fn var_minus_bound(b: &Expr, state: &RichAbstractState) -> Option<(Symbol, i64)> {
4565    match b {
4566        Expr::Identifier(v) => Some((*v, 0)),
4567        Expr::BinaryOp {
4568            op: BinaryOpKind::Subtract,
4569            left,
4570            right,
4571        } => {
4572            let (v, head) = var_minus_bound(left, state)?;
4573            // The subtracted term must be provably non-negative (else `n -
4574            // term` could exceed `n` and the bound would be unsound).
4575            let r_lo = match eval_expr(right, &state.intervals).lo {
4576                Bound::Finite(lo) => lo,
4577                _ => return None,
4578            };
4579            if r_lo < 0 {
4580                return None;
4581            }
4582            Some((v, head.saturating_add(r_lo)))
4583        }
4584        _ => None,
4585    }
4586}
4587
4588/// Extract `(var, offset)` from an affine index expression: `v`, `v + k`,
4589/// `k + v`, or `v - k` (`k` an integer literal).
4590fn affine_of(e: &Expr) -> Option<(Symbol, i64)> {
4591    match e {
4592        Expr::Identifier(s) => Some((*s, 0)),
4593        Expr::BinaryOp {
4594            op: BinaryOpKind::Add,
4595            left,
4596            right,
4597        } => match (&**left, &**right) {
4598            (Expr::Identifier(s), Expr::Literal(Literal::Number(k))) => Some((*s, *k)),
4599            (Expr::Literal(Literal::Number(k)), Expr::Identifier(s)) => Some((*s, *k)),
4600            _ => None,
4601        },
4602        Expr::BinaryOp {
4603            op: BinaryOpKind::Subtract,
4604            left,
4605            right,
4606        } => match (&**left, &**right) {
4607            (Expr::Identifier(s), Expr::Literal(Literal::Number(k))) => Some((*s, -*k)),
4608            _ => None,
4609        },
4610        _ => None,
4611    }
4612}
4613
4614/// If `collection` is an array and `index` is affine in a live guard's
4615/// induction variable that proves it in bounds, record the index's address
4616/// as proven (consumed by the bytecode compiler for both `IndexUnchecked`
4617/// reads and `SetIndexUnchecked` stores).
4618fn try_record_index(
4619    collection: &Expr,
4620    index: &Expr,
4621    guards: &[IvGuard],
4622    length_def: &HashMap<Symbol, (Symbol, i64)>,
4623    clobbered: &std::collections::HashSet<Symbol>,
4624    facts: &mut OracleFacts,
4625) {
4626    let Expr::Identifier(arr) = collection else {
4627        return;
4628    };
4629    if clobbered.contains(arr) {
4630        return;
4631    }
4632    let Some((iv, k)) = affine_of(index) else {
4633        return;
4634    };
4635    let proven = guards
4636        .iter()
4637        .any(|g| g.iv == iv && !clobbered.contains(&g.iv) && guard_proves(g, *arr, k, length_def));
4638    if proven {
4639        facts
4640            .relational_inbounds
4641            .insert(index as *const Expr as usize);
4642    }
4643}
4644
4645/// Does guard `g` prove `1 <= (iv + k) <= length(arr)` for an access on
4646/// `arr` with affine offset `k`?
4647fn guard_proves(
4648    g: &IvGuard,
4649    arr: Symbol,
4650    k: i64,
4651    length_def: &HashMap<Symbol, (Symbol, i64)>,
4652) -> bool {
4653    // Lower bound: iv >= iv_lo ⇒ index = iv + k >= iv_lo + k, need >= 1.
4654    if g.iv_lo.saturating_add(k) < 1 {
4655        return false;
4656    }
4657    // Upper bound: index_max = iv_max + k, where iv_max = bound - (strict?1:0).
4658    let slack = if g.strict { 1 } else { 0 };
4659    match &g.bound {
4660        // bound == length(arr): need index_max <= bound ⇒ k - slack <= 0.
4661        IvBound::LenOf(g_arr) => *g_arr == arr && k - slack <= 0,
4662        // bound == n - headroom, length(arr) >= n + off: iv_max = n - headroom
4663        // - slack, so index_max = iv_max + k; need <= n + off
4664        // ⇒ k - slack - headroom <= off.
4665        IvBound::Var { var, headroom } => match length_def.get(&arr) {
4666            Some((n, off)) => *n == *var && k - slack - headroom <= *off,
4667            None => false,
4668        },
4669    }
4670}
4671
4672/// True if `sym` is rebound (target of `Set`/`Let`) anywhere in `body`.
4673fn var_rebound_in(sym: Symbol, body: &[Stmt]) -> bool {
4674    body.iter().any(|s| match s {
4675        Stmt::Set { target, .. } => *target == sym,
4676        Stmt::Let { var, .. } => *var == sym,
4677        Stmt::If {
4678            then_block,
4679            else_block,
4680            ..
4681        } => {
4682            var_rebound_in(sym, then_block)
4683                || matches!(else_block, Some(eb) if var_rebound_in(sym, eb))
4684        }
4685        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => var_rebound_in(sym, body),
4686        _ => false,
4687    })
4688}
4689
4690/// `value` is `iv + c` or `c + iv` with `c` a literal `>= 1`.
4691fn is_positive_increment(value: &Expr, iv: Symbol) -> bool {
4692    if let Expr::BinaryOp {
4693        op: BinaryOpKind::Add,
4694        left,
4695        right,
4696    } = value
4697    {
4698        let is_iv = |e: &Expr| matches!(e, Expr::Identifier(s) if *s == iv);
4699        let amt = match (&**left, &**right) {
4700            (l, Expr::Literal(Literal::Number(c))) if is_iv(l) => Some(*c),
4701            (Expr::Literal(Literal::Number(c)), r) if is_iv(r) => Some(*c),
4702            _ => None,
4703        };
4704        return amt.is_some_and(|c| c >= 1);
4705    }
4706    false
4707}
4708
4709/// The loop's LAST top-level statement is `iv = iv + c` (c >= 1) and `iv` is
4710/// written NOWHERE else. Then every access before it sees the un-incremented
4711/// `iv`, so no per-access clobber tracking is needed and the induction is
4712/// monotone — the cleanest sound shape for region-entry hoisting.
4713fn iv_increment_is_last(iv: Symbol, body: &[Stmt]) -> bool {
4714    let Some((last, rest)) = body.split_last() else {
4715        return false;
4716    };
4717    let last_is_inc = matches!(last, Stmt::Set { target, value }
4718        if *target == iv && is_positive_increment(value, iv));
4719    last_is_inc && !var_rebound_in(iv, rest)
4720}
4721
4722/// Record a single covered store/read `item (iv+k) of arr` as speculatively
4723/// in bounds and fold its offset into the per-array `(kmin, kmax)`.
4724fn consider_hoist_access(
4725    collection: &Expr,
4726    index: &Expr,
4727    iv: Symbol,
4728    state: &RichAbstractState,
4729    body: &[Stmt],
4730    facts: &mut OracleFacts,
4731    per_array: &mut HashMap<Symbol, (i64, i64)>,
4732) {
4733    let Expr::Identifier(arr) = collection else {
4734        return;
4735    };
4736    // The array must be a proven collection, stable (never rebound, never
4737    // resized — a realloc would stale the pinned pointer), and the index
4738    // affine in THIS loop's induction variable.
4739    if !state.coll_vars.contains(arr) || var_rebound_in(*arr, body) || array_resized_in(*arr, body)
4740    {
4741        return;
4742    }
4743    // Speculate ONLY on a function-PARAMETER collection — its length is
4744    // fundamentally unknown, so a region-entry runtime check is the right
4745    // tool. A locally-built array has a statically determinable length and is
4746    // left to the static path (speculating there would only ever deopt).
4747    if !state.param_colls.contains(arr) {
4748        return;
4749    }
4750    let Some((aiv, k)) = affine_of(index) else {
4751        return;
4752    };
4753    if aiv != iv {
4754        return;
4755    }
4756    let key = index as *const Expr as usize;
4757    if facts.relational_inbounds.contains(&key) {
4758        return; // already proven statically — no runtime guard needed
4759    }
4760    facts.speculative_inbounds.insert(key);
4761    let entry = per_array.entry(*arr).or_insert((k, k));
4762    entry.0 = entry.0.min(k);
4763    entry.1 = entry.1.max(k);
4764}
4765
4766/// Walk statements (and their expressions) collecting covered hoist accesses.
4767fn walk_hoist_accesses(
4768    stmts: &[Stmt],
4769    iv: Symbol,
4770    state: &RichAbstractState,
4771    body: &[Stmt],
4772    facts: &mut OracleFacts,
4773    per_array: &mut HashMap<Symbol, (i64, i64)>,
4774) {
4775    for s in stmts {
4776        for_each_direct_expr(s, &mut |e| {
4777            walk_hoist_in_expr(e, iv, state, body, facts, per_array)
4778        });
4779        if let Stmt::SetIndex {
4780            collection, index, ..
4781        } = s
4782        {
4783            consider_hoist_access(collection, index, iv, state, body, facts, per_array);
4784        }
4785        match s {
4786            Stmt::If {
4787                then_block,
4788                else_block,
4789                ..
4790            } => {
4791                walk_hoist_accesses(then_block, iv, state, body, facts, per_array);
4792                if let Some(eb) = else_block {
4793                    walk_hoist_accesses(eb, iv, state, body, facts, per_array);
4794                }
4795            }
4796            Stmt::While { body: b, .. } | Stmt::Repeat { body: b, .. } => {
4797                walk_hoist_accesses(b, iv, state, body, facts, per_array);
4798            }
4799            _ => {}
4800        }
4801    }
4802}
4803
4804/// Find `item (iv+k) of arr` reads anywhere in an expression tree.
4805fn walk_hoist_in_expr(
4806    e: &Expr,
4807    iv: Symbol,
4808    state: &RichAbstractState,
4809    body: &[Stmt],
4810    facts: &mut OracleFacts,
4811    per_array: &mut HashMap<Symbol, (i64, i64)>,
4812) {
4813    use crate::ast::stmt::StringPart;
4814    if let Expr::Index { collection, index } = e {
4815        consider_hoist_access(collection, index, iv, state, body, facts, per_array);
4816    }
4817    let mut go = |x: &Expr| walk_hoist_in_expr(x, iv, state, body, facts, per_array);
4818    match e {
4819        Expr::BinaryOp { left, right, .. }
4820        | Expr::Union { left, right }
4821        | Expr::Intersection { left, right }
4822        | Expr::Range {
4823            start: left,
4824            end: right,
4825        } => {
4826            go(left);
4827            go(right);
4828        }
4829        Expr::Not { operand } => go(operand),
4830        Expr::Call { args, .. } => args.iter().for_each(|a| go(a)),
4831        Expr::CallExpr { callee, args } => {
4832            go(callee);
4833            args.iter().for_each(|a| go(a));
4834        }
4835        Expr::Index { collection, index } => {
4836            go(collection);
4837            go(index);
4838        }
4839        Expr::Slice {
4840            collection,
4841            start,
4842            end,
4843        } => {
4844            go(collection);
4845            go(start);
4846            go(end);
4847        }
4848        Expr::Copy { expr } => go(expr),
4849        Expr::Give { value } => go(value),
4850        Expr::Length { collection } => go(collection),
4851        Expr::Contains { collection, value } => {
4852            go(collection);
4853            go(value);
4854        }
4855        Expr::List(items) | Expr::Tuple(items) => items.iter().for_each(|i| go(i)),
4856        Expr::FieldAccess { object, .. } => go(object),
4857        Expr::New { init_fields, .. } => init_fields.iter().for_each(|(_, fe)| go(fe)),
4858        Expr::NewVariant { fields, .. } => fields.iter().for_each(|(_, fe)| go(fe)),
4859        Expr::OptionSome { value } => go(value),
4860        Expr::WithCapacity { value, capacity } => {
4861            go(value);
4862            go(capacity);
4863        }
4864        Expr::InterpolatedString(parts) => {
4865            for p in parts {
4866                if let StringPart::Expr { value, .. } = p {
4867                    go(value);
4868                }
4869            }
4870        }
4871        _ => {}
4872    }
4873}
4874
4875/// One region-entry guard per array a hoisted loop reads, from the covered offsets `(kmin, kmax)` of each,
4876/// ordered by the array's symbol: the guards the compiler emits are a function of the loop, whatever order
4877/// the accesses were collected in.
4878fn hoist_descs(
4879    per_array: impl IntoIterator<Item = (Symbol, (i64, i64))>,
4880    bound: Symbol,
4881    iv: Symbol,
4882    strict: i64,
4883) -> Vec<HoistDesc> {
4884    let mut descs: Vec<HoistDesc> = per_array
4885        .into_iter()
4886        .filter_map(|(array, (kmin, kmax))| {
4887            Some(HoistDesc {
4888                array,
4889                bound,
4890                iv,
4891                add_max: i32::try_from(kmax - strict).ok()?,
4892                add_min: i32::try_from(kmin).ok()?,
4893            })
4894        })
4895        .collect();
4896    descs.sort_by_key(|d| d.array);
4897    descs
4898}
4899
4900/// SPECULATIVE region-entry hoist (V8 loop bound-check elimination): when a
4901/// loop's array length is not statically provable (e.g. a function parameter)
4902/// but the induction is monotone, the bound loop-invariant, and the array
4903/// stable, record the covered `item (iv+k) of arr` accesses as in-bounds and
4904/// emit one descriptor per array — justified at runtime by a single
4905/// region-entry check (`RegionBoundsGuard`), which the VM verifies before
4906/// entering native code (declining the region, and so the elision, on miss).
4907fn record_hoist_speculation(
4908    cond: &Expr,
4909    body: &[Stmt],
4910    state: &RichAbstractState,
4911    facts: &mut OracleFacts,
4912    loop_key: usize,
4913) {
4914    // Same body restriction as static elision: no resize, no call, nothing
4915    // unmodeled (any of which could change the array's length).
4916    if !body_is_index_proof_safe(body) {
4917        return;
4918    }
4919    let mut guards: Vec<IvGuard> = Vec::new();
4920    collect_iv_guards(cond, state, &mut guards);
4921    // One plain-variable guard `iv </<= bound`, bound loop-invariant, the
4922    // increment last (so monotone, no clobber tracking needed).
4923    let Some(g) = guards.iter().find(|g| {
4924        matches!(g.bound, IvBound::Var { headroom: 0, var } if !var_rebound_in(var, body))
4925            && iv_increment_is_last(g.iv, body)
4926    }) else {
4927        return;
4928    };
4929    let IvBound::Var { var: bound, .. } = g.bound else {
4930        return;
4931    };
4932    if bound == g.iv {
4933        return;
4934    }
4935    let mut per_array: HashMap<Symbol, (i64, i64)> = HashMap::new();
4936    walk_hoist_accesses(body, g.iv, state, body, facts, &mut per_array);
4937    if per_array.is_empty() {
4938        return;
4939    }
4940    let strict = if g.strict { 1 } else { 0 };
4941    let descs = hoist_descs(per_array, bound, g.iv, strict);
4942    if !descs.is_empty() {
4943        facts.hoist_descs.entry(loop_key).or_default().extend(descs);
4944    }
4945}
4946
4947/// The length fact a counted build loop establishes for the array it fills.
4948enum BuildLength {
4949    /// Variable bound: `length(arr) >= n + off`.
4950    Symbolic(Symbol, Symbol, i64),
4951    /// Literal bound: `length(arr)` lies in the interval — exact when the array's
4952    /// entry length is (the interval check then proves reads directly).
4953    Concrete(Symbol, Interval),
4954}
4955
4956/// Recognize a counted build loop `while c </<= B: <fill arr once per
4957/// iteration>`, where `B` is a variable (→ a symbolic length lower bound) or an
4958/// integer literal (→ a concrete length) — the standard allocation-size fact.
4959/// The loop appends one item per trip to whatever the array held at entry, so a
4960/// table seeded before its fill loop (`Push 1 to dp`, then `n` zeros) ends with
4961/// its seed counted in. Strict by construction: the body is flat with exactly
4962/// one `push to arr`, exactly one `c := c + 1`, `c` starting at a known
4963/// constant, and nothing else that resizes a collection or branches (a
4964/// conditional push would make the length too small).
4965fn infer_build_length(cond: &Expr, body: &[Stmt], entry: &RichAbstractState) -> Vec<BuildLength> {
4966    let (c_e, b_e, strict) = match cond {
4967        Expr::BinaryOp { op, left, right } => {
4968            let (l, r) = (&**left, &**right);
4969            match op {
4970                BinaryOpKind::Lt => (l, r, true),
4971                BinaryOpKind::LtEq => (l, r, false),
4972                _ => return Vec::new(),
4973            }
4974        }
4975        _ => return Vec::new(),
4976    };
4977    let Expr::Identifier(c) = c_e else {
4978        return Vec::new();
4979    };
4980    let c = *c;
4981    // The bound is a variable (symbolic) or an integer literal (concrete).
4982    let bound_var = match b_e {
4983        Expr::Identifier(n) => Some(*n),
4984        Expr::Literal(Literal::Number(_)) => None,
4985        _ => return Vec::new(),
4986    };
4987    if bound_var == Some(c) {
4988        return Vec::new();
4989    }
4990    // c starts at a known constant c0 at loop entry.
4991    let iv = entry.intervals.get_var(&c);
4992    let c0 = match (iv.lo, iv.hi) {
4993        (Bound::Finite(lo), Bound::Finite(hi)) if lo == hi => lo,
4994        _ => return Vec::new(),
4995    };
4996    // Pushes PER ARRAY: a MULTI-array build loop (graph_bfs's `Push adjStarts;
4997    // Push adjCounts; Push adj x5`) gives every array pushed EXACTLY once a
4998    // length equal to the trip count. An array pushed `K > 1` times has length
4999    // `K * n`, which `length_def`'s `(var, off)` form cannot hold, so it is
5000    // skipped (no false length fact). The body is still otherwise restricted to
5001    // pushes + the single increment — a branch or call undercounts.
5002    let mut push_counts: HashMap<Symbol, u32> = HashMap::new();
5003    let mut increments = 0;
5004    for s in body {
5005        match s {
5006            Stmt::Push { collection, .. } => {
5007                let Expr::Identifier(a) = &**collection else {
5008                    return Vec::new();
5009                };
5010                *push_counts.entry(*a).or_insert(0) += 1;
5011            }
5012            Stmt::Set { target, value } => {
5013                if *target == c {
5014                    if !is_increment_by_one(value, c) {
5015                        return Vec::new();
5016                    }
5017                    increments += 1;
5018                } else if bound_var == Some(*target) {
5019                    return Vec::new(); // the bound is mutated inside the loop
5020                }
5021            }
5022            Stmt::Let { var, .. } => {
5023                if *var == c || bound_var == Some(*var) {
5024                    return Vec::new();
5025                }
5026            }
5027            // Anything that could resize the array, branch (a conditional
5028            // push undercounts), or call out disqualifies the inference.
5029            Stmt::Show { .. }
5030            | Stmt::RuntimeAssert { .. }
5031            | Stmt::Assert { .. }
5032            | Stmt::Trust { .. } => {}
5033            _ => return Vec::new(),
5034        }
5035    }
5036    if increments != 1 {
5037        return Vec::new();
5038    }
5039    // trip count = B - c0 (for `<`) or B - c0 + 1 (for `<=`).
5040    let off = if strict { -c0 } else { -c0 + 1 };
5041    // Deterministic order (HashMap iteration is not) — sort by dense index.
5042    let mut arrays: Vec<(Symbol, u32)> = push_counts.into_iter().collect();
5043    arrays.sort_by_key(|(a, _)| a.index());
5044    let mut out = Vec::new();
5045    for (arr, count) in arrays {
5046        if count != 1 || arr == c || bound_var == Some(arr) {
5047            continue;
5048        }
5049        // The items the array holds at loop entry stay; the loop appends after
5050        // them. The symbolic fact is a LOWER bound, so it takes the entry
5051        // length's lower end, and it holds for a zero-trip loop too: no trips
5052        // means `n + off <= 0`, so `n + off + seed <= seed <= length`.
5053        let entry_len = entry.intervals.get_length(&arr);
5054        let Bound::Finite(seed) = entry_len.lo else {
5055            continue;
5056        };
5057        match (bound_var, b_e) {
5058            (Some(n), _) => {
5059                if let Some(total) = off.checked_add(seed) {
5060                    out.push(BuildLength::Symbolic(arr, n, total));
5061                }
5062            }
5063            (None, Expr::Literal(Literal::Number(bn))) => {
5064                if let Some(trips) = bn.checked_add(off) {
5065                    let filled = Interval::exact(trips.max(0)).add(&entry_len);
5066                    out.push(BuildLength::Concrete(arr, filled));
5067                }
5068            }
5069            _ => {}
5070        }
5071    }
5072    out
5073}
5074
5075/// `value` is exactly `c + 1` or `1 + c`.
5076fn is_increment_by_one(value: &Expr, c: Symbol) -> bool {
5077    if let Expr::BinaryOp {
5078        op: BinaryOpKind::Add,
5079        left,
5080        right,
5081    } = value
5082    {
5083        let is_c = |e: &Expr| matches!(e, Expr::Identifier(s) if *s == c);
5084        let is_one = |e: &Expr| matches!(e, Expr::Literal(Literal::Number(1)));
5085        return (is_c(&**left) && is_one(&**right)) || (is_one(&**left) && is_c(&**right));
5086    }
5087    false
5088}
5089
5090/// True when the loop body contains only statements the recognizer can
5091/// reason about. Resizes (`Push`/`Pop`/`Add`/`Remove`) ARE allowed — a read
5092/// on a stable array stays sound while a DIFFERENT array grows (the common
5093/// "build B from A" loop); the per-array `array_resized_in` check keeps the
5094/// resized array's own reads checked. A CALL (which could resize anything) or
5095/// an unmodeled statement still disqualifies.
5096fn body_is_index_proof_safe(body: &[Stmt]) -> bool {
5097    body.iter().all(|s| match s {
5098        Stmt::Let { .. }
5099        | Stmt::Set { .. }
5100        | Stmt::SetIndex { .. }
5101        | Stmt::Push { .. }
5102        | Stmt::Pop { .. }
5103        | Stmt::Add { .. }
5104        | Stmt::Remove { .. }
5105        | Stmt::Show { .. }
5106        | Stmt::Return { .. }
5107        | Stmt::Break
5108        | Stmt::RuntimeAssert { .. }
5109        | Stmt::Assert { .. }
5110        | Stmt::Trust { .. } => true,
5111        Stmt::If {
5112            then_block,
5113            else_block,
5114            ..
5115        } => {
5116            body_is_index_proof_safe(then_block)
5117                && match else_block {
5118                    Some(eb) => body_is_index_proof_safe(eb),
5119                    None => true,
5120                }
5121        }
5122        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => body_is_index_proof_safe(body),
5123        _ => false,
5124    })
5125}
5126
5127/// Collect every collection grown/shrunk anywhere in `body`. Reads on these
5128/// stay CHECKED: a resize can realloc the buffer, and the JIT region pins the
5129/// pointer/length once at entry.
5130/// Arrays whose length could DECREASE in the loop (so an `i <= length(arr)`
5131/// guard, checked at the top of each iteration, may no longer hold at a read).
5132/// GROW-only ops (`Push`/`Add`) leave the length monotonically non-decreasing,
5133/// so the guard keeps holding — those do NOT make an array unsafe. Only SHRINK
5134/// (`Pop`/`Remove`) and ALIASING (a second live handle that could itself be
5135/// shrunk) can drop the length below the guard.
5136fn collect_resized_arrays(body: &[Stmt], out: &mut std::collections::HashSet<Symbol>) {
5137    for s in body {
5138        match s {
5139            // Grow-only: length never decreases — the bound survives. NOT
5140            // clobbered (this is the relaxation that proves a growing FIFO's
5141            // own cursor reads, e.g. graph_bfs's queue).
5142            Stmt::Push { .. } | Stmt::Add { .. } => {}
5143            // Shrink: length can drop below the guard.
5144            Stmt::Remove { collection, .. } => {
5145                if let Expr::Identifier(c) = &**collection {
5146                    out.insert(*c);
5147                }
5148            }
5149            Stmt::Pop { collection, into } => {
5150                if let Expr::Identifier(c) = &**collection {
5151                    out.insert(*c);
5152                }
5153                if let Some(v) = into {
5154                    out.insert(*v);
5155                }
5156            }
5157            // Aliasing: `Let b be a` / `Set b to a` makes `b` a second handle
5158            // on `a`'s allocation; a later `Pop b` would shrink `a` without
5159            // naming it, so the source `a` is no longer provably grow-only.
5160            Stmt::Let { value, .. } | Stmt::Set { value, .. } => {
5161                if let Expr::Identifier(src) = &**value {
5162                    out.insert(*src);
5163                }
5164            }
5165            Stmt::If {
5166                then_block,
5167                else_block,
5168                ..
5169            } => {
5170                collect_resized_arrays(then_block, out);
5171                if let Some(eb) = else_block {
5172                    collect_resized_arrays(eb, out);
5173                }
5174            }
5175            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
5176                collect_resized_arrays(body, out);
5177            }
5178            _ => {}
5179        }
5180    }
5181}
5182
5183/// True if `sym` is grown or shrunk (`Push`/`Pop`/`Add`/`Remove`) anywhere in
5184/// `body` — its length is not loop-stable, so its reads stay checked.
5185fn array_resized_in(sym: Symbol, body: &[Stmt]) -> bool {
5186    let hits = |c: &Expr| matches!(c, Expr::Identifier(s) if *s == sym);
5187    body.iter().any(|s| match s {
5188        Stmt::Push { collection, .. }
5189        | Stmt::Add { collection, .. }
5190        | Stmt::Remove { collection, .. } => hits(collection),
5191        Stmt::Pop { collection, into } => hits(collection) || matches!(into, Some(v) if *v == sym),
5192        Stmt::If {
5193            then_block,
5194            else_block,
5195            ..
5196        } => {
5197            array_resized_in(sym, then_block)
5198                || matches!(else_block, Some(eb) if array_resized_in(sym, eb))
5199        }
5200        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => array_resized_in(sym, body),
5201        _ => false,
5202    })
5203}
5204
5205/// Walk the body in execution order, recording each proven `item i of arr`
5206/// read up to the point a guard variable is clobbered. A nested loop
5207/// pre-marks every variable it clobbers (it repeats, so a later-iteration
5208/// write reaches an earlier-source read); a `Repeat`'s reads are not
5209/// recorded (its pattern rebinds the iteration variable).
5210fn record_proven_reads(
5211    stmts: &[Stmt],
5212    guards: &[IvGuard],
5213    length_def: &HashMap<Symbol, (Symbol, i64)>,
5214    clobbered: &mut std::collections::HashSet<Symbol>,
5215    facts: &mut OracleFacts,
5216    globals: &CalleeGlobals,
5217) {
5218    for stmt in stmts {
5219        for_each_direct_expr(stmt, &mut |e| {
5220            record_index_reads(e, guards, length_def, clobbered, facts)
5221        });
5222        // A store `Set item E of arr to v` — prove the STORE index too (its
5223        // index is a direct expression, not an `Index` node a read walk sees).
5224        if let Stmt::SetIndex {
5225            collection, index, ..
5226        } = stmt
5227        {
5228            try_record_index(collection, index, guards, length_def, clobbered, facts);
5229        }
5230        match stmt {
5231            Stmt::If {
5232                then_block,
5233                else_block,
5234                ..
5235            } => {
5236                let mut c_then = clobbered.clone();
5237                record_proven_reads(then_block, guards, length_def, &mut c_then, facts, globals);
5238                let mut c_else = clobbered.clone();
5239                if let Some(eb) = else_block {
5240                    record_proven_reads(eb, guards, length_def, &mut c_else, facts, globals);
5241                }
5242                clobbered.extend(c_then);
5243                clobbered.extend(c_else);
5244            }
5245            Stmt::While { body, .. } => {
5246                let mut inner = clobbered.clone();
5247                for m in collect_mutations_in(body, globals) {
5248                    inner.insert(m);
5249                }
5250                record_proven_reads(body, guards, length_def, &mut inner.clone(), facts, globals);
5251                *clobbered = inner;
5252            }
5253            Stmt::Repeat { pattern, body, .. } => {
5254                if let Some(v) = pattern_loop_var(pattern) {
5255                    clobbered.insert(v);
5256                }
5257                for m in collect_mutations_in(body, globals) {
5258                    clobbered.insert(m);
5259                }
5260            }
5261            _ => {}
5262        }
5263        // Only a rebinding of a variable invalidates subsequent proofs — an
5264        // element store (`SetIndex`) leaves the length untouched.
5265        match stmt {
5266            Stmt::Set { target, .. } => {
5267                clobbered.insert(*target);
5268            }
5269            Stmt::Let { var, .. } => {
5270                clobbered.insert(*var);
5271            }
5272            _ => {}
5273        }
5274    }
5275}
5276
5277/// Apply `f` to each expression a statement evaluates directly (not those in
5278/// nested blocks — those are walked separately by `record_proven_reads`).
5279fn for_each_direct_expr(stmt: &Stmt, f: &mut impl FnMut(&Expr)) {
5280    match stmt {
5281        Stmt::Let { value, .. } | Stmt::Set { value, .. } => f(value),
5282        Stmt::SetIndex {
5283            collection,
5284            index,
5285            value,
5286        } => {
5287            f(collection);
5288            f(index);
5289            f(value);
5290        }
5291        Stmt::Show { object, .. } => f(object),
5292        // The pushed/added value is an expression that may read other arrays
5293        // (e.g. `Push item li of left to result` — the "build B from A" loop).
5294        Stmt::Push { value, .. } | Stmt::Add { value, .. } | Stmt::Remove { value, .. } => f(value),
5295        Stmt::Return { value: Some(v) } => f(v),
5296        Stmt::RuntimeAssert { condition, .. } => f(condition),
5297        Stmt::If { cond, .. } => f(cond),
5298        Stmt::While {
5299            cond, decreasing, ..
5300        } => {
5301            f(cond);
5302            if let Some(d) = decreasing {
5303                f(d);
5304            }
5305        }
5306        Stmt::Repeat { iterable, .. } => f(iterable),
5307        _ => {}
5308    }
5309}
5310
5311/// Walk `e`, recording the arena address of every `item E of arr` index
5312/// sub-expression a live guard proves in bounds (`E` affine in the guard's
5313/// induction variable, `arr` un-clobbered).
5314fn record_index_reads(
5315    e: &Expr,
5316    guards: &[IvGuard],
5317    length_def: &HashMap<Symbol, (Symbol, i64)>,
5318    clobbered: &std::collections::HashSet<Symbol>,
5319    facts: &mut OracleFacts,
5320) {
5321    use crate::ast::stmt::StringPart;
5322    if let Expr::Index { collection, index } = e {
5323        try_record_index(collection, index, guards, length_def, clobbered, facts);
5324    }
5325    match e {
5326        Expr::BinaryOp { left, right, .. }
5327        | Expr::Union { left, right }
5328        | Expr::Intersection { left, right }
5329        | Expr::Range {
5330            start: left,
5331            end: right,
5332        } => {
5333            record_index_reads(left, guards, length_def, clobbered, facts);
5334            record_index_reads(right, guards, length_def, clobbered, facts);
5335        }
5336        Expr::Not { operand } => record_index_reads(operand, guards, length_def, clobbered, facts),
5337        Expr::Call { args, .. } => {
5338            for a in args {
5339                record_index_reads(a, guards, length_def, clobbered, facts);
5340            }
5341        }
5342        Expr::CallExpr { callee, args } => {
5343            record_index_reads(callee, guards, length_def, clobbered, facts);
5344            for a in args {
5345                record_index_reads(a, guards, length_def, clobbered, facts);
5346            }
5347        }
5348        Expr::Index { collection, index } => {
5349            record_index_reads(collection, guards, length_def, clobbered, facts);
5350            record_index_reads(index, guards, length_def, clobbered, facts);
5351        }
5352        Expr::Slice {
5353            collection,
5354            start,
5355            end,
5356        } => {
5357            record_index_reads(collection, guards, length_def, clobbered, facts);
5358            record_index_reads(start, guards, length_def, clobbered, facts);
5359            record_index_reads(end, guards, length_def, clobbered, facts);
5360        }
5361        Expr::Copy { expr } => record_index_reads(expr, guards, length_def, clobbered, facts),
5362        Expr::Give { value } => record_index_reads(value, guards, length_def, clobbered, facts),
5363        Expr::Length { collection } => {
5364            record_index_reads(collection, guards, length_def, clobbered, facts)
5365        }
5366        Expr::Contains { collection, value } => {
5367            record_index_reads(collection, guards, length_def, clobbered, facts);
5368            record_index_reads(value, guards, length_def, clobbered, facts);
5369        }
5370        Expr::List(items) | Expr::Tuple(items) => {
5371            for it in items {
5372                record_index_reads(it, guards, length_def, clobbered, facts);
5373            }
5374        }
5375        Expr::FieldAccess { object, .. } => {
5376            record_index_reads(object, guards, length_def, clobbered, facts)
5377        }
5378        Expr::New { init_fields, .. } => {
5379            for (_, fe) in init_fields {
5380                record_index_reads(fe, guards, length_def, clobbered, facts);
5381            }
5382        }
5383        Expr::NewVariant { fields, .. } => {
5384            for (_, fe) in fields {
5385                record_index_reads(fe, guards, length_def, clobbered, facts);
5386            }
5387        }
5388        Expr::OptionSome { value } => {
5389            record_index_reads(value, guards, length_def, clobbered, facts)
5390        }
5391        Expr::WithCapacity { value, capacity } => {
5392            record_index_reads(value, guards, length_def, clobbered, facts);
5393            record_index_reads(capacity, guards, length_def, clobbered, facts);
5394        }
5395        Expr::InterpolatedString(parts) => {
5396            for p in parts {
5397                if let StringPart::Expr { value, .. } = p {
5398                    record_index_reads(value, guards, length_def, clobbered, facts);
5399                }
5400            }
5401        }
5402        _ => {}
5403    }
5404}
5405
5406/// EXODIA Phase 1 entry point: analyze a parsed program and return the
5407/// per-expression fact table (Main statements AND every function body,
5408/// seeded from declared parameter types).
5409/// Apply `f` to each child statement block of `s` that shares (or nests under)
5410/// its scope — used by the program-wide scans the dense-map gate needs.
5411fn each_child_block(s: &Stmt, f: &mut impl FnMut(&[Stmt])) {
5412    match s {
5413        Stmt::If {
5414            then_block,
5415            else_block,
5416            ..
5417        } => {
5418            f(then_block);
5419            if let Some(eb) = else_block {
5420                f(eb);
5421            }
5422        }
5423        Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => f(body),
5424        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => f(tasks),
5425        Stmt::Inspect { arms, .. } => {
5426            for a in arms {
5427                f(a.body);
5428            }
5429        }
5430        Stmt::FunctionDef { body, .. } => f(body),
5431        _ => {}
5432    }
5433}
5434
5435/// Record, per `Map`/`HashMap` local declared `… with capacity CAP`, the capacity
5436/// as a kernel `LinearExpr` — but only when CAP is affine and every variable it
5437/// names is program-invariant (`reassigned` excludes it). A map symbol defined by
5438/// two such `Let`s has an ambiguous capacity and is poisoned (never recorded).
5439/// Recording for non-`Int` maps is harmless: their keys are not affine integers,
5440/// so `try_prove_dense_key` never proves them and the (Int-only) codegen gate
5441/// never consults them.
5442fn gather_map_caps(
5443    stmts: &[Stmt],
5444    interner: &crate::intern::Interner,
5445    reassigned: &std::collections::HashSet<Symbol>,
5446    out: &mut HashMap<Symbol, super::affine::LinExpr>,
5447    poisoned: &mut std::collections::HashSet<Symbol>,
5448) {
5449    for s in stmts {
5450        if let Stmt::Let { var, value, .. } = s {
5451            if let Expr::WithCapacity {
5452                value: inner,
5453                capacity,
5454            } = value
5455            {
5456                if let Expr::New { type_name, .. } = inner {
5457                    if matches!(interner.resolve(*type_name), "Map" | "HashMap") {
5458                        if let Some(cap_lin) = super::affine::lin_of(capacity) {
5459                            let mut cap_syms = Vec::new();
5460                            affine_collect_syms(capacity, &mut cap_syms);
5461                            let invariant = cap_syms.iter().all(|s| !reassigned.contains(s));
5462                            if poisoned.contains(var) {
5463                                // already ambiguous — leave unrecorded
5464                            } else if !invariant {
5465                                out.remove(var);
5466                                poisoned.insert(*var);
5467                            } else if out.insert(*var, cap_lin).is_some() {
5468                                // second WithCapacity definition of the same map
5469                                out.remove(var);
5470                                poisoned.insert(*var);
5471                            }
5472                        }
5473                    }
5474                }
5475            }
5476        }
5477        each_child_block(s, &mut |b| {
5478            gather_map_caps(b, interner, reassigned, out, poisoned)
5479        });
5480    }
5481}
5482
5483/// The inclusive loop bound `B` of a counted condition `iv </<= B` whose counter
5484/// is a bare identifier — the candidate key-domain capacity for a map filled by
5485/// the loop. `None` for any other condition shape.
5486fn counted_loop_bound<'a>(cond: &'a Expr<'a>) -> Option<&'a Expr<'a>> {
5487    let Expr::BinaryOp { op, left, right } = cond else {
5488        return None;
5489    };
5490    if !matches!(op, BinaryOpKind::Lt | BinaryOpKind::LtEq) {
5491        return None;
5492    }
5493    let Expr::Identifier(_) = *left else {
5494        return None;
5495    };
5496    Some(*right)
5497}
5498
5499/// Collect every `new Map`/`new HashMap` local created WITHOUT an explicit
5500/// capacity (a bare `Expr::New`) — the maps whose capacity, if any, must be
5501/// INFERRED from a fill loop rather than read off the declaration.
5502fn collect_bare_new_maps(
5503    stmts: &[Stmt],
5504    interner: &crate::intern::Interner,
5505    out: &mut std::collections::HashSet<Symbol>,
5506) {
5507    for s in stmts {
5508        if let Stmt::Let { var, value, .. } = s {
5509            if let Expr::New { type_name, .. } = value {
5510                if matches!(interner.resolve(*type_name), "Map" | "HashMap") {
5511                    out.insert(*var);
5512                }
5513            }
5514        }
5515        each_child_block(s, &mut |b| collect_bare_new_maps(b, interner, out));
5516    }
5517}
5518
5519/// Record every bare-`new` map inserted into within `stmts` (a `Set item _ of m`),
5520/// restricted to the `candidates` set.
5521fn collect_loop_inserted_maps(
5522    stmts: &[Stmt],
5523    candidates: &std::collections::HashSet<Symbol>,
5524    out: &mut Vec<Symbol>,
5525) {
5526    for s in stmts {
5527        if let Stmt::SetIndex {
5528            collection: Expr::Identifier(m),
5529            ..
5530        } = s
5531        {
5532            if candidates.contains(m) {
5533                out.push(*m);
5534            }
5535        }
5536        each_child_block(s, &mut |b| collect_loop_inserted_maps(b, candidates, out));
5537    }
5538}
5539
5540/// Capacity inference for a `Map of Int to Int` created with a BARE `new Map`
5541/// (no `with capacity`) but filled inside a counted loop: the loop bound `B` of a
5542/// `While iv </<= B` whose body inserts into the map is a candidate key-domain
5543/// capacity. The dense gate still PROVES every key `<= B` before lowering, so a
5544/// loose or unrelated `B` simply fails the proof and the map stays a hash table —
5545/// recording it is never a miscompile, only an opportunity (this is what unlocks
5546/// two_sum's `seen`, whose keys `x = item i of arr` and `complement = n - x` are
5547/// element-derived, not loop counters). `B` must be affine and program-invariant.
5548/// `or_insert` so an explicit `with capacity` already in `out` always wins, and
5549/// `poisoned` (ambiguous explicit caps) are left untouched.
5550fn gather_implicit_map_caps(
5551    stmts: &[Stmt],
5552    interner: &crate::intern::Interner,
5553    reassigned: &std::collections::HashSet<Symbol>,
5554    poisoned: &std::collections::HashSet<Symbol>,
5555    out: &mut HashMap<Symbol, super::affine::LinExpr>,
5556) {
5557    let mut bare = std::collections::HashSet::new();
5558    collect_bare_new_maps(stmts, interner, &mut bare);
5559    if bare.is_empty() {
5560        return;
5561    }
5562    fn walk(
5563        stmts: &[Stmt],
5564        bare: &std::collections::HashSet<Symbol>,
5565        reassigned: &std::collections::HashSet<Symbol>,
5566        poisoned: &std::collections::HashSet<Symbol>,
5567        out: &mut HashMap<Symbol, super::affine::LinExpr>,
5568    ) {
5569        for s in stmts {
5570            if let Stmt::While { cond, body, .. } = s {
5571                if let Some(bound) = counted_loop_bound(cond) {
5572                    if let Some(b_lin) = super::affine::lin_of(bound) {
5573                        let mut syms = Vec::new();
5574                        affine_collect_syms(bound, &mut syms);
5575                        if syms.iter().all(|x| !reassigned.contains(x)) {
5576                            let mut inserted = Vec::new();
5577                            collect_loop_inserted_maps(body, bare, &mut inserted);
5578                            for m in inserted {
5579                                if !poisoned.contains(&m) && !out.contains_key(&m) {
5580                                    out.insert(m, b_lin.clone());
5581                                }
5582                            }
5583                        }
5584                    }
5585                }
5586            }
5587            each_child_block(s, &mut |b| walk(b, bare, reassigned, poisoned, out));
5588        }
5589    }
5590    walk(stmts, &bare, reassigned, poisoned, out);
5591}
5592
5593/// Render an affine capacity `LinExpr` as a Rust `i64` expression string — used to
5594/// size a dense map's direct-addressed array (`with_bounds(0, (cap) + 1)`) at its
5595/// constructor site. `None` if any coefficient or the constant is non-integer (no
5596/// clean rendering), in which case the dense gate declines and the map stays a
5597/// hash table. Terms are emitted in symbol-index order for determinism.
5598pub fn lin_to_rust(
5599    e: &super::affine::LinExpr,
5600    interner: &crate::intern::Interner,
5601) -> Option<String> {
5602    let mut coeffs: Vec<(i64, i64)> = Vec::new();
5603    for (idx, c) in e.coefficients.iter() {
5604        let ci = c.to_i64()?;
5605        if ci != 0 {
5606            coeffs.push((*idx, ci));
5607        }
5608    }
5609    coeffs.sort_by_key(|&(idx, _)| idx);
5610    let mut terms: Vec<String> = Vec::new();
5611    for (idx, ci) in coeffs {
5612        let name = interner.resolve(Symbol::from_index(idx as usize));
5613        terms.push(if ci == 1 {
5614            name.to_string()
5615        } else {
5616            format!("{} * {}", ci, name)
5617        });
5618    }
5619    let k = e.constant.to_i64()?;
5620    if k != 0 || terms.is_empty() {
5621        terms.push(k.to_string());
5622    }
5623    Some(terms.join(" + "))
5624}
5625
5626/// Tally how many `Set item _ of m to _` insert sites each map symbol has across
5627/// the program. A map with exactly one insert loop is eligible for the
5628/// full-coverage recognizer; more than one (or zero) is not.
5629fn count_insert_sites(stmts: &[Stmt], out: &mut HashMap<Symbol, u32>) {
5630    for s in stmts {
5631        if let Stmt::SetIndex {
5632            collection: Expr::Identifier(m),
5633            ..
5634        } = s
5635        {
5636            *out.entry(*m).or_insert(0) += 1;
5637        }
5638        each_child_block(s, &mut |b| count_insert_sites(b, out));
5639    }
5640}
5641
5642/// Recognize a CONTIGUOUS, UNIT-STRIDE, UNCONDITIONAL insert loop over a map in
5643/// `map_caps`: `While iv </<= UB:` whose body is EXACTLY `Set item iv of m to _`
5644/// and `Set iv to iv + 1`. Such a loop writes `m[iv]` for every integer `iv` in
5645/// `[entry(iv), B]`, so the inserted key set is that whole contiguous range —
5646/// the gap-free coverage presence elision needs. Returns `(m, iv, B)` with `B`
5647/// the inclusive upper bound (`UB - 1` for `<`, `UB` for `<=`). Deliberately
5648/// strict: a conditional insert, a non-unit stride, a `break`, or any extra
5649/// statement leaves gaps and is rejected (no elision, presence bit kept).
5650fn match_insert_loop(
5651    cond: &Expr,
5652    body: &[Stmt],
5653    map_caps: &HashMap<Symbol, super::affine::LinExpr>,
5654) -> Option<(Symbol, Symbol, super::affine::LinExpr)> {
5655    use super::affine::{konst, lin_of};
5656    // cond: `iv < UB` (B = UB - 1) or `iv <= UB` (B = UB), iv a bare identifier.
5657    let Expr::BinaryOp { op, left, right } = cond else {
5658        return None;
5659    };
5660    let Expr::Identifier(iv) = left else {
5661        return None;
5662    };
5663    let b_lin = match op {
5664        BinaryOpKind::Lt => lin_of(right)?.sub(&konst(1)),
5665        BinaryOpKind::LtEq => lin_of(right)?,
5666        _ => return None,
5667    };
5668    if body.len() != 2 {
5669        return None;
5670    }
5671    let mut found_map: Option<Symbol> = None;
5672    let mut found_incr = false;
5673    for s in body {
5674        match s {
5675            // The unconditional insert `Set item iv of m to _`.
5676            Stmt::SetIndex {
5677                collection: Expr::Identifier(m),
5678                index: Expr::Identifier(ix),
5679                ..
5680            } if ix == iv && map_caps.contains_key(m) => {
5681                if found_map.is_some() {
5682                    return None;
5683                }
5684                found_map = Some(*m);
5685            }
5686            // The unit increment `Set iv to iv + 1` (either operand order).
5687            Stmt::Set {
5688                target,
5689                value:
5690                    Expr::BinaryOp {
5691                        op: BinaryOpKind::Add,
5692                        left: l,
5693                        right: r,
5694                    },
5695            } if target == iv => {
5696                let iv_plus_one = matches!((l, r),
5697                    (Expr::Identifier(a), Expr::Literal(Literal::Number(1))) if a == iv)
5698                    || matches!((l, r),
5699                        (Expr::Literal(Literal::Number(1)), Expr::Identifier(a)) if a == iv);
5700                if !iv_plus_one {
5701                    return None;
5702                }
5703                found_incr = true;
5704            }
5705            _ => return None,
5706        }
5707    }
5708    match (found_map, found_incr) {
5709        (Some(m), true) => Some((m, *iv, b_lin)),
5710        _ => None,
5711    }
5712}
5713
5714/// Record, per map whose single insert loop fully covers a contiguous range, the
5715/// covered interval `[A, B]` — `A` the induction variable's constant entry value
5716/// (the most recent literal assignment in scope before the loop), `B` from the
5717/// loop guard. Only maps with EXACTLY one insert site are considered (so the one
5718/// loop accounts for every inserted key).
5719fn gather_insert_coverage(
5720    stmts: &[Stmt],
5721    map_caps: &HashMap<Symbol, super::affine::LinExpr>,
5722    insert_counts: &HashMap<Symbol, u32>,
5723    inits: &mut HashMap<Symbol, i64>,
5724    out: &mut HashMap<Symbol, (super::affine::LinExpr, super::affine::LinExpr)>,
5725) {
5726    use super::affine::konst;
5727    for s in stmts {
5728        if let Stmt::While { cond, body, .. } = s {
5729            if let Some((m, iv, b_lin)) = match_insert_loop(cond, body, map_caps) {
5730                if insert_counts.get(&m) == Some(&1) {
5731                    if let Some(&a) = inits.get(&iv) {
5732                        out.entry(m).or_insert((konst(a), b_lin));
5733                    }
5734                }
5735            }
5736        }
5737        each_child_block(s, &mut |b| {
5738            gather_insert_coverage(b, map_caps, insert_counts, &mut inits.clone(), out)
5739        });
5740        // Track constant inits in execution order so a loop sees its IV's entry
5741        // value; any non-literal (re)assignment clears the fact.
5742        match s {
5743            Stmt::Let {
5744                var,
5745                value: Expr::Literal(Literal::Number(n)),
5746                ..
5747            } => {
5748                inits.insert(*var, *n);
5749            }
5750            Stmt::Let { var, .. } => {
5751                inits.remove(var);
5752            }
5753            Stmt::Set {
5754                target,
5755                value: Expr::Literal(Literal::Number(n)),
5756            } => {
5757                inits.insert(*target, *n);
5758            }
5759            Stmt::Set { target, .. } => {
5760                inits.remove(target);
5761            }
5762            _ => {}
5763        }
5764    }
5765}
5766
5767pub fn oracle_analyze(stmts: &[Stmt]) -> OracleFacts {
5768    let mut facts = OracleFacts::default();
5769    let callee_globals = std::rc::Rc::new(CalleeGlobals::of_program(stmts));
5770    let mut st = RichAbstractState::new();
5771    st.callee_globals = callee_globals.clone();
5772    rich_walk_block(stmts, &mut st, &mut facts);
5773    // Function bodies: parameters carry their declared scalar types.
5774    for s in stmts {
5775        if let Stmt::FunctionDef { params, body, .. } = s {
5776            let mut fst = RichAbstractState::new();
5777            fst.callee_globals = callee_globals.clone();
5778            for (psym, ty) in params.iter() {
5779                if let crate::ast::stmt::TypeExpr::Primitive(t) = ty {
5780                    // Declared types arrive as interned names; tag the ones
5781                    // the scalar lattice models.
5782                    fst.types.insert(*psym, type_tag_for_name(*t));
5783                }
5784                // Two parameters may be handed the same allocation by a
5785                // caller — unknown provenance for the alias domain.
5786                fst.aliases.taint(*psym);
5787            }
5788            rich_walk_block(body, &mut fst, &mut facts);
5789        }
5790    }
5791    strip_concurrent_loop_snapshots(stmts, &mut facts, false);
5792    facts
5793}
5794
5795/// Map a declared primitive type NAME to a type-domain fact (Top when the
5796/// name is outside the scalar lattice). Resolved structurally — the interner
5797/// is unavailable here, so compare against the few candidate tags by trying
5798/// each known name through the type registry convention.
5799fn type_tag_for_name(_name: Symbol) -> TypeAbstraction {
5800    // Without the interner, names cannot be resolved to strings here;
5801    // declared-type seeding happens in oracle_analyze_with via the interner.
5802    TypeAbstraction::Top
5803}
5804
5805/// [`oracle_analyze`] with the interner, enabling declared-parameter type
5806/// seeds inside function bodies. Used by every NON-AOT consumer (VM bytecode,
5807/// copy-and-patch JIT, e-graph, UI) — these get NO entry-guard precondition, so
5808/// the partition's accesses stay behind a runtime `RegionBoundsGuard` rather
5809/// than being statically elided on a precondition the bytecode never enforces.
5810pub fn oracle_analyze_with(stmts: &[Stmt], interner: &crate::intern::Interner) -> OracleFacts {
5811    oracle_analyze_with_opts(stmts, interner, false)
5812}
5813
5814/// [`oracle_analyze_with`] for the `largo build` AOT codegen ONLY. Enables the
5815/// recursive-1-based-partition entry-guard precondition (`1 <= lo`,
5816/// `hi <= len`) and alias `length_def` propagation — sound here because the AOT
5817/// codegen emits the matching runtime `assert!` at the function entry. The
5818/// VM/JIT path emits no such assert, so it must use [`oracle_analyze_with`].
5819pub fn oracle_analyze_with_entry_guards(
5820    stmts: &[Stmt],
5821    interner: &crate::intern::Interner,
5822) -> OracleFacts {
5823    oracle_analyze_with_opts(stmts, interner, true)
5824}
5825
5826/// The functions every return of which hands back a sequence as long as the one handed to them at a parameter
5827/// position: `function -> position`. A candidate (a sequence parameter, a sequence return type, and a body whose
5828/// statements the walk enters, so no return hides from it) is walked with that parameter's entry length named
5829/// ([`super::affine::entry_len_index`]); every `Return` it holds must be recorded handing back a sequence whose length
5830/// equals it. Calls assume the summaries still standing, and a refuted candidate is dropped and the rest walked again
5831/// until none is refuted. The greatest fixpoint is sound for what a call returns: a call that returns made only
5832/// calls that returned, so the summaries hold by induction on the depth of the calls.
5833fn length_preserving_functions(
5834    stmts: &[Stmt],
5835    fn_returns: &std::rc::Rc<HashMap<Symbol, TypeTag>>,
5836    callee_globals: &std::rc::Rc<CalleeGlobals>,
5837    seq_types: &std::rc::Rc<HashSet<Symbol>>,
5838) -> HashMap<Symbol, usize> {
5839    use super::affine::{entry_len_index, len_index, len_var, LinExpr};
5840    use crate::ast::stmt::TypeExpr;
5841    let is_seq =
5842        |ty: &TypeExpr| matches!(ty, TypeExpr::Generic { base, .. } if seq_types.contains(base));
5843    let mut defs = Vec::new();
5844    let mut candidates: HashMap<Symbol, Vec<usize>> = HashMap::new();
5845    for s in stmts {
5846        let Stmt::FunctionDef {
5847            name,
5848            params,
5849            body,
5850            return_type: Some(ret),
5851            ..
5852        } = s
5853        else {
5854            continue;
5855        };
5856        let mut sites = Vec::new();
5857        if !is_seq(ret) || !return_sites(body, &mut sites) || sites.is_empty() {
5858            continue;
5859        }
5860        let positions: Vec<usize> = (0..params.len()).filter(|&i| is_seq(params[i].1)).collect();
5861        if !positions.is_empty() {
5862            candidates.insert(*name, positions);
5863            defs.push((*name, params, *body, sites));
5864        }
5865    }
5866    loop {
5867        let assumed: std::rc::Rc<HashMap<Symbol, usize>> = std::rc::Rc::new(
5868            candidates
5869                .iter()
5870                .filter_map(|(f, ps)| ps.first().map(|p| (*f, *p)))
5871                .collect(),
5872        );
5873        let mut refuted = false;
5874        for (name, params, body, sites) in &defs {
5875            let positions = candidates[name].clone();
5876            if positions.is_empty() {
5877                continue;
5878            }
5879            let mut fst = RichAbstractState::new();
5880            fst.fn_returns = fn_returns.clone();
5881            fst.callee_globals = callee_globals.clone();
5882            fst.seq_types = seq_types.clone();
5883            fst.len_summaries = assumed.clone();
5884            for (i, (p, ty)) in params.iter().enumerate() {
5885                fst.aliases.taint(*p);
5886                if is_seq(ty) {
5887                    fst.seq_vars.insert(*p);
5888                    fst.coll_vars.insert(*p);
5889                    fst.karr
5890                        .assign(len_index(*p), Some(&LinExpr::var(entry_len_index(i))));
5891                }
5892            }
5893            let mut facts = OracleFacts {
5894                return_probe: Some(Vec::new()),
5895                ..OracleFacts::default()
5896            };
5897            rich_walk_block(body, &mut fst, &mut facts);
5898            let returns = facts.return_probe.take().unwrap_or_default();
5899            let kept: Vec<usize> = positions
5900                .iter()
5901                .copied()
5902                .filter(|&p| {
5903                    let entry = LinExpr::var(entry_len_index(p));
5904                    sites.iter().all(|&site| {
5905                        let mut at = returns.iter().filter(|(a, _, _)| *a == site).peekable();
5906                        at.peek().is_some()
5907                            && at.all(|(_, named, karr)| {
5908                                named.is_some_and(|c| karr.entails_zero(&len_var(c).sub(&entry)))
5909                            })
5910                    })
5911                })
5912                .collect();
5913            if kept.len() != positions.len() {
5914                refuted = true;
5915                candidates.insert(*name, kept);
5916            }
5917        }
5918        if !refuted {
5919            break;
5920        }
5921    }
5922    candidates
5923        .into_iter()
5924        .filter_map(|(f, ps)| ps.first().map(|p| (f, *p)))
5925        .collect()
5926}
5927
5928/// Collect the address of every `Return` in `block` that hands back a value, through the blocks the walk enters.
5929/// False when the block holds a `Return` without a value, or a statement whose blocks the walk does not enter: a
5930/// return could hide there, so no summary may rest on the ones found.
5931fn return_sites(block: &[Stmt], out: &mut Vec<usize>) -> bool {
5932    block.iter().all(|s| match s {
5933        Stmt::Return { value: Some(_) } => {
5934            out.push(s as *const Stmt as usize);
5935            true
5936        }
5937        Stmt::If {
5938            then_block,
5939            else_block,
5940            ..
5941        } => return_sites(then_block, out) && else_block.map_or(true, |eb| return_sites(eb, out)),
5942        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => return_sites(body, out),
5943        Stmt::Inspect { arms, .. } => arms.iter().all(|a| return_sites(a.body, out)),
5944        Stmt::Let { .. }
5945        | Stmt::Set { .. }
5946        | Stmt::SetIndex { .. }
5947        | Stmt::SetField { .. }
5948        | Stmt::Push { .. }
5949        | Stmt::Pop { .. }
5950        | Stmt::Add { .. }
5951        | Stmt::Remove { .. }
5952        | Stmt::Swap { .. }
5953        | Stmt::Show { .. }
5954        | Stmt::Call { .. }
5955        | Stmt::Break
5956        | Stmt::RuntimeAssert { .. } => true,
5957        _ => false,
5958    })
5959}
5960
5961/// Shared body of the two public entry points. `aot_entry_guard` gates the
5962/// entry-guard-precondition facts to the AOT path that enforces them.
5963fn oracle_analyze_with_opts(
5964    stmts: &[Stmt],
5965    interner: &crate::intern::Interner,
5966    aot_entry_guard: bool,
5967) -> OracleFacts {
5968    let mut facts = OracleFacts::default();
5969    let callee_globals = std::rc::Rc::new(CalleeGlobals::of_program(stmts));
5970    // Dense-map gate (precondition): record each `Map of Int to Int … with
5971    // capacity CAP`'s invariant affine capacity BEFORE the loop walks, so
5972    // `try_prove_dense_key` can relate a key to it while the loop guards are live.
5973    {
5974        let reassigned = rebound_names(stmts, &callee_globals);
5975        let mut poisoned = std::collections::HashSet::new();
5976        gather_map_caps(
5977            stmts,
5978            interner,
5979            &reassigned,
5980            &mut facts.map_caps,
5981            &mut poisoned,
5982        );
5983        // Implicit capacity: a bare `new Map` filled by a counted loop takes that
5984        // loop's bound as a candidate key-domain cap (proof-gated downstream) —
5985        // so a `Map of Int to Int` written without `with capacity` can still go
5986        // dense (two_sum's `seen`). Explicit caps above already win via `or_insert`.
5987        gather_implicit_map_caps(stmts, interner, &reassigned, &poisoned, &mut facts.map_caps);
5988        // Presence elision precondition: which dense maps have a single insert
5989        // loop that fully covers a contiguous key range.
5990        let mut insert_counts = HashMap::new();
5991        count_insert_sites(stmts, &mut insert_counts);
5992        let mut inits = HashMap::new();
5993        gather_insert_coverage(
5994            stmts,
5995            &facts.map_caps,
5996            &insert_counts,
5997            &mut inits,
5998            &mut facts.map_insert_cover,
5999        );
6000    }
6001    // DECLARED primitive return types: a call to one of these functions
6002    // (native or user-defined) produces a typed value — a static fact the
6003    // kernel enforces dynamically.
6004    let mut fn_returns: HashMap<Symbol, TypeTag> = HashMap::new();
6005    for s in stmts {
6006        if let Stmt::FunctionDef {
6007            name,
6008            return_type: Some(ty),
6009            ..
6010        } = s
6011        {
6012            if let crate::ast::stmt::TypeExpr::Primitive(t) | crate::ast::stmt::TypeExpr::Named(t) =
6013                ty
6014            {
6015                let tag = match interner.resolve(*t) {
6016                    "Int" | "Element" | "Event" | "View" => Some(TypeTag::Int),
6017                    "Float" => Some(TypeTag::Float),
6018                    "Bool" => Some(TypeTag::Bool),
6019                    "Text" => Some(TypeTag::Text),
6020                    _ => None,
6021                };
6022                if let Some(tag) = tag {
6023                    fn_returns.insert(*name, tag);
6024                }
6025            }
6026        }
6027    }
6028    let fn_returns = std::rc::Rc::new(fn_returns);
6029    let seq_types: std::rc::Rc<HashSet<Symbol>> = std::rc::Rc::new(
6030        ["Seq", "List"]
6031            .iter()
6032            .filter_map(|n| interner.lookup(n))
6033            .collect(),
6034    );
6035    let len_summaries = std::rc::Rc::new(length_preserving_functions(
6036        stmts,
6037        &fn_returns,
6038        &callee_globals,
6039        &seq_types,
6040    ));
6041    let mut st = RichAbstractState::new();
6042    st.fn_returns = fn_returns.clone();
6043    st.callee_globals = callee_globals.clone();
6044    st.seq_types = seq_types.clone();
6045    st.len_summaries = len_summaries.clone();
6046    rich_walk_block(stmts, &mut st, &mut facts);
6047    for s in stmts {
6048        if let Stmt::FunctionDef { params, body, .. } = s {
6049            let mut fst = RichAbstractState::new();
6050            fst.fn_returns = fn_returns.clone();
6051            fst.callee_globals = callee_globals.clone();
6052            fst.seq_types = seq_types.clone();
6053            fst.len_summaries = len_summaries.clone();
6054            fst.aot_entry_guard = aot_entry_guard;
6055            for (psym, ty) in params.iter() {
6056                match ty {
6057                    crate::ast::stmt::TypeExpr::Primitive(t) => {
6058                        let tag = match interner.resolve(*t) {
6059                            "Int" | "Element" | "Event" | "View" => {
6060                                TypeAbstraction::Concrete(TypeTag::Int)
6061                            }
6062                            "Float" => TypeAbstraction::Concrete(TypeTag::Float),
6063                            "Bool" => TypeAbstraction::Concrete(TypeTag::Bool),
6064                            "Text" => TypeAbstraction::Concrete(TypeTag::Text),
6065                            _ => TypeAbstraction::Top,
6066                        };
6067                        fst.types.insert(*psym, tag);
6068                    }
6069                    // An ordered-collection parameter (`arr: Seq of Int`): a
6070                    // proven collection of unknown length — the speculative
6071                    // region-entry hoist's target.
6072                    crate::ast::stmt::TypeExpr::Generic { base, .. }
6073                        if matches!(interner.resolve(*base), "Seq" | "List" | "Array") =>
6074                    {
6075                        fst.coll_vars.insert(*psym);
6076                        fst.param_colls.insert(*psym);
6077                        if seq_types.contains(base) {
6078                            fst.seq_vars.insert(*psym);
6079                        }
6080                    }
6081                    _ => {}
6082                }
6083                // Two parameters may be handed the same allocation by a
6084                // caller — unknown provenance for the alias domain.
6085                fst.aliases.taint(*psym);
6086            }
6087            // Recursive 1-based partition precondition (quicksort/Lomuto): the
6088            // function is only ever entered with `1 <= lo` and `hi <= length(arr)`
6089            // — the contract `codegen::entry_guard` asserts at runtime for these
6090            // pure functions. Seeding those facts lets the relational BCE
6091            // discharge the partition's `item j of arr` / `item i of arr` accesses
6092            // (`1 <= i <= j < hi <= len`), a relation the interval domain alone
6093            // cannot express. Sound: every access sits past the `lo < hi` base
6094            // case, exactly where the runtime guard has already enforced these.
6095            // AOT ONLY — the VM/JIT bytecode path emits no entry guard, so it
6096            // must not see these unenforced facts (else it would drop a
6097            // `RegionBoundsGuard` it actually needs).
6098            let mut partition_guarded = false;
6099            if aot_entry_guard {
6100                if let Some(g) =
6101                    crate::codegen::entry_guard::detect_entry_guard(params, body, interner)
6102                {
6103                    fst.intervals.set_var(
6104                        g.lo,
6105                        Interval {
6106                            lo: Bound::Finite(1),
6107                            hi: Bound::PosInf,
6108                        },
6109                    );
6110                    fst.intervals.set_var(
6111                        g.hi,
6112                        Interval {
6113                            lo: Bound::Finite(1),
6114                            hi: Bound::PosInf,
6115                        },
6116                    );
6117                    fst.length_def.insert(g.arr, (g.hi, 0));
6118                    // `lo>=1`/`hi>=1` as function-wide ambient facts carried ON THE
6119                    // STATE — they flow (via clone) into the loop fixpoint's record
6120                    // state, where the header interval is widened away and a
6121                    // thread-local was empty. Enforced by the entry-guard `assert!`.
6122                    fst.entry_guard_lowers = vec![(g.lo, 1), (g.hi, 1)];
6123                    partition_guarded = true;
6124                } else if let Some(g) =
6125                    crate::codegen::entry_guard::detect_heap_sift_guard(params, body, interner)
6126                {
6127                    // Affine-index descent (heap sift): `end < arr.len()` (length_def)
6128                    // and `start,end >= 0` (enforced by the codegen entry guard). LIFT:
6129                    // the whole function body is in scope HERE, so verify the loop
6130                    // `counter` is `>= 0` (grounded by `Let counter be start`, start>=0)
6131                    // and seed that as a function-wide lower — no per-access whole-body
6132                    // context needed. The conditionally-assigned indices (`swapIdx`)
6133                    // then ground off this seeded lower in `try_prove_affine`.
6134                    fst.intervals.set_var(
6135                        g.start,
6136                        Interval {
6137                            lo: Bound::Finite(0),
6138                            hi: Bound::PosInf,
6139                        },
6140                    );
6141                    fst.intervals.set_var(
6142                        g.end,
6143                        Interval {
6144                            lo: Bound::Finite(0),
6145                            hi: Bound::PosInf,
6146                        },
6147                    );
6148                    fst.length_def.insert(g.arr, (g.end, 1));
6149                    fst.entry_guard_lowers = vec![(g.start, 0), (g.end, 0)];
6150                    let mutated: std::collections::HashSet<Symbol> =
6151                        collect_mutations_in(body, &callee_globals)
6152                            .into_iter()
6153                            .collect();
6154                    let assumed = std::collections::HashSet::new();
6155                    if sym_ge_lo(g.counter, 0, body, &fst, &mutated, &assumed, 64) {
6156                        fst.entry_guard_lowers.push((g.counter, 0));
6157                    }
6158                }
6159            }
6160            if partition_guarded {
6161                // Inlined top-level walk for the entry-guarded partition (quicksort):
6162                // the affine index proof runs only for LOOP bodies, so a post-loop
6163                // access — the Lomuto partition's `item i of arr` pivot swap, sitting
6164                // after the `while j < hi` scan — is never proven and keeps its bounds
6165                // branch. This mirrors `rich_walk_block`'s transfer exactly
6166                // (`record_stmt_exprs` + `rich_walk_stmt`), interleaving the affine
6167                // proof at each top-level statement's PRE-state — so the loop-exit
6168                // invariant `lo <= i <= hi` that `rich_walk_loop` records into the
6169                // post-loop state discharges the pivot swap. Scoped to the entry-guarded
6170                // partition functions (no other program reaches this branch), so it
6171                // cannot change any non-partition program's oracle output.
6172                let tl_mutated: std::collections::HashSet<Symbol> =
6173                    collect_mutations_in(body, &callee_globals)
6174                        .into_iter()
6175                        .collect();
6176                let mut tl_clobbered: std::collections::HashSet<Symbol> =
6177                    std::collections::HashSet::new();
6178                collect_resized_arrays(body, &mut tl_clobbered);
6179                for stmt in body.iter() {
6180                    record_stmt_exprs(stmt, &fst, &mut facts);
6181                    prove_toplevel_accesses(
6182                        stmt,
6183                        body,
6184                        &fst,
6185                        &tl_clobbered,
6186                        &tl_mutated,
6187                        &mut facts,
6188                    );
6189                    rich_walk_stmt(stmt, &mut fst, &mut facts);
6190                }
6191            } else {
6192                rich_walk_block(body, &mut fst, &mut facts);
6193            }
6194        }
6195    }
6196    strip_concurrent_loop_snapshots(stmts, &mut facts, false);
6197    facts
6198}
6199
6200/// Loops under Concurrent/Parallel blocks run interleaved: the sequential
6201/// alias walk is not a sound model of their entry states, so their
6202/// snapshots are withheld and the distinctness queries refuse.
6203fn strip_concurrent_loop_snapshots(stmts: &[Stmt], facts: &mut OracleFacts, in_concurrent: bool) {
6204    for stmt in stmts {
6205        match stmt {
6206            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
6207                if in_concurrent {
6208                    facts.loop_aliases.remove(&(stmt as *const Stmt as usize));
6209                }
6210                strip_concurrent_loop_snapshots(body, facts, in_concurrent);
6211            }
6212            Stmt::If {
6213                then_block,
6214                else_block,
6215                ..
6216            } => {
6217                strip_concurrent_loop_snapshots(then_block, facts, in_concurrent);
6218                if let Some(eb) = else_block {
6219                    strip_concurrent_loop_snapshots(eb, facts, in_concurrent);
6220                }
6221            }
6222            Stmt::Zone { body, .. } => {
6223                strip_concurrent_loop_snapshots(body, facts, in_concurrent);
6224            }
6225            Stmt::FunctionDef { body, .. } => {
6226                strip_concurrent_loop_snapshots(body, facts, in_concurrent);
6227            }
6228            Stmt::Inspect { arms, .. } => {
6229                for arm in arms {
6230                    strip_concurrent_loop_snapshots(arm.body, facts, in_concurrent);
6231                }
6232            }
6233            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
6234                strip_concurrent_loop_snapshots(tasks, facts, true);
6235            }
6236            _ => {}
6237        }
6238    }
6239}
6240
6241pub(crate) fn rich_abstract_interp_stmts<'a>(
6242    stmts: Vec<Stmt<'a>>,
6243    _expr_arena: &'a Arena<Expr<'a>>,
6244    _stmt_arena: &'a Arena<Stmt<'a>>,
6245) -> (Vec<Stmt<'a>>, RichAbstractState) {
6246    let mut st = RichAbstractState::new();
6247    st.callee_globals = std::rc::Rc::new(CalleeGlobals::of_program(&stmts));
6248    let mut facts = OracleFacts::default();
6249    rich_walk_block(&stmts, &mut st, &mut facts);
6250    (stmts, st)
6251}
6252
6253fn rich_walk_block(block: &[Stmt], st: &mut RichAbstractState, facts: &mut OracleFacts) {
6254    for stmt in block {
6255        record_stmt_exprs(stmt, st, facts);
6256        rich_walk_stmt(stmt, st, facts);
6257    }
6258}
6259
6260/// Record facts for every expression a statement holds, at the PRE-state
6261/// (the state its expressions evaluate in).
6262fn record_stmt_exprs(stmt: &Stmt, st: &RichAbstractState, facts: &mut OracleFacts) {
6263    use crate::ast::stmt::ReadSource;
6264    match stmt {
6265        Stmt::Let { value, .. } | Stmt::Set { value, .. } => record_expr(value, st, facts),
6266        Stmt::Return { value: Some(e) } => {
6267            record_expr(e, st, facts);
6268            if let Some(probe) = &mut facts.return_probe {
6269                let named = match e {
6270                    Expr::Identifier(s) if st.seq_vars.contains(s) => Some(*s),
6271                    _ => None,
6272                };
6273                probe.push((stmt as *const Stmt as usize, named, st.karr.clone()));
6274            }
6275        }
6276        Stmt::Call { args, .. } => {
6277            for a in args {
6278                record_expr(a, st, facts);
6279            }
6280        }
6281        Stmt::If { cond, .. } | Stmt::While { cond, .. } => record_expr(cond, st, facts),
6282        Stmt::Repeat { iterable, .. } => record_expr(iterable, st, facts),
6283        Stmt::Show { object, .. } | Stmt::Give { object, .. } => record_expr(object, st, facts),
6284        Stmt::Push { value, collection }
6285        | Stmt::Add { value, collection }
6286        | Stmt::Remove { value, collection } => {
6287            record_expr(value, st, facts);
6288            record_expr(collection, st, facts);
6289        }
6290        Stmt::SetIndex {
6291            collection,
6292            index,
6293            value,
6294        } => {
6295            record_expr(collection, st, facts);
6296            record_expr(index, st, facts);
6297            record_expr(value, st, facts);
6298            record_karr(index, st, facts);
6299        }
6300        Stmt::SetField { object, value, .. } => {
6301            record_expr(object, st, facts);
6302            record_expr(value, st, facts);
6303        }
6304        Stmt::Inspect { target, .. } => record_expr(target, st, facts),
6305        Stmt::RuntimeAssert { condition, .. } => record_expr(condition, st, facts),
6306        Stmt::Sleep { milliseconds } => record_expr(milliseconds, st, facts),
6307        Stmt::ReadFrom {
6308            source: ReadSource::File(p),
6309            ..
6310        } => record_expr(p, st, facts),
6311        _ => {}
6312    }
6313}
6314
6315fn rich_walk_stmt(stmt: &Stmt, st: &mut RichAbstractState, facts: &mut OracleFacts) {
6316    // The statement's OWN effects (its arms below recurse into nested blocks, whose statements get
6317    // their own turn here): foreign code forgets everything, a call forgets the callee-written globals.
6318    let own = WriteSet::of_stmt_shallow(stmt).with_callee_globals(&st.callee_globals);
6319    if own.is_opaque() {
6320        st.forget_everything();
6321        return;
6322    }
6323    if own.has_calls() {
6324        st.forget_callee_globals();
6325    }
6326    karr_step(stmt, &own, st);
6327    match stmt {
6328        Stmt::Let { var, value, .. } => rich_bind(*var, value, st),
6329        Stmt::Swap { a, b } => {
6330            for sym in [*a, *b] {
6331                st.invalidate_var(sym);
6332                st.aliases.unlink(sym);
6333            }
6334        }
6335        Stmt::Set { target, value } => rich_bind(*target, value, st),
6336        Stmt::Push { collection, value } | Stmt::Add { collection, value } => {
6337            rich_grow(collection, st);
6338            observe_written_elem(collection, value, st);
6339        }
6340        Stmt::Pop { collection, into } => {
6341            rich_shrink(collection, st);
6342            if let Some(v) = into {
6343                st.invalidate_var(*v);
6344                st.aliases.unlink(*v);
6345                // A popped element may be any handle ever stored in the
6346                // container — unknown provenance.
6347                st.aliases.taint(*v);
6348            }
6349        }
6350        Stmt::Remove { collection, .. } => rich_shrink(collection, st),
6351        // A store leaves the length unchanged but adds an element value: join
6352        // it into the collection's element bound (the scatter `Set item k of
6353        // arr to V` case).
6354        Stmt::SetIndex {
6355            collection, value, ..
6356        } => observe_written_elem(collection, value, st),
6357        Stmt::SetField { object, .. } => {
6358            if let Expr::Identifier(s) = *object {
6359                for a in st.aliases.may_alias(*s) {
6360                    st.shapes.insert(a, CollectionShape::Top);
6361                }
6362            }
6363        }
6364        Stmt::If {
6365            cond,
6366            then_block,
6367            else_block,
6368        } => {
6369            rich_walk_if(cond, then_block, *else_block, st, facts);
6370        }
6371        Stmt::While { cond, body, .. } => {
6372            let key = stmt as *const Stmt as usize;
6373            rich_walk_loop(Some(cond), body, st, None, facts, Some(key));
6374        }
6375        Stmt::Repeat { pattern, body, .. } => {
6376            let key = stmt as *const Stmt as usize;
6377            rich_walk_loop(None, body, st, pattern_loop_var(pattern), facts, Some(key));
6378        }
6379        Stmt::Inspect { target, arms, .. } => rich_walk_inspect(target, arms, st, facts),
6380        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
6381            // Tasks interleave: an equality one establishes another may break between any two statements.
6382            st.karr = super::karr::AffineSpace::top();
6383            rich_walk_block(tasks, st, facts);
6384            st.karr = super::karr::AffineSpace::top();
6385        }
6386        Stmt::Zone { body, .. } => {
6387            // Walk the zone body so aliasing established inside it is visible
6388            // and loops within it get borrow-hoist snapshots — but suppress
6389            // per-expression fact recording: the EXODIA region/JIT compiler
6390            // consumes those and assumes none exist inside zones. State
6391            // updates and loop_aliases snapshots stay live; only the
6392            // exprs/lengths/collections tables are held back.
6393            let prev = facts.suppress_exprs;
6394            facts.suppress_exprs = true;
6395            rich_walk_block(body, st, facts);
6396            facts.suppress_exprs = prev;
6397        }
6398        Stmt::Call { args, .. } => {
6399            // A callee may resize any collection it is handed: forget their sizes.
6400            for arg in args {
6401                if let Expr::Identifier(s) = *arg {
6402                    for a in st.aliases.may_alias(*s) {
6403                        st.shapes.insert(a, CollectionShape::Top);
6404                        st.intervals.set_length(a, Interval::non_negative());
6405                    }
6406                }
6407            }
6408        }
6409        Stmt::Give { object, .. } => {
6410            if let Expr::Identifier(s) = *object {
6411                st.invalidate_var(*s);
6412                st.aliases.unlink(*s);
6413            }
6414        }
6415        Stmt::ReadFrom { var, .. } => {
6416            st.invalidate_var(*var);
6417            st.aliases.unlink(*var);
6418        }
6419        // Every other statement is not descended into: everything it (or any block inside it) binds,
6420        // mutates, or reaches through a call is unknown afterwards; foreign code anywhere in it forgets
6421        // everything.
6422        _ => {
6423            let effects = WriteSet::of_stmt(stmt).with_callee_globals(&st.callee_globals);
6424            if effects.is_opaque() {
6425                st.forget_everything();
6426                return;
6427            }
6428            if effects.has_calls() {
6429                st.forget_callee_globals();
6430            }
6431            for sym in effects.symbols() {
6432                st.invalidate_var(sym);
6433                st.aliases.unlink(sym);
6434            }
6435        }
6436    }
6437}
6438
6439/// A counted loop's exit value. `While x <= B` (or `x < B`) whose one write of `x` is an unconditional top-level
6440/// `Set x to x + 1`, with `B` affine over names the body leaves alone and sequences it does not resize, ends with
6441/// `x = B + 1` (`x = B`) when `x` starts at most there: every pass begins with the guard holding and adds at most
6442/// one, so `x` never passes that value, and the loop ends only once `x` exceeds `B`. The equality joins `after`'s,
6443/// along with everything that moved in step with `x` (a counted build's length).
6444fn karr_counted_exit(
6445    cond: &Expr,
6446    body: &[Stmt],
6447    entry: &RichAbstractState,
6448    after: &mut RichAbstractState,
6449) {
6450    use super::affine::{konst, lin_of_with_lengths, var};
6451    let Expr::BinaryOp { op, left, right } = cond else {
6452        return;
6453    };
6454    let Expr::Identifier(x) = left else { return };
6455    let past = match op {
6456        BinaryOpKind::LtEq => 1,
6457        BinaryOpKind::Lt => 0,
6458        _ => return,
6459    };
6460    let writes = WriteSet::of_block(body).with_callee_globals(&entry.callee_globals);
6461    if writes.is_opaque()
6462        || !top_level_unconditional_incs(body, &entry.callee_globals)
6463            .iter()
6464            .any(|(v, d)| v == x && *d == 1)
6465    {
6466        return;
6467    }
6468    let mut resized = HashSet::new();
6469    collect_resized_arrays(body, &mut resized);
6470    let fixed =
6471        |c: Symbol| entry.seq_vars.contains(&c) && !resized.contains(&c) && !writes.may_write(c);
6472    let Some(bound) = lin_of_with_lengths(right, &fixed) else {
6473        return;
6474    };
6475    let int = |s: Symbol| {
6476        matches!(
6477            entry.types.get(&s),
6478            Some(TypeAbstraction::Concrete(TypeTag::Int))
6479        )
6480    };
6481    let names = bound
6482        .coefficients
6483        .keys()
6484        .filter(|&&k| k >= 0)
6485        .map(|&k| Symbol::from_index(k as usize));
6486    let names_ok = names.clone().all(|s| int(s) && !writes.may_write(s));
6487    if !int(*x) || !names_ok || !entry_proves(entry, &bound.add(&konst(past)).sub(&var(*x))) {
6488        return;
6489    }
6490    after.karr.meet_eq(&var(*x).sub(&bound).sub(&konst(past)));
6491}
6492
6493/// Whether `goal >= 0` follows at `st` from its equalities, the intervals and symbolic bounds of the names they and
6494/// `goal` mention, and every length being non-negative.
6495fn entry_proves(st: &RichAbstractState, goal: &super::affine::LinExpr) -> bool {
6496    use super::affine::{consistent, konst, le, prove, var};
6497    let mut system = Vec::new();
6498    for eq in st.karr.equalities() {
6499        system.push(le(&eq, &konst(0)));
6500        system.push(le(&konst(0), &eq));
6501    }
6502    let mut mentioned: std::collections::BTreeSet<i64> =
6503        goal.coefficients.keys().copied().collect();
6504    for c in &system {
6505        mentioned.extend(c.expr.coefficients.keys().copied());
6506    }
6507    for &k in &mentioned {
6508        if k < 0 {
6509            system.push(le(&konst(0), &super::affine::LinExpr::var(k)));
6510            continue;
6511        }
6512        let s = Symbol::from_index(k as usize);
6513        let iv = st.intervals.get_var(&s);
6514        if let Bound::Finite(lo) = iv.lo {
6515            system.push(le(&konst(lo), &var(s)));
6516        }
6517        if let Bound::Finite(hi) = iv.hi {
6518            system.push(le(&var(s), &konst(hi)));
6519        }
6520        if let Some(u) = st.scalar_upper.get(&s) {
6521            system.push(le(&var(s), u));
6522        }
6523        if let Some(l) = st.scalar_lower.get(&s) {
6524            system.push(le(l, &var(s)));
6525        }
6526    }
6527    consistent(&system) && prove(&system, goal)
6528}
6529
6530/// What a statement other than a binding does to the equalities: a push or a pop moves its sequence's length by
6531/// one, a store into a sequence keeps it, and every other name the statement writes (or lends to a callee's
6532/// `mutable` parameter) may come back as anything. A binding's transfer is [`karr_after_bind`]; a compound
6533/// statement's blocks are walked statement by statement.
6534fn karr_step(stmt: &Stmt, own: &WriteSet, st: &mut RichAbstractState) {
6535    use super::affine::{konst, len_index, len_var};
6536    let named = |e: &Expr| match e {
6537        Expr::Identifier(s) => Some(*s),
6538        _ => None,
6539    };
6540    let moved: Option<(Symbol, i64)> = match stmt {
6541        Stmt::Let { .. } | Stmt::Set { .. } => return,
6542        Stmt::Push { collection, .. } => named(collection).map(|c| (c, 1)),
6543        Stmt::Pop { collection, .. } => named(collection).map(|c| (c, -1)),
6544        _ => None,
6545    };
6546    let kept = match stmt {
6547        Stmt::SetIndex { collection, .. } => named(collection).filter(|c| st.seq_vars.contains(c)),
6548        _ => None,
6549    };
6550    let unknown: Vec<Symbol> = own
6551        .symbols()
6552        .filter(|s| Some(*s) != moved.map(|(c, _)| c) && Some(*s) != kept)
6553        .collect();
6554    for name in unknown {
6555        st.karr_unknown(name);
6556    }
6557    if let Some((c, by)) = moved {
6558        st.karr_resized(c);
6559        let next = st.seq_vars.contains(&c).then(|| len_var(c).add(&konst(by)));
6560        st.karr.assign(len_index(c), next.as_ref());
6561    }
6562}
6563
6564/// `Let v be value.` / `Set v to value.` — rebinds `v`, so its old aliasing is
6565/// severed and all five facts are recomputed from `value`.
6566/// Record an element written into a collection (`Push`/`Add`/`SetIndex`):
6567/// join the value's interval into the element bound of every handle that
6568/// aliases the collection (a write through one alias is visible through all).
6569/// The SYMBOLIC upper bound of `value` as a linear expression over program
6570/// variables, or `None` if no useful one is known. This is the variable-divisor
6571/// sibling of `eval_expr`'s concrete interval upper: it exists precisely for the
6572/// bounds a concrete `Interval` cannot hold. A `(...) % n` with a VARIABLE `n`
6573/// is `<= n - 1` (the truncated remainder satisfies this whenever `n >= 1`,
6574/// which the `while i < n` fill loop guarantees and an empty array makes
6575/// vacuous); a scalar carries its `scalar_upper`; an element read carries its
6576/// array's `elem_upper`; a numeric literal is its own bound.
6577fn value_upper(value: &Expr, st: &RichAbstractState) -> Option<super::affine::LinExpr> {
6578    use super::affine::{konst, var};
6579    match value {
6580        Expr::Literal(Literal::Number(k)) => Some(konst(*k)),
6581        Expr::Identifier(s) => st.scalar_upper.get(s).cloned(),
6582        Expr::Index { collection, .. } => match collection {
6583            Expr::Identifier(arr) => st.elem_upper.get(arr).cloned(),
6584            _ => None,
6585        },
6586        Expr::BinaryOp {
6587            op: BinaryOpKind::Modulo,
6588            right,
6589            ..
6590        } => match right {
6591            Expr::Identifier(n) => Some(var(*n).sub(&konst(1))),
6592            _ => None,
6593        },
6594        // A non-negative `y` divided by a literal `k >= 1` is at most `y`.
6595        Expr::BinaryOp {
6596            op: BinaryOpKind::Divide,
6597            left,
6598            right,
6599        } if divides_nonnegative(left, right, st) => super::affine::lin_of(left),
6600        _ => None,
6601    }
6602}
6603
6604/// Whether `left / right` divides a value the intervals prove non-negative by a literal of at least one: its quotient
6605/// lies in `[0, left]`.
6606fn divides_nonnegative(left: &Expr, right: &Expr, st: &RichAbstractState) -> bool {
6607    matches!(right, Expr::Literal(Literal::Number(k)) if *k >= 1)
6608        && matches!(eval_expr(left, &st.intervals).lo, Bound::Finite(lo) if lo >= 0)
6609}
6610
6611/// The symbolic LOWER bound of `value`, the mirror of [`value_upper`]. An
6612/// element read carries its array's proven concrete element interval lower (the
6613/// `% n`-filled array's `0`); a scalar carries its `scalar_lower`; a literal is
6614/// its own bound. Captured here because a loop-local read variable's raw
6615/// interval is flooded to ⊤ by its undefined entry value, losing this lower.
6616fn value_lower(value: &Expr, st: &RichAbstractState) -> Option<super::affine::LinExpr> {
6617    use super::affine::konst;
6618    match value {
6619        Expr::Literal(Literal::Number(k)) => Some(konst(*k)),
6620        Expr::Identifier(s) => st.scalar_lower.get(s).cloned(),
6621        Expr::Index { collection, .. } => match collection {
6622            Expr::Identifier(arr) => match st.intervals.get_elem(arr).lo {
6623                Bound::Finite(lo) => Some(konst(lo)),
6624                _ => None,
6625            },
6626            _ => None,
6627        },
6628        Expr::BinaryOp {
6629            op: BinaryOpKind::Divide,
6630            left,
6631            right,
6632        } if divides_nonnegative(left, right, st) => Some(konst(0)),
6633        _ => None,
6634    }
6635}
6636
6637/// Merge two symbolic element-upper bounds under the "EVERY element satisfies
6638/// it" reading: the result must dominate BOTH. Equal bounds (the uniform fill —
6639/// every store is the same `% n`) are kept; otherwise the one provably the
6640/// larger in the current interval state wins (so a constant zero-init folds into
6641/// the symbolic `n - 1`), and the bound drops to ⊤ when the two are unordered.
6642fn join_sym_upper(
6643    a: &super::affine::LinExpr,
6644    b: &super::affine::LinExpr,
6645    st: &RichAbstractState,
6646) -> Option<super::affine::LinExpr> {
6647    if a == b {
6648        return Some(a.clone());
6649    }
6650    if lin_ge_zero(&b.sub(a), st) {
6651        return Some(b.clone()); // b - a >= 0 ⟹ b is the weaker (larger) upper
6652    }
6653    if lin_ge_zero(&a.sub(b), st) {
6654        return Some(a.clone());
6655    }
6656    // LENIENT: a non-positive constant element (the zero-init of a build-then-
6657    // scatter array) joins into a `% m` element upper `m - 1`. Sound under
6658    // `m >= 1`: then `c <= 0 <= m - 1`, so every element satisfies `m - 1`
6659    // (vacuous when the array is empty). The `m >= 1` precondition is discharged
6660    // by a nonemptiness-guarded `assert!(m > 0)` at any elision that consumes the
6661    // bound (see `try_prove_affine` / `positivity_guards`). Restricted to the
6662    // `m - 1` shape so the divisor to guard is unambiguous.
6663    if is_nonpos_const(a) && mod_upper_divisor(b).is_some() {
6664        return Some(b.clone());
6665    }
6666    if is_nonpos_const(b) && mod_upper_divisor(a).is_some() {
6667        return Some(a.clone());
6668    }
6669    None
6670}
6671
6672/// `Some(m)` when `e` is the variable-divisor modulo upper `m - 1` (a single
6673/// variable with coefficient `+1` and constant `-1`) — the bound `value_upper`
6674/// emits for `(...) % m`. Its `m >= 1` precondition is what the positivity guard
6675/// discharges.
6676fn mod_upper_divisor(e: &super::affine::LinExpr) -> Option<Symbol> {
6677    if e.coefficients.len() != 1 || e.constant.to_i64() != Some(-1) {
6678        return None;
6679    }
6680    let (&idx, coeff) = e.coefficients.iter().next()?;
6681    (coeff.to_i64() == Some(1)).then(|| Symbol::from_index(idx as usize))
6682}
6683
6684/// Is `e` a constant `<= 0` (no variables, non-positive)?
6685fn is_nonpos_const(e: &super::affine::LinExpr) -> bool {
6686    e.coefficients.is_empty() && !e.constant.is_positive()
6687}
6688
6689/// Is the linear expression `e` provably `>= 0` under the current per-variable
6690/// intervals? Evaluates `const + Σ coeff·interval(var)` and tests the lower
6691/// bound is a finite non-negative. A non-integer rational or a variable whose
6692/// interval is unbounded below (for a positive coefficient) fails closed.
6693fn lin_ge_zero(e: &super::affine::LinExpr, st: &RichAbstractState) -> bool {
6694    let Some(k) = e.constant.to_i64() else {
6695        return false;
6696    };
6697    let mut acc = Interval::exact(k);
6698    for (idx, coeff) in &e.coefficients {
6699        let Some(c) = coeff.to_i64() else {
6700            return false;
6701        };
6702        let sym = Symbol::from_index(*idx as usize);
6703        acc = acc.add(&Interval::exact(c).mul(&st.intervals.get_var(&sym)));
6704    }
6705    matches!(acc.lo, Bound::Finite(v) if v >= 0)
6706}
6707
6708fn observe_written_elem(collection: &Expr, value: &Expr, st: &mut RichAbstractState) {
6709    if let Expr::Identifier(sym) = collection {
6710        let v = eval_expr(value, &st.intervals);
6711        // The symbolic element upper of the written value, computed BEFORE the
6712        // mutations below (it reads other variables' bounds, never `sym`'s).
6713        let sym_up = value_upper(value, st);
6714        // The scalar TYPE of the written value, likewise BEFORE the mutations
6715        // (it reads `types`/`elem_type`, never the array's own future state).
6716        let sym_ty = eval_type(value, &st.types, &st.fn_returns, &st.elem_type);
6717        for a in st.aliases.may_alias(*sym) {
6718            // Freshness BEFORE the concrete update: a fresh array (⊥ element
6719            // interval) is SEEDED by the first write; a non-fresh one JOINS.
6720            let was_fresh = st.intervals.get_elem(&a).is_bottom();
6721            st.intervals.observe_elem(a, v.clone());
6722            // Element TYPE: every element must satisfy the join over all writes.
6723            // A fresh array is seeded; a non-fresh one joins. An unknown write
6724            // type (`Top`) forces the element type to ⊤, exactly as the symbolic
6725            // upper does — once an element's type is unknown, all reads are ⊤.
6726            if was_fresh {
6727                st.elem_type.insert(a, sym_ty.clone());
6728            } else {
6729                let joined = match st.elem_type.get(&a) {
6730                    Some(existing) => existing.join(&sym_ty),
6731                    None => TypeAbstraction::Top,
6732                };
6733                st.elem_type.insert(a, joined);
6734            }
6735            match &sym_up {
6736                // An unbounded written value forces the array's element upper to
6737                // ⊤ — every element must satisfy the bound, and this one doesn't.
6738                None => {
6739                    st.elem_upper.remove(&a);
6740                }
6741                Some(nb) => {
6742                    if was_fresh {
6743                        st.elem_upper.insert(a, nb.clone());
6744                    } else if let Some(existing) = st.elem_upper.get(&a).cloned() {
6745                        match join_sym_upper(&existing, nb, st) {
6746                            Some(m) => {
6747                                st.elem_upper.insert(a, m);
6748                            }
6749                            None => {
6750                                st.elem_upper.remove(&a);
6751                            }
6752                        }
6753                    }
6754                    // existing absent + non-fresh = ⊤ (a prior element was
6755                    // unbounded); a bounded write cannot recover it.
6756                }
6757            }
6758        }
6759    }
6760}
6761
6762fn rich_bind(var: Symbol, value: &Expr, st: &mut RichAbstractState) {
6763    let karr = karr_after_bind(var, value, st);
6764    let is_seq = sequence_length(value, st).is_some();
6765    rich_bind_facts(var, value, st);
6766    st.karr = karr;
6767    if is_seq {
6768        st.seq_vars.insert(var);
6769    } else {
6770        st.seq_vars.remove(&var);
6771    }
6772}
6773
6774/// The equalities after `var := value`, from the state before it: `var`'s new value when it is an Int affine over
6775/// the integers and sequence lengths, and its new length when it is a sequence. A name the value lends to a
6776/// callee's `mutable` parameter may come back as anything.
6777fn karr_after_bind(var: Symbol, value: &Expr, st: &RichAbstractState) -> super::karr::AffineSpace {
6778    let int_valued = matches!(
6779        eval_type(value, &st.types, &st.fn_returns, &st.elem_type),
6780        TypeAbstraction::Concrete(TypeTag::Int)
6781    );
6782    let lent: Vec<Symbol> = WriteSet::of_expr(value).symbols().collect();
6783    if lent.is_empty() {
6784        return karr_assigned(var, value, int_valued, st.karr.clone(), st);
6785    }
6786    let mut probe = RichAbstractState {
6787        karr: st.karr.clone(),
6788        aliases: st.aliases.clone(),
6789        seq_vars: st.seq_vars.clone(),
6790        seq_types: st.seq_types.clone(),
6791        len_summaries: st.len_summaries.clone(),
6792        ..RichAbstractState::new()
6793    };
6794    for name in lent {
6795        probe.karr_unknown(name);
6796    }
6797    let karr = std::mem::replace(&mut probe.karr, super::karr::AffineSpace::top());
6798    karr_assigned(var, value, int_valued, karr, &probe)
6799}
6800
6801/// `karr` after `var := value`, reading lengths through the sequences `lengths` tracks.
6802fn karr_assigned(
6803    var: Symbol,
6804    value: &Expr,
6805    int_valued: bool,
6806    mut karr: super::karr::AffineSpace,
6807    lengths: &RichAbstractState,
6808) -> super::karr::AffineSpace {
6809    use super::affine::{len_index, lin_of_with_lengths, var_index};
6810    let scalar = if int_valued {
6811        lin_of_with_lengths(value, &|c| lengths.seq_vars.contains(&c))
6812    } else {
6813        None
6814    };
6815    let length = sequence_length(value, lengths);
6816    karr.assign(var_index(var), scalar.as_ref());
6817    karr.assign(len_index(var), length.as_ref());
6818    karr
6819}
6820
6821/// The length of the sequence `value` makes, affine over the state before it, when it is one this walk tracks: a
6822/// new sequence (0), a list literal, a copy of or another name for a tracked sequence, or a call that returns a
6823/// sequence as long as a tracked one it is handed.
6824fn sequence_length(value: &Expr, st: &RichAbstractState) -> Option<super::affine::LinExpr> {
6825    use super::affine::{konst, len_var};
6826    let tracked = |e: &Expr| match e {
6827        Expr::Identifier(s) if st.seq_vars.contains(s) => Some(len_var(*s)),
6828        _ => None,
6829    };
6830    match value {
6831        Expr::New { type_name, .. } if st.seq_types.contains(type_name) => Some(konst(0)),
6832        Expr::List(items) => Some(konst(items.len() as i64)),
6833        Expr::Identifier(_) => tracked(value),
6834        Expr::Copy { expr } => tracked(expr),
6835        Expr::WithCapacity { value, .. } => sequence_length(value, st),
6836        Expr::Call { function, args } => tracked(args.get(*st.len_summaries.get(function)?)?),
6837        _ => None,
6838    }
6839}
6840
6841fn rich_bind_facts(var: Symbol, value: &Expr, st: &mut RichAbstractState) {
6842    // `WithCapacity` changes only the allocation strategy. Bind every semantic
6843    // fact (freshness, shape, length, element type and aliases) from the inner
6844    // value so an allocation hint cannot hide optimizations from this tier.
6845    // Capacity metadata itself is collected independently by `gather_map_caps`
6846    // and the backend-specific lowering.
6847    if let Expr::WithCapacity { value, .. } = value {
6848        rich_bind_facts(var, value, st);
6849        return;
6850    }
6851    st.aliases.unlink(var);
6852    // Writing `var` invalidates any length fact it participates in: the array
6853    // itself is rebound, or a size variable `n` in `length(arr) >= n + off`
6854    // is reassigned (so the old relation no longer holds).
6855    st.length_def.remove(&var);
6856    st.length_def.retain(|_, (n, _)| *n != var);
6857    // Likewise any affine scalar definition that names `var` (as the defined
6858    // variable or anywhere in another's right-hand side) is now stale.
6859    st.scalar_def.remove(&var);
6860    let vi = var.index() as i64;
6861    st.scalar_def
6862        .retain(|_, e| !e.coefficients.contains_key(&vi));
6863    // Symbolic bounds that name `var` (its own scalar upper, the element upper
6864    // of a rebound collection, or any bound whose RHS mentions `var`) are now
6865    // stale — drop them exactly like the affine scalar definitions above.
6866    st.scalar_upper.remove(&var);
6867    st.scalar_upper
6868        .retain(|_, e| !e.coefficients.contains_key(&vi));
6869    st.elem_upper.remove(&var);
6870    st.elem_upper
6871        .retain(|_, e| !e.coefficients.contains_key(&vi));
6872    // The element TYPE of a rebound collection is stale; its values can't name
6873    // another variable, so only its own entry needs dropping (re-seeded below
6874    // for a fresh/aliased collection by the element-write observers).
6875    st.elem_type.remove(&var);
6876    st.scalar_lower.remove(&var);
6877    st.scalar_lower
6878        .retain(|_, e| !e.coefficients.contains_key(&vi));
6879    // Rebinding resets `var`'s extern-length status; the producer arms below
6880    // re-establish it for aliases/copies/slices of an extern-length array.
6881    st.param_colls.remove(&var);
6882
6883    let iv = eval_expr(value, &st.intervals);
6884    st.intervals.set_var(var, iv);
6885    let value_ty = eval_type(value, &st.types, &st.fn_returns, &st.elem_type);
6886    st.types.insert(var, value_ty);
6887    st.nullability.insert(var, nullability_of_expr(value, st));
6888    // Rebinding discards the old binding's element bound; the producer arms
6889    // below re-establish it for fresh/aliased collections.
6890    st.intervals.clear_elem(&var);
6891    // Record an affine scalar definition `var = E` (E linear over ≥1 variable)
6892    // for the LIA bounds prover — a constant value is already in the interval
6893    // domain, so only variable-bearing forms are worth an equality fact. NEVER
6894    // record a SELF-REFERENTIAL update (`Set n to n + 10`): as an equality
6895    // `n = n + 10` it is the contradiction `0 = 10`, which would make the LIA
6896    // system inconsistent and prove every bound vacuously (unsound).
6897    if let Some(e) = super::affine::lin_of(value) {
6898        if !e.coefficients.is_empty() && !e.coefficients.contains_key(&(var.index() as i64)) {
6899            st.scalar_def.insert(var, e);
6900        }
6901    }
6902    // Symbolic UPPER bound for the new binding — `Let u be item _ of adj` carries
6903    // `adj`'s element upper, `Let neighbor be (...) % n` carries `n - 1`. A
6904    // self-referential bound (`Set x to x % n`) would be unsound to keep, so a
6905    // result naming `var` is dropped.
6906    if let Some(u) = value_upper(value, st) {
6907        if !u.coefficients.contains_key(&(var.index() as i64)) {
6908            st.scalar_upper.insert(var, u);
6909        }
6910    }
6911    if let Some(l) = value_lower(value, st) {
6912        if !l.coefficients.contains_key(&(var.index() as i64)) {
6913            st.scalar_lower.insert(var, l);
6914        }
6915    }
6916    // A3 LENGTH BINDING: `Let n be length of A` ⟹ `length(A) = n`, recorded as
6917    // the symbolic lower bound `length(A) >= n + 0` — the symmetric fact to a
6918    // build loop's `length_def`. Lets the bounds prover relate an index bounded
6919    // by `n` back to `A`'s length (string_search: `text[i+j]` with
6920    // `i+j <= textLen = length(text)`). Invalidated when `A` is resized/rebound
6921    // or `n` is reassigned, exactly like the build-loop fact. Holds for a String
6922    // too — its byte length is what the `as_bytes()[..]` access checks.
6923    if let Expr::Length { collection } = value {
6924        if let Expr::Identifier(a) = &**collection {
6925            if *a != var {
6926                st.length_def.insert(*a, (var, 0));
6927            }
6928        }
6929    }
6930
6931    match value {
6932        Expr::New { .. } => {
6933            st.shapes.insert(var, CollectionShape::Empty);
6934            st.intervals.set_length(var, Interval::exact(0));
6935            st.coll_vars.insert(var);
6936            // A fresh empty collection has NO elements: element bound `⊥`, so
6937            // the first `Push` seeds an exact bound and a 0-trip build loop's
6938            // exit join keeps the filled branch's bound.
6939            st.intervals.observe_elem(var, Interval::bottom());
6940        }
6941        Expr::List(items) | Expr::Tuple(items) => {
6942            let n = items.len() as u64;
6943            st.shapes
6944                .insert(var, CollectionShape::from_bounds(n, Some(n)));
6945            st.intervals
6946                .set_length(var, Interval::exact(items.len() as i64));
6947            st.coll_vars.insert(var);
6948            // Element bound = join of the literal items (`⊥` for an empty list).
6949            let mut el = Interval::bottom();
6950            for it in items.iter() {
6951                el = el.join(&eval_expr(it, &st.intervals));
6952            }
6953            st.intervals.observe_elem(var, el);
6954            // Element TYPE = join of the item types; an empty list stays fresh
6955            // (absent), so its later writes seed it exactly.
6956            let mut item_iter = items.iter();
6957            if let Some(first) = item_iter.next() {
6958                let mut ty = eval_type(first, &st.types, &st.fn_returns, &st.elem_type);
6959                for it in item_iter {
6960                    ty = ty.join(&eval_type(it, &st.types, &st.fn_returns, &st.elem_type));
6961                }
6962                st.elem_type.insert(var, ty);
6963            }
6964        }
6965        Expr::Identifier(src) => {
6966            // `v` and `src` are now two names for one allocation.
6967            st.aliases.link(var, *src);
6968            let shape = st.shapes.get(src).cloned().unwrap_or(CollectionShape::Top);
6969            st.shapes.insert(var, shape);
6970            let len = st.intervals.get_length(src);
6971            st.intervals.set_length(var, len);
6972            // The alias shares the element bound of its source.
6973            if st.intervals.elem.contains_key(src) {
6974                let e = st.intervals.get_elem(src);
6975                st.intervals.observe_elem(var, e);
6976            }
6977            // …and the source's element TYPE (one allocation, same elements).
6978            if let Some(t) = st.elem_type.get(src).cloned() {
6979                st.elem_type.insert(var, t);
6980            }
6981            if st.coll_vars.contains(src) {
6982                st.coll_vars.insert(var);
6983                // An alias of an extern-length array is itself extern-length.
6984                if st.param_colls.contains(src) {
6985                    st.param_colls.insert(var);
6986                }
6987            } else {
6988                st.coll_vars.remove(&var);
6989            }
6990            // An alias shares its source's symbolic length lower bound (one
6991            // allocation): `length(src) >= n` ⟹ `length(var) >= n`. The quicksort
6992            // partition reads `result` after `Let mutable result be arr`, so the
6993            // entry-guard fact on `arr` must flow to `result`. A later resize of
6994            // either name drops it (`rich_grow`/`rich_shrink` walk `may_alias`).
6995            // AOT-only: this rides on the entry-guard precondition, which only the
6996            // AOT codegen enforces — gated so the VM/JIT oracle is unchanged.
6997            if st.aot_entry_guard {
6998                if let Some(&(n, off)) = st.length_def.get(src) {
6999                    if n != var {
7000                        st.length_def.insert(var, (n, off));
7001                    }
7002                }
7003            }
7004        }
7005        Expr::Copy { expr } => {
7006            // A fresh unaliased value of the OPERAND's kind.
7007            st.shapes.insert(var, CollectionShape::Top);
7008            let from_coll =
7009                matches!(
7010                    expr,
7011                    Expr::Identifier(s) if st.coll_vars.contains(s)
7012                ) || matches!(expr, Expr::New { .. } | Expr::List(_) | Expr::Slice { .. });
7013            if from_coll {
7014                st.coll_vars.insert(var);
7015            } else {
7016                st.coll_vars.remove(&var);
7017            }
7018        }
7019        Expr::Slice { .. } => {
7020            // A slice that evaluates is always a fresh list.
7021            st.shapes.insert(var, CollectionShape::Top);
7022            st.coll_vars.insert(var);
7023        }
7024        _ => {
7025            // Unmodeled producer — kind unknown.
7026            st.shapes.insert(var, CollectionShape::Top);
7027            st.coll_vars.remove(&var);
7028            // Provenance: scalar and definitely-fresh producers stay
7029            // alias-tracked; anything that can RETURN AN EXISTING HANDLE —
7030            // calls, container extraction (Index/FieldAccess), opaque
7031            // escapes — taints the binding (it may alias anything).
7032            match value {
7033                Expr::Literal(_)
7034                | Expr::BinaryOp { .. }
7035                | Expr::Not { .. }
7036                | Expr::Length { .. }
7037                | Expr::Contains { .. }
7038                | Expr::Range { .. }
7039                | Expr::Union { .. }
7040                | Expr::Intersection { .. }
7041                | Expr::InterpolatedString(_)
7042                | Expr::OptionNone => {}
7043                _ => st.aliases.taint(var),
7044            }
7045        }
7046    }
7047}
7048
7049/// `Push`/`Add` — one element added to a shared allocation: grow the shape and
7050/// length of the collection and every variable that aliases it.
7051fn rich_grow(collection: &Expr, st: &mut RichAbstractState) {
7052    if let Expr::Identifier(sym) = collection {
7053        let new_shape = st
7054            .shapes
7055            .get(sym)
7056            .cloned()
7057            .unwrap_or(CollectionShape::Top)
7058            .pushed();
7059        let new_len = st.intervals.get_length(sym).add(&Interval::exact(1));
7060        for a in st.aliases.may_alias(*sym) {
7061            st.shapes.insert(a, new_shape.clone());
7062            st.intervals.set_length(a, new_len.clone());
7063            // A resize moves length off its build-time relation — drop it
7064            // (conservative; a grow keeps `>=` valid but we re-derive cleanly).
7065            st.length_def.remove(&a);
7066        }
7067    }
7068}
7069
7070/// `Pop`/`Remove` — one element removed from a shared allocation.
7071fn rich_shrink(collection: &Expr, st: &mut RichAbstractState) {
7072    if let Expr::Identifier(sym) = collection {
7073        let new_shape = st
7074            .shapes
7075            .get(sym)
7076            .cloned()
7077            .unwrap_or(CollectionShape::Top)
7078            .popped();
7079        let new_len = st.intervals.get_length(sym).sub(&Interval::exact(1));
7080        for a in st.aliases.may_alias(*sym) {
7081            st.shapes.insert(a, new_shape.clone());
7082            st.intervals.set_length(a, new_len.clone());
7083            // A shrink can break the `length(arr) >= n` lower bound — drop it.
7084            st.length_def.remove(&a);
7085        }
7086    }
7087}
7088
7089fn nullability_of_expr(expr: &Expr, st: &RichAbstractState) -> Nullability {
7090    match expr {
7091        Expr::Literal(lit) => Nullability::for_literal(lit),
7092        Expr::Identifier(s) => st.nullability.get(s).cloned().unwrap_or(Nullability::Maybe),
7093        Expr::New { .. }
7094        | Expr::NewVariant { .. }
7095        | Expr::List(_)
7096        | Expr::Tuple(_)
7097        | Expr::Range { .. }
7098        | Expr::BinaryOp { .. }
7099        | Expr::Not { .. }
7100        | Expr::Length { .. }
7101        | Expr::Contains { .. } => Nullability::Definite,
7102        // Index/Call/FieldAccess may yield `nothing`: stay conservative.
7103        _ => Nullability::Maybe,
7104    }
7105}
7106
7107fn pattern_loop_var(p: &Pattern) -> Option<Symbol> {
7108    match p {
7109        Pattern::Identifier(s) => Some(*s),
7110        _ => None,
7111    }
7112}
7113
7114fn rich_walk_if(
7115    cond: &Expr,
7116    then_block: &[Stmt],
7117    else_block: Option<&[Stmt]>,
7118    st: &mut RichAbstractState,
7119    facts: &mut OracleFacts,
7120) {
7121    match eval_condition(cond, &st.intervals) {
7122        Some(true) => {
7123            narrow_state(cond, &mut st.intervals);
7124            rich_walk_block(then_block, st, facts);
7125        }
7126        Some(false) => {
7127            if let Some(eb) = else_block {
7128                narrow_state_negated(cond, &mut st.intervals);
7129                rich_walk_block(eb, st, facts);
7130            }
7131        }
7132        None => {
7133            let mut then_st = st.clone();
7134            narrow_state(cond, &mut then_st.intervals);
7135            rich_walk_block(then_block, &mut then_st, facts);
7136
7137            let mut else_st = st.clone();
7138            narrow_state_negated(cond, &mut else_st.intervals);
7139            if let Some(eb) = else_block {
7140                rich_walk_block(eb, &mut else_st, facts);
7141            }
7142
7143            *st = rich_join(&then_st, &else_st);
7144        }
7145    }
7146}
7147
7148/// Refine a loop-INVARIANT bound variable's interval lower from the guard the
7149/// body entry implies: `i < n` with `i` at its pre-loop value `i0` proves
7150/// `n > i0` (`n >= i0 + 1`); `i <= n` proves `n >= i0`. Sound because `n` is not
7151/// mutated, so the relation established at first entry holds for the whole body.
7152/// Descends through `and` and accepts the flipped `n > i` / `n >= i` forms.
7153fn refine_invariant_bound_from_guard(
7154    cond: &Expr,
7155    pre: &RichAbstractState,
7156    mutated: &[Symbol],
7157    out: &mut AbstractState,
7158) {
7159    if let Expr::BinaryOp {
7160        op: BinaryOpKind::And,
7161        left,
7162        right,
7163    } = cond
7164    {
7165        refine_invariant_bound_from_guard(left, pre, mutated, out);
7166        refine_invariant_bound_from_guard(right, pre, mutated, out);
7167        return;
7168    }
7169    let Expr::BinaryOp { op, left, right } = cond else {
7170        return;
7171    };
7172    let (iv_e, bnd_e, strict) = match op {
7173        BinaryOpKind::Lt => (left, right, true),
7174        BinaryOpKind::LtEq => (left, right, false),
7175        BinaryOpKind::Gt => (right, left, true),
7176        BinaryOpKind::GtEq => (right, left, false),
7177        _ => return,
7178    };
7179    let (Expr::Identifier(iv), Expr::Identifier(bnd)) = (iv_e, bnd_e) else {
7180        return;
7181    };
7182    if mutated.contains(bnd) {
7183        return; // the bound must be loop-invariant for the relation to persist
7184    }
7185    let Bound::Finite(i0) = pre.intervals.get_var(iv).lo else {
7186        return;
7187    };
7188    let Some(new_lo) = (if strict { i0.checked_add(1) } else { Some(i0) }) else {
7189        return;
7190    };
7191    let cur = out.get_var(bnd);
7192    out.set_var(
7193        *bnd,
7194        Interval {
7195            lo: Bound::max_bound(&cur.lo, &Bound::Finite(new_lo)),
7196            hi: cur.hi,
7197        },
7198    );
7199}
7200
7201/// Widening-to-fixpoint loop analysis (EXODIA 1.1): iterate the body
7202/// transfer, widening the mutated variables' facts between passes through
7203/// the threshold ladder; on convergence the recorded body facts hold at the
7204/// loop invariant. A non-converging loop (cap hit) falls back to the sound
7205/// invalidate-everything treatment for whatever is still unstable.
7206/// How deep a loop may sit inside enclosing loops' fixpoints and still get a fixpoint of its own.
7207/// Each fixpoint walks its body four times (two ascent passes, a narrowing probe, the recording pass),
7208/// and every walk re-analyzes the loops nested inside — 4^depth on a deep nest, which the recursive
7209/// inliner produces routinely (eight unfolded levels of `solve`). Beyond this depth a loop is walked
7210/// once with everything it may write widened: sound, linear, and it only forfeits precision deep in a
7211/// nest.
7212const MAX_FIXPOINT_NESTING: usize = 4;
7213
7214fn rich_walk_loop(
7215    cond: Option<&Expr>,
7216    body: &[Stmt],
7217    st: &mut RichAbstractState,
7218    loop_var: Option<Symbol>,
7219    facts: &mut OracleFacts,
7220    loop_key: Option<usize>,
7221) {
7222    let body_writes = WriteSet::of_block(body).with_callee_globals(&st.callee_globals);
7223    if body_writes.is_opaque() {
7224        // Foreign code in the body may rewrite anything: no fact survives the loop.
7225        st.forget_everything();
7226        return;
7227    }
7228    let mut mutated: Vec<Symbol> = body_writes.symbols().collect();
7229    if let Some(lv) = loop_var {
7230        if !mutated.contains(&lv) {
7231            mutated.push(lv);
7232        }
7233    }
7234    // A loop a `Break` of its own can end leaves with its condition still holding and with what its last
7235    // iteration wrote before breaking: neither the negated condition nor the loop head's facts hold after it.
7236    let breaks = crate::loop_shape::leaves_by_break(body);
7237    if facts.loop_depth >= MAX_FIXPOINT_NESTING {
7238        rich_walk_loop_widened(cond, body, st, &mutated, breaks, facts, loop_key);
7239        return;
7240    }
7241    facts.loop_depth += 1;
7242    rich_walk_loop_fixpoint(cond, body, st, loop_var, &mutated, breaks, facts, loop_key);
7243    facts.loop_depth -= 1;
7244}
7245
7246/// The bounded-nesting path: everything the loop may write is unknown from its first iteration on,
7247/// then ONE pass over the body under that widened state records the facts inside it (a fact that
7248/// holds with every written name at ⊤ holds on every iteration).
7249fn rich_walk_loop_widened(
7250    cond: Option<&Expr>,
7251    body: &[Stmt],
7252    st: &mut RichAbstractState,
7253    mutated: &[Symbol],
7254    breaks: bool,
7255    facts: &mut OracleFacts,
7256    loop_key: Option<usize>,
7257) {
7258    for &m in mutated {
7259        st.karr_unknown(m);
7260        st.invalidate_var(m);
7261        st.aliases.unlink(m);
7262        st.intervals.set_length(m, Interval::non_negative());
7263        st.length_def.remove(&m);
7264    }
7265    let mut record_state = st.clone();
7266    if let Some(c) = cond {
7267        narrow_state(c, &mut record_state.intervals);
7268    }
7269    // Record the SAME facts the converged path records, from the widened state. Every one of them is
7270    // a statement about all iterations, and a fact that survives having each written name widened to
7271    // `top` survives every iteration — so the facts are weaker here, never wrong. They must still be
7272    // recorded: codegen's borrow-hoist reads `loop_aliases` KEYED BY THIS LOOP'S ADDRESS, and a loop
7273    // that contributes no entry makes codegen plan against a different picture than the one the
7274    // walk built (an aliased buffer hoisted to a slice at the loop head while a statement inside it
7275    // still emits the `Rc<RefCell<…>>` form — Rust that does not compile).
7276    if let Some(key) = loop_key {
7277        match facts.loop_aliases.entry(key) {
7278            std::collections::hash_map::Entry::Occupied(mut e) => {
7279                e.get_mut().union_from(&record_state.aliases);
7280            }
7281            std::collections::hash_map::Entry::Vacant(v) => {
7282                v.insert(record_state.aliases.clone());
7283            }
7284        }
7285    }
7286    let header = record_state.clone();
7287    if let Some(c) = cond {
7288        record_loop_index_bounds(c, body, &record_state, facts);
7289        record_affine_index_bounds(c, body, &record_state, st, facts, false);
7290        if let Some(key) = loop_key {
7291            record_hoist_speculation(c, body, &record_state, facts, key);
7292        }
7293    }
7294    rich_walk_block(body, &mut record_state, facts);
7295    if let Some(c) = cond {
7296        record_expr(c, &record_state, facts);
7297        record_affine_index_bounds(c, body, &header, st, facts, true);
7298    }
7299    if let Some(c) = cond.filter(|_| !breaks) {
7300        narrow_state_negated(c, &mut st.intervals);
7301    }
7302}
7303
7304fn rich_walk_loop_fixpoint(
7305    cond: Option<&Expr>,
7306    body: &[Stmt],
7307    st: &mut RichAbstractState,
7308    loop_var: Option<Symbol>,
7309    mutated: &[Symbol],
7310    breaks: bool,
7311    facts: &mut OracleFacts,
7312    loop_key: Option<usize>,
7313) {
7314    let mutated: Vec<Symbol> = mutated.to_vec();
7315    // Repeat loop variables hold unknown element values inside the body —
7316    // and the element handle could be ANY handle stored in the iterable.
7317    let mut inside = st.clone();
7318    if let Some(lv) = loop_var {
7319        inside.invalidate_var(lv);
7320        inside.aliases.unlink(lv);
7321        inside.aliases.taint(lv);
7322    }
7323    if let Some(c) = cond {
7324        narrow_state(c, &mut inside.intervals);
7325        // The loop body implies its guard at first entry: `i < n` with `i` at
7326        // its pre-loop value `i0` proves `n > i0`, i.e. `n >= i0 + 1`. Since `n`
7327        // is loop-invariant (not mutated), this lower holds throughout the body
7328        // — it is what lets a `% n` element bound `n - 1` dominate a constant
7329        // zero-init in the symbolic element join (graph_bfs's adjacency array).
7330        refine_invariant_bound_from_guard(c, st, &mutated, &mut inside.intervals);
7331    }
7332
7333    // Fixpoint over the mutated set: facts recorded into a SINK during the
7334    // ascent (intermediate states are not loop invariants).
7335    let mut sink = OracleFacts::default();
7336    sink.loop_depth = facts.loop_depth;
7337    let mut converged = false;
7338    for pass in 0..12 {
7339        let mut next = inside.clone();
7340        rich_walk_block(body, &mut next, &mut sink);
7341        if let Some(c) = cond {
7342            narrow_state(c, &mut next.intervals);
7343        }
7344        // Widen the mutated variables; everything else keeps the entry fact
7345        // (sound: un-mutated vars are loop-invariant).
7346        let mut stable = true;
7347        for &m in &mutated {
7348            // Captured BEFORE the concrete element merge below overwrites the
7349            // ⊥-ness: a fresh entry seeds the symbolic element upper from `next`.
7350            let inside_fresh_elem = inside.intervals.get_elem(&m).is_bottom();
7351            let cur_iv = inside.intervals.get_var(&m);
7352            let nxt_iv = next.intervals.get_var(&m);
7353            let wid = cur_iv.widen(&nxt_iv);
7354            if !wid.leq(&cur_iv) || !cur_iv.leq(&wid) {
7355                stable = false;
7356            }
7357            inside.intervals.set_var(m, wid);
7358            // A length still growing is not a converged loop: a list the body pushes onto reaches a new
7359            // length every pass, and the pass that stops looking is not the last one the program runs.
7360            let cur_len = inside.intervals.get_length(&m);
7361            let nxt_len = next.intervals.get_length(&m);
7362            let wid_len = cur_len.widen(&nxt_len);
7363            if !wid_len.leq(&cur_len) || !cur_len.leq(&wid_len) {
7364                stable = false;
7365            }
7366            inside.intervals.set_length(m, wid_len);
7367
7368            // Element bound: DELAYED widening. Join for the first few passes so
7369            // a bound fed by an external converging value settles EXACTLY
7370            // (`(seed/65536) % 1000 → [0,999]`, which a threshold widen would
7371            // round up to 1000 and lose by one), then widen so a SELF-feeding
7372            // accumulator (`counts[v] += 1`, growing by 1 each pass) escapes to
7373            // ±∞ and converges instead of pinning the loop to the iteration cap
7374            // (which forces the blunt invalidate-everything fallback, losing the
7375            // length fact). A wider element bound is always sound.
7376            if inside.intervals.elem.contains_key(&m) || next.intervals.elem.contains_key(&m) {
7377                let cur_el = inside.intervals.get_elem(&m);
7378                let nxt_el = next.intervals.get_elem(&m);
7379                let merged = if pass < 3 {
7380                    cur_el.join(&nxt_el)
7381                } else {
7382                    cur_el.widen(&nxt_el)
7383                };
7384                if !(merged.leq(&cur_el) && cur_el.leq(&merged)) {
7385                    stable = false;
7386                }
7387                inside.intervals.elem.insert(m, merged);
7388            }
7389
7390            // Symbolic element upper — the variable-divisor sibling of the
7391            // concrete elem above. Seeded from `next` on a fresh entry, then an
7392            // equality/domination merge (a symbolic LinExpr is its own fixed
7393            // point, so no widening); drops to ⊤ on disagreement.
7394            let merged_sym = if inside_fresh_elem {
7395                next.elem_upper.get(&m).cloned()
7396            } else {
7397                match (
7398                    inside.elem_upper.get(&m).cloned(),
7399                    next.elem_upper.get(&m).cloned(),
7400                ) {
7401                    (Some(e), Some(n)) => join_sym_upper(&e, &n, &next),
7402                    _ => None,
7403                }
7404            };
7405            if inside.elem_upper.get(&m) != merged_sym.as_ref() {
7406                stable = false;
7407            }
7408            match merged_sym {
7409                Some(l) => {
7410                    inside.elem_upper.insert(m, l);
7411                }
7412                None => {
7413                    inside.elem_upper.remove(&m);
7414                }
7415            }
7416            // Element TYPE — the type sibling of the concrete elem above. Seeded
7417            // from `next` on a fresh entry, then JOINED across the back-edge. The
7418            // type lattice is finite-height (`widen == join`, capped union), so a
7419            // plain join converges; a divergent type lands at ⊤ (sound: every
7420            // element must satisfy the join, so a wider type only forfeits the
7421            // elision). Stability participates in the fixpoint check.
7422            let merged_et = if inside_fresh_elem {
7423                next.elem_type.get(&m).cloned()
7424            } else {
7425                match (
7426                    inside.elem_type.get(&m).cloned(),
7427                    next.elem_type.get(&m).cloned(),
7428                ) {
7429                    (Some(e), Some(n)) => Some(e.join(&n)),
7430                    _ => None,
7431                }
7432            };
7433            if inside.elem_type.get(&m) != merged_et.as_ref() {
7434                stable = false;
7435            }
7436            match merged_et {
7437                Some(t) => {
7438                    inside.elem_type.insert(m, t);
7439                }
7440                None => {
7441                    inside.elem_type.remove(&m);
7442                }
7443            }
7444            // A mutated SCALAR's `scalar_upper` (the element/modulo bound on `u =
7445            // item _ of adj`, re-established by its in-body `Let` every pass) IS
7446            // a loop invariant when stable: build it up from the first defining
7447            // pass, keep it while it holds, drop it the moment it diverges or
7448            // vanishes (so the fixpoint converges instead of oscillating).
7449            let merged_su = match (
7450                inside.scalar_upper.get(&m).cloned(),
7451                next.scalar_upper.get(&m).cloned(),
7452            ) {
7453                (Some(a), Some(b)) if a == b => Some(a),
7454                (None, Some(b)) => Some(b),
7455                _ => None,
7456            };
7457            if inside.scalar_upper.get(&m) != merged_su.as_ref() {
7458                stable = false;
7459            }
7460            match merged_su {
7461                Some(l) => {
7462                    inside.scalar_upper.insert(m, l);
7463                }
7464                None => {
7465                    inside.scalar_upper.remove(&m);
7466                }
7467            }
7468            let merged_sl = match (
7469                inside.scalar_lower.get(&m).cloned(),
7470                next.scalar_lower.get(&m).cloned(),
7471            ) {
7472                (Some(a), Some(b)) if a == b => Some(a),
7473                (None, Some(b)) => Some(b),
7474                _ => None,
7475            };
7476            if inside.scalar_lower.get(&m) != merged_sl.as_ref() {
7477                stable = false;
7478            }
7479            match merged_sl {
7480                Some(l) => {
7481                    inside.scalar_lower.insert(m, l);
7482                }
7483                None => {
7484                    inside.scalar_lower.remove(&m);
7485                }
7486            }
7487
7488            let cur_ty = inside
7489                .types
7490                .get(&m)
7491                .cloned()
7492                .unwrap_or(TypeAbstraction::Top);
7493            let nxt_ty = next.types.get(&m).cloned().unwrap_or(TypeAbstraction::Top);
7494            let j = cur_ty.join(&nxt_ty);
7495            if !(j.leq(&cur_ty) && cur_ty.leq(&j)) {
7496                stable = false;
7497            }
7498            inside.types.insert(m, j);
7499
7500            let cur_sh = inside
7501                .shapes
7502                .get(&m)
7503                .cloned()
7504                .unwrap_or(CollectionShape::Top);
7505            let nxt_sh = next.shapes.get(&m).cloned().unwrap_or(CollectionShape::Top);
7506            inside.shapes.insert(m, cur_sh.widen(&nxt_sh));
7507
7508            // Kind survives growth, but a rebinding inside the body
7509            // (absent from `next`) drops the proof.
7510            if !next.coll_vars.contains(&m) {
7511                inside.coll_vars.remove(&m);
7512            }
7513
7514            let cur_n = inside
7515                .nullability
7516                .get(&m)
7517                .cloned()
7518                .unwrap_or(Nullability::Maybe);
7519            let nxt_n = next
7520                .nullability
7521                .get(&m)
7522                .cloned()
7523                .unwrap_or(Nullability::Maybe);
7524            inside.nullability.insert(m, cur_n.join(&nxt_n));
7525        }
7526        // Loop-CARRIED aliasing: an edge created at the end of one iteration
7527        // (`Set prev to curr`) holds at the top of the next, so the alias
7528        // graph joins by union across the back-edge. Monotone over a finite
7529        // symbol set — converges. Growth participates in the stability check.
7530        if inside.aliases.union_from(&next.aliases) {
7531            stable = false;
7532        }
7533        // The equalities at the header hold on entry and after every pass: the hull of both. Each growth raises its
7534        // dimension, so it settles within a pass per quantity it relates.
7535        let hull = inside.karr.join(&next.karr);
7536        if !hull.leq(&inside.karr) {
7537            stable = false;
7538        }
7539        inside.karr = hull;
7540        let seqs_before = inside.seq_vars.len();
7541        inside.seq_vars.retain(|s| next.seq_vars.contains(s));
7542        if inside.seq_vars.len() != seqs_before {
7543            stable = false;
7544        }
7545        if stable {
7546            converged = true;
7547            break;
7548        }
7549    }
7550
7551    if converged {
7552        // The converged alias graph IS the loop invariant — snapshot it for
7553        // the distinctness queries (borrow hoisting). Non-converged loops
7554        // record nothing: queries refuse by default.
7555        if let Some(key) = loop_key {
7556            match facts.loop_aliases.entry(key) {
7557                std::collections::hash_map::Entry::Occupied(mut e) => {
7558                    e.get_mut().union_from(&inside.aliases);
7559                }
7560                std::collections::hash_map::Entry::Vacant(v) => {
7561                    v.insert(inside.aliases.clone());
7562                }
7563            }
7564        }
7565        // NARROWING (Cousot descending iteration). The widening above accelerates
7566        // ascending chains by throwing a still-growing bound to ±∞ — sound, but it
7567        // discards the finite bound a MODULO re-establishes every iteration
7568        // (`b = (a + b) % M` re-clamps `b` to `[0, M-1]` no matter the entry). Re-
7569        // applying the body from the widened post-fixpoint and keeping every
7570        // finite bound while replacing only ±∞ descends back toward the true
7571        // invariant, STAYING a sound over-approximation (`inside ⊒ lfp` ⟹
7572        // `F(inside) ⊒ lfp`). It is the license the raw-i64 lowering needs:
7573        // recovering `a, b ∈ [0, M-1]` proves `a + b` fits i64, so the overflow
7574        // guard is dropped and the hot loop matches C. Scoped to scalar var
7575        // intervals (the arithmetic-guard input); element/length/shape facts,
7576        // already converged, are untouched. Bounded — each pass fills ≥1 ±∞.
7577        const NARROW_PASSES: usize = 4;
7578        for _ in 0..NARROW_PASSES {
7579            let mut probe = inside.clone();
7580            let mut narrow_sink = OracleFacts::default();
7581            narrow_sink.loop_depth = facts.loop_depth;
7582            rich_walk_block(body, &mut probe, &mut narrow_sink);
7583            if let Some(c) = cond {
7584                narrow_state(c, &mut probe.intervals);
7585            }
7586            let mut tightened = false;
7587            for &m in &mutated {
7588                let cur = inside.intervals.get_var(&m);
7589                let narrowed = cur.narrow(&probe.intervals.get_var(&m));
7590                if !(narrowed.leq(&cur) && cur.leq(&narrowed)) {
7591                    tightened = true;
7592                }
7593                inside.intervals.set_var(m, narrowed);
7594            }
7595            if !tightened {
7596                break;
7597            }
7598        }
7599
7600        // Record body facts at the invariant UNDER the loop condition (the
7601        // body only runs when it holds), then build the after-state: the
7602        // loop may run zero times (entry state) or exit from the invariant
7603        // — join, then apply the negated condition.
7604        let mut record_state = inside.clone();
7605        if let Some(c) = cond {
7606            narrow_state(c, &mut record_state.intervals);
7607        }
7608        // RELATIONAL induction-variable bound (V8/LLVM SCEV): a guard that
7609        // bounds an index variable by an array's length lets every
7610        // `item i of arr` read in the body skip its bounds check. Then the
7611        // SPECULATIVE hoist: arrays whose length is not statically known get a
7612        // single region-entry runtime check instead.
7613        let header = record_state.clone();
7614        if let Some(c) = cond {
7615            record_loop_index_bounds(c, body, &record_state, facts);
7616            // GENERAL multi-variable proof (kernel LIA): catches the affine
7617            // indices the single-var recognizer above cannot — knapsack's
7618            // `prev[w-wi+1]` under a path guard, nested-loop windows, scatter
7619            // indices bounded through element ranges. Idempotent with the
7620            // single-var path (both feed the same `relational_inbounds` set).
7621            record_affine_index_bounds(c, body, &record_state, st, facts, false);
7622            if let Some(key) = loop_key {
7623                record_hoist_speculation(c, body, &record_state, facts, key);
7624            }
7625        }
7626        rich_walk_block(body, &mut record_state, facts);
7627        // The condition is evaluated again after every iteration, at what the body leaves: its facts join that
7628        // state to the entry state `record_stmt_exprs` recorded them at.
7629        if let Some(c) = cond {
7630            record_expr(c, &record_state, facts);
7631        }
7632        // The equalities each access is evaluated under are recorded now: prove from them.
7633        if let Some(c) = cond {
7634            record_affine_index_bounds(c, body, &header, st, facts, true);
7635        }
7636        let mut after = rich_join(st, &inside);
7637        if breaks {
7638            after.forget_written(&mutated);
7639        } else if let Some(c) = cond {
7640            narrow_state_negated(c, &mut after.intervals);
7641            karr_counted_exit(c, body, st, &mut after);
7642            // Allocation-size fact: a counted build loop establishes a length
7643            // bound on the array it fills (`st` is the pre-loop entry state —
7644            // the array's emptiness and the counter's start are read there).
7645            // A variable bound gives a symbolic lower bound (consumed by the
7646            // relational recognizer); a literal bound gives a concrete exact
7647            // length (consumed by the interval bounds check directly).
7648            for bl in infer_build_length(c, body, st) {
7649                match bl {
7650                    BuildLength::Symbolic(arr, n, off) => {
7651                        after.length_def.insert(arr, (n, off));
7652                    }
7653                    BuildLength::Concrete(arr, len) => {
7654                        after.intervals.set_length(arr, len);
7655                    }
7656                }
7657            }
7658        }
7659        // Loop-EXIT induction bound for the entry-guarded partition's pivot swap.
7660        // For `while j < hi` where `j` is a top-level unconditional `+1` counter and
7661        // `i` a monotone-increasing var sharing `j`'s loop-entry def, the strict
7662        // guard with `Δj = 1` lands `j` on exactly `hi` at exit, and the loop
7663        // invariant `i <= j` (equal start, `Δi <= Δj`) then gives `i <= hi` AFTER the
7664        // loop; `i >= lo` holds since `i` only rises from its init `lo`. Record
7665        // `lo <= i <= hi` as symbolic bounds so the following top-level `item i of
7666        // arr` (proven by the inlined entry-guard walk) discharges. Gated to the
7667        // entry-guarded functions (`entry_guard_lowers` non-empty) so no other
7668        // program's loops are affected; SOUND — both bounds hold throughout the
7669        // post-loop region, where `i` is not written (a later write clears them).
7670        if !breaks && !st.entry_guard_lowers.is_empty() {
7671            if let Some(Expr::BinaryOp {
7672                op: BinaryOpKind::Lt,
7673                left: Expr::Identifier(j),
7674                right: Expr::Identifier(hi),
7675            }) = cond
7676            {
7677                if top_level_unconditional_incs(body, &st.callee_globals)
7678                    .iter()
7679                    .any(|(v, d)| v == j && *d == 1)
7680                {
7681                    for i in monotone_inc_vars(body, 1) {
7682                        if i != *j {
7683                            if let (Some(di), Some(dj)) =
7684                                (st.scalar_def.get(&i), st.scalar_def.get(j))
7685                            {
7686                                if di == dj {
7687                                    let lo_def = di.clone();
7688                                    after.scalar_lower.entry(i).or_insert(lo_def);
7689                                    after
7690                                        .scalar_upper
7691                                        .entry(i)
7692                                        .or_insert_with(|| super::affine::var(*hi));
7693                                }
7694                            }
7695                        }
7696                    }
7697                }
7698            }
7699        }
7700        *st = after;
7701    } else {
7702        // Sound fallback: forget everything the body can write.
7703        if let Some(c) = cond.filter(|_| !breaks) {
7704            narrow_state_negated(c, &mut st.intervals);
7705        }
7706        for m in mutated {
7707            st.karr_unknown(m);
7708            st.intervals.set_var(m, Interval::top());
7709            st.intervals.set_length(m, Interval::non_negative());
7710            st.types.insert(m, TypeAbstraction::Top);
7711            st.shapes.insert(m, CollectionShape::Top);
7712            st.nullability.insert(m, Nullability::Maybe);
7713            st.coll_vars.remove(&m);
7714        }
7715    }
7716}
7717
7718fn rich_walk_inspect(
7719    target: &Expr,
7720    arms: &[MatchArm],
7721    st: &mut RichAbstractState,
7722    facts: &mut OracleFacts,
7723) {
7724    if arms.is_empty() {
7725        return;
7726    }
7727    let mut acc: Option<RichAbstractState> = None;
7728    for arm in arms {
7729        let mut arm_st = st.clone();
7730        // A concrete-variant arm proves the scrutinee (and its field bindings)
7731        // present — this is what lets the unwrap/`nothing` guard be removed.
7732        if arm.variant.is_some() {
7733            if let Expr::Identifier(sym) = target {
7734                arm_st.nullability.insert(*sym, Nullability::Definite);
7735            }
7736            for (_field, binding) in &arm.bindings {
7737                arm_st.nullability.insert(*binding, Nullability::Definite);
7738            }
7739        }
7740        // Field bindings extract handles from the scrutinee — unknown
7741        // provenance for the alias domain.
7742        for (_field, binding) in &arm.bindings {
7743            arm_st.aliases.unlink(*binding);
7744            arm_st.aliases.taint(*binding);
7745        }
7746        rich_walk_block(arm.body, &mut arm_st, facts);
7747        acc = Some(match acc {
7748            None => arm_st,
7749            Some(prev) => rich_join(&prev, &arm_st),
7750        });
7751    }
7752    if let Some(joined) = acc {
7753        *st = joined;
7754    }
7755}
7756
7757fn rich_join(a: &RichAbstractState, b: &RichAbstractState) -> RichAbstractState {
7758    let mut intervals = AbstractState::new();
7759    join_states(&mut intervals, &a.intervals, &b.intervals);
7760    RichAbstractState {
7761        intervals,
7762        types: join_maps(&a.types, &b.types),
7763        shapes: join_maps(&a.shapes, &b.shapes),
7764        nullability: join_maps(&a.nullability, &b.nullability),
7765        aliases: alias_union(&a.aliases, &b.aliases),
7766        // Kind proven only where BOTH paths prove it.
7767        coll_vars: a.coll_vars.intersection(&b.coll_vars).cloned().collect(),
7768        fn_returns: a.fn_returns.clone(),
7769        callee_globals: a.callee_globals.clone(),
7770        // A length fact survives a join only where both paths agree exactly.
7771        length_def: a
7772            .length_def
7773            .iter()
7774            .filter(|(k, v)| b.length_def.get(k) == Some(v))
7775            .map(|(k, v)| (*k, *v))
7776            .collect(),
7777        // Parameter-collection membership is a function-entry constant.
7778        param_colls: a.param_colls.union(&b.param_colls).copied().collect(),
7779        // A scalar definition survives a join only where both paths define it
7780        // to the SAME affine expression.
7781        scalar_def: a
7782            .scalar_def
7783            .iter()
7784            .filter(|(k, v)| b.scalar_def.get(*k) == Some(*v))
7785            .map(|(k, v)| (*k, v.clone()))
7786            .collect(),
7787        // Symbolic upper bounds survive a join only where both paths carry the
7788        // SAME bound — a divergent (or absent-on-one-side) bound is ⊤. Sound:
7789        // dropping a bound only forfeits an elision, never licenses one.
7790        scalar_upper: a
7791            .scalar_upper
7792            .iter()
7793            .filter(|(k, v)| b.scalar_upper.get(*k) == Some(*v))
7794            .map(|(k, v)| (*k, v.clone()))
7795            .collect(),
7796        elem_upper: join_elem_upper_maps(a, b),
7797        elem_type: join_elem_type_maps(a, b),
7798        scalar_lower: a
7799            .scalar_lower
7800            .iter()
7801            .filter(|(k, v)| b.scalar_lower.get(*k) == Some(*v))
7802            .map(|(k, v)| (*k, v.clone()))
7803            .collect(),
7804        // A function-entry constant (both joined states are the same body), so
7805        // it survives every merge and reaches the post-branch alias binds.
7806        aot_entry_guard: a.aot_entry_guard || b.aot_entry_guard,
7807        entry_guard_lowers: if a.entry_guard_lowers.is_empty() {
7808            b.entry_guard_lowers.clone()
7809        } else {
7810            a.entry_guard_lowers.clone()
7811        },
7812        karr: a.karr.join(&b.karr),
7813        seq_vars: a.seq_vars.intersection(&b.seq_vars).copied().collect(),
7814        seq_types: a.seq_types.clone(),
7815        len_summaries: a.len_summaries.clone(),
7816    }
7817}
7818
7819/// Join the per-collection symbolic element uppers under the "EVERY element
7820/// satisfies it" reading, mirroring the concrete element interval's ⊥-seed: a
7821/// side whose array is ⊥ (a fresh `new Seq`, no elements) contributes nothing,
7822/// so the OTHER side's bound carries across the 0-iteration exit branch of a
7823/// build loop. When both sides hold elements the bounds must agree (or one
7824/// dominate); otherwise the bound is lost to ⊤.
7825fn join_elem_upper_maps(
7826    a: &RichAbstractState,
7827    b: &RichAbstractState,
7828) -> HashMap<Symbol, super::affine::LinExpr> {
7829    let mut out = HashMap::new();
7830    let keys: HashSet<Symbol> = a
7831        .elem_upper
7832        .keys()
7833        .chain(b.elem_upper.keys())
7834        .cloned()
7835        .collect();
7836    for key in keys {
7837        let a_bot = a.intervals.get_elem(&key).is_bottom();
7838        let b_bot = b.intervals.get_elem(&key).is_bottom();
7839        let v = if a_bot {
7840            b.elem_upper.get(&key).cloned()
7841        } else if b_bot {
7842            a.elem_upper.get(&key).cloned()
7843        } else {
7844            match (a.elem_upper.get(&key), b.elem_upper.get(&key)) {
7845                (Some(x), Some(y)) => join_sym_upper(x, y, b),
7846                _ => None,
7847            }
7848        };
7849        if let Some(l) = v {
7850            out.insert(key, l);
7851        }
7852    }
7853    out
7854}
7855
7856/// Join the per-collection element TYPES under the "EVERY element satisfies it"
7857/// reading, mirroring [`join_elem_upper_maps`]'s ⊥-seed: a side whose array is ⊥
7858/// (a fresh `new Seq`, no elements) contributes nothing, so the OTHER side's type
7859/// carries across the 0-iteration exit branch of a build loop. When both sides
7860/// hold elements the types JOIN (a divergent pair lands at ⊤, sound).
7861fn join_elem_type_maps(
7862    a: &RichAbstractState,
7863    b: &RichAbstractState,
7864) -> HashMap<Symbol, TypeAbstraction> {
7865    let mut out = HashMap::new();
7866    let keys: HashSet<Symbol> = a
7867        .elem_type
7868        .keys()
7869        .chain(b.elem_type.keys())
7870        .cloned()
7871        .collect();
7872    for key in keys {
7873        let a_bot = a.intervals.get_elem(&key).is_bottom();
7874        let b_bot = b.intervals.get_elem(&key).is_bottom();
7875        let v = if a_bot {
7876            b.elem_type.get(&key).cloned()
7877        } else if b_bot {
7878            a.elem_type.get(&key).cloned()
7879        } else {
7880            match (a.elem_type.get(&key), b.elem_type.get(&key)) {
7881                (Some(x), Some(y)) => Some(x.join(y)),
7882                _ => None,
7883            }
7884        };
7885        if let Some(t) = v {
7886            out.insert(key, t);
7887        }
7888    }
7889    out
7890}
7891
7892fn join_maps<V: AbstractDomain>(
7893    a: &HashMap<Symbol, V>,
7894    b: &HashMap<Symbol, V>,
7895) -> HashMap<Symbol, V> {
7896    let mut out = HashMap::new();
7897    let keys: HashSet<Symbol> = a.keys().chain(b.keys()).cloned().collect();
7898    for k in keys {
7899        let top = V::top();
7900        let va = a.get(&k).unwrap_or(&top);
7901        let vb = b.get(&k).unwrap_or(&top);
7902        out.insert(k, va.join(vb));
7903    }
7904    out
7905}
7906
7907fn alias_union(a: &AliasGraph, b: &AliasGraph) -> AliasGraph {
7908    let mut out = a.clone();
7909    out.union_from(b);
7910    out
7911}
7912
7913/// Every name `block` may write, as the shared analysis sees it (nested blocks and every binder kind
7914/// included). Use [`collect_mutations_in`] when the program's callee-written globals are at hand.
7915fn collect_mutations(block: &[Stmt]) -> Vec<Symbol> {
7916    collect_mutations_in(block, &CalleeGlobals::default())
7917}
7918
7919/// [`collect_mutations`] with the globals any call in `block` may assign folded in. After foreign
7920/// code every name the block mentions is suspect, so all of them are returned.
7921fn collect_mutations_in(block: &[Stmt], globals: &CalleeGlobals) -> Vec<Symbol> {
7922    let writes = WriteSet::of_block(block).with_callee_globals(globals);
7923    let mut out: Vec<Symbol> = writes.symbols().collect();
7924    if writes.is_opaque() {
7925        for s in block {
7926            collect_idents_stmt(s, &mut |sym, _| {
7927                if !out.contains(&sym) {
7928                    out.push(sym);
7929                }
7930            });
7931        }
7932    }
7933    out
7934}
7935
7936#[cfg(test)]
7937#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/domain_tests.rs"]
7938mod domain_tests;
7939
7940#[cfg(test)]
7941#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/type_domain_tests.rs"]
7942mod type_domain_tests;
7943
7944#[cfg(test)]
7945#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/shape_domain_tests.rs"]
7946mod shape_domain_tests;
7947
7948#[cfg(test)]
7949#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/nullability_domain_tests.rs"]
7950mod nullability_domain_tests;
7951
7952#[cfg(test)]
7953#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/alias_domain_tests.rs"]
7954mod alias_domain_tests;
7955
7956#[cfg(test)]
7957#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/product_lattice_tests.rs"]
7958mod product_lattice_tests;
7959
7960#[cfg(test)]
7961#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/rich_walk_tests.rs"]
7962mod rich_walk_tests;
7963
7964#[cfg(test)]
7965#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/abstract_interp/hoist_order_tests.rs"]
7966mod hoist_order_tests;