Skip to main content

tract_data/dim/
tree.rs

1use crate::dim::Assertion;
2use crate::internal::*;
3
4use super::{DimLike, sym::*};
5use itertools::Itertools;
6use num_integer::Integer;
7use num_traits::{AsPrimitive, PrimInt, Zero};
8use std::cmp::Ordering;
9use std::collections::{HashMap, HashSet};
10use std::fmt::Debug;
11use std::ops::Neg;
12use std::{fmt, ops};
13
14#[derive(Debug)]
15pub enum TooEarly {
16    UndeterminedSymbol(String),
17    Other(String),
18}
19
20impl std::fmt::Display for TooEarly {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        match self {
23            TooEarly::UndeterminedSymbol(s) => write!(f, "Undetermined symbol in expression: {s}"),
24            TooEarly::Other(s) => write!(f, "{s}"),
25        }
26    }
27}
28
29impl std::error::Error for TooEarly {}
30
31macro_rules! b( ($e:expr) => { Box::new($e) } );
32
33// `Hash` stays structural while `PartialEq` accepts an algebraic second chance:
34// see the `PartialEq` impl below for the rationale (the simplifier's internal
35// `HashMap<TDim, _>` only ever compares within same-canonical-form buckets, so
36// the standard `a == b => hash(a) == hash(b)` contract being violated outside
37// that path is acceptable here).
38#[allow(clippy::derived_hash_with_manual_eq)]
39#[derive(Clone, Eq, Hash, Debug)]
40pub enum TDim {
41    Val(i64),
42    Sym(Symbol),
43    Add(Vec<TDim>),
44    Mul(Vec<TDim>),
45    MulInt(i64, Box<TDim>),
46    Div(Box<TDim>, u64),
47    Broadcast(Vec<TDim>),
48    Min(Vec<TDim>),
49    Max(Vec<TDim>),
50    /// Comparison: evaluates to 1 (true) or 0 (false). lhs >= rhs
51    Ge(Box<TDim>, Box<TDim>),
52    /// Comparison: evaluates to 1 (true) or 0 (false). lhs == rhs
53    Eq(Box<TDim>, Box<TDim>),
54}
55
56use TDim::*;
57
58/// Structural equality on the TDim tree — what `#[derive(PartialEq)]` would
59/// produce.  Used as the fast-path inside `PartialEq` (and by the simplifier's
60/// internal `HashMap<TDim, _>`, which compares within same-hash buckets where
61/// structural equality is the only thing that matters).
62fn eq_structural(a: &TDim, b: &TDim) -> bool {
63    match (a, b) {
64        (Val(x), Val(y)) => x == y,
65        (Sym(x), Sym(y)) => x == y,
66        (Add(x), Add(y))
67        | (Mul(x), Mul(y))
68        | (Broadcast(x), Broadcast(y))
69        | (Min(x), Min(y))
70        | (Max(x), Max(y)) => {
71            x.len() == y.len() && x.iter().zip(y).all(|(a, b)| eq_structural(a, b))
72        }
73        (MulInt(p, x), MulInt(q, y)) => p == q && eq_structural(x, y),
74        (Div(x, p), Div(y, q)) => p == q && eq_structural(x, y),
75        (Ge(a, b), Ge(c, d)) | (Eq(a, b), Eq(c, d)) => eq_structural(a, c) && eq_structural(b, d),
76        _ => false,
77    }
78}
79
80// Thread-local guard: while simplifying the difference inside `eq`, fall back
81// to the structural-only path for any nested `==` calls.  Without this guard
82// the simplifier's internal `HashMap<TDim, i64>` would re-enter `eq` from
83// inside `(self - other).simplify()`, recursing without bound on
84// non-structurally-equal inputs.
85std::thread_local! {
86    static EQ_GUARD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
87}
88
89impl PartialEq for TDim {
90    fn eq(&self, other: &Self) -> bool {
91        // Fast path: structural tree equality.
92        if eq_structural(self, other) {
93            return true;
94        }
95        // Inside an enclosing simplification triggered by a previous
96        // second-chance call, fall back to structural equality only.
97        if EQ_GUARD.with(|g| g.get()) {
98            return false;
99        }
100        // Skip second-chance when either side is a leaf (`Val` or `Sym`).
101        // For `Val(c)` vs anything non-`Val`: if they were semantically
102        // equal, the simplifier should already have folded the other side
103        // to `Val(c)`; running a diff-and-simplify here just risks
104        // arithmetic overflow on extreme constants (e.g. the simplifier
105        // filters against `Val(i64::MAX)`/`Val(i64::MIN)` sentinels).
106        // For `Sym(x)` leaves, assertion-driven equality belongs in
107        // `simplify`, not in `eq`.
108        if matches!(self, Val(_) | Sym(_)) || matches!(other, Val(_) | Sym(_)) {
109            return false;
110        }
111        // Second chance: prove the difference simplifies to zero.  Two
112        // algebraically equal TDims often arrive at different canonical
113        // forms via different construction paths (e.g. `1 + (7S+3)/4` and
114        // `((S+1)*7)/4` after blockify substitutes T → k·S in encoder
115        // shapes).  Subtracting and simplifying lets the existing
116        // simplifier rules cancel them out.
117        EQ_GUARD.with(|g| g.set(true));
118        let diff = (self.clone() - other.clone()).simplify();
119        EQ_GUARD.with(|g| g.set(false));
120        matches!(diff, Val(0))
121    }
122}
123
124fn tdim_lexi_order(a: &TDim, b: &TDim) -> Ordering {
125    match (a, b) {
126        (Sym(a), Sym(b)) => a.cmp(b),
127        (Val(a), Val(b)) => a.cmp(b),
128        (Add(a), Add(b))
129        | (Mul(a), Mul(b))
130        | (Broadcast(a), Broadcast(b))
131        | (Min(a), Min(b))
132        | (Max(a), Max(b)) => a.len().cmp(&b.len()).then(
133            a.iter()
134                .zip(b.iter())
135                .fold(Ordering::Equal, |acc, (a, b)| acc.then_with(|| tdim_lexi_order(a, b))),
136        ),
137        (MulInt(p, d), MulInt(q, e)) => p.cmp(q).then_with(|| tdim_lexi_order(d, e)),
138        (Div(d, p), Div(e, q)) => p.cmp(q).then_with(|| tdim_lexi_order(d, e)),
139        (Sym(_), _) => Ordering::Less,
140        (_, Sym(_)) => Ordering::Greater,
141        (Val(_), _) => Ordering::Less,
142        (_, Val(_)) => Ordering::Greater,
143        (Add(_), _) => Ordering::Less,
144        (_, Add(_)) => Ordering::Greater,
145        (Mul(_), _) => Ordering::Less,
146        (_, Mul(_)) => Ordering::Greater,
147        (MulInt(_, _), _) => Ordering::Less,
148        (_, MulInt(_, _)) => Ordering::Greater,
149        (Broadcast(_), _) => Ordering::Less,
150        (_, Broadcast(_)) => Ordering::Greater,
151        (Min(_), _) => Ordering::Less,
152        (_, Min(_)) => Ordering::Greater,
153        (Max(_), _) => Ordering::Less,
154        (_, Max(_)) => Ordering::Greater,
155        (Ge(a1, b1), Ge(a2, b2)) | (Eq(a1, b1), Eq(a2, b2)) => {
156            tdim_lexi_order(a1, a2).then_with(|| tdim_lexi_order(b1, b2))
157        }
158        (Ge(_, _) | Eq(_, _), _) => Ordering::Less,
159        (_, Ge(_, _) | Eq(_, _)) => Ordering::Greater,
160    }
161}
162
163/// `Div(Add(terms), q)` — try to extract every `MulInt(c, X)` where `c % q == 0`
164/// out of the Div, leaving only a constant remainder in `[0, q)`.
165///
166/// Returns `Some(simplified)` when the residual constant is in `[0, q)` and
167/// every extracted symbolic factor `X` is provably non-negative — both
168/// conditions are required for soundness under tract's truncating
169/// division (`Rust i64 /`):
170///
171/// * the constant being in `[0, q)` makes `c/q_trunc = 0`;
172/// * `X ≥ 0` makes the identity `(k·X + c)/k_trunc = X` hold (it fails
173///   at e.g. `X = -1, k = 2, c = 0` because truncation rounds toward zero).
174///
175/// The `Val` arm above already handles constants outside `[0, q)`, so by
176/// the time we get here `terms` contains at most one `Val` and any number
177/// of `MulInt(c, X)` / other shapes.
178fn try_divide_multiple_plus_remainder(
179    terms: &[TDim],
180    q: u64,
181    scope: &SymbolScopeData,
182    extra: &[Assertion],
183) -> Option<TDim> {
184    let mut quotients: Vec<TDim> = vec![];
185    let mut const_rem: i64 = 0;
186    let mut any_extracted = false;
187    for term in terms {
188        match term {
189            MulInt(c, x) if *c != 0 && c.rem_euclid(q as i64) == 0 => {
190                if !scope.prove_positive_or_zero_with_extra(x, extra) {
191                    return None;
192                }
193                let new_coeff = c / (q as i64);
194                quotients.push(if new_coeff == 1 {
195                    (**x).clone()
196                } else if new_coeff == -1 {
197                    MulInt(-1, x.clone())
198                } else {
199                    MulInt(new_coeff, x.clone())
200                });
201                any_extracted = true;
202            }
203            Val(v) => const_rem += v,
204            _ => return None,
205        }
206    }
207    if !any_extracted {
208        return None;
209    }
210    if !(0..q as i64).contains(&const_rem) {
211        return None;
212    }
213    Some(if quotients.len() == 1 { quotients.remove(0) } else { Add(quotients) })
214}
215
216impl fmt::Display for TDim {
217    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
218        match &self {
219            Sym(sym) => write!(fmt, "{sym}"),
220            Val(it) => write!(fmt, "{it}"),
221            Add(it) => write!(fmt, "{}", it.iter().map(|x| format!("{x}")).join("+")),
222            Mul(it) => write!(fmt, "{}", it.iter().map(|x| format!("({x})")).join("*")),
223            Broadcast(it) => {
224                write!(fmt, "broadcast({})", it.iter().map(|x| format!("({x})")).join(", "))
225            }
226            Min(it) => write!(fmt, "min({})", it.iter().map(|x| format!("{x}")).join(",")),
227            Max(it) => write!(fmt, "max({})", it.iter().map(|x| format!("{x}")).join(",")),
228            MulInt(a, b) => write!(fmt, "{a}*{b}"),
229            Div(a, b) => write!(fmt, "({a})/{b}"),
230            Ge(a, b) => write!(fmt, "({a}>={b})"),
231            Eq(a, b) => write!(fmt, "({a}=={b})"),
232        }
233    }
234}
235
236impl TDim {
237    #[inline]
238    pub fn is_one(&self) -> bool {
239        matches!(self, Val(1))
240    }
241
242    #[inline]
243    /// Concrete value of the dim, or a lightweight `TooEarly` for a symbolic
244    /// one. The error is a plain enum — no anyhow conversion, no message
245    /// formatting, and (crucially) no backtrace — so probing concreteness by
246    /// discarding the error (`.ok()`, `if let Ok`) is cheap. Use `?` in a
247    /// `TractResult` context to promote a genuine failure to a full error.
248    pub fn to_i64(&self) -> Result<i64, TooEarly> {
249        if let Val(v) = self { Ok(*v) } else { Err(TooEarly::UndeterminedSymbol(self.to_string())) }
250    }
251
252    #[inline]
253    pub fn as_i64(&self) -> Option<i64> {
254        if let Val(v) = self { Some(*v) } else { None }
255    }
256
257    /// Non-erroring counterpart of `eval_to_i64`: returns `None` instead of
258    /// building an error when a symbol is undetermined or arithmetic overflows.
259    /// Use this on hot paths that only want the constant value and discard the
260    /// reason for failure, so no message string is formatted and (crucially,
261    /// when `RUST_BACKTRACE` is set) no backtrace is captured.
262    pub fn maybe_eval_to_i64(&self, values: &SymbolValues) -> Option<i64> {
263        match self {
264            Sym(sym) => values.get(sym),
265            Val(v) => Some(*v),
266            Add(terms) => terms
267                .iter()
268                .try_fold(0i64, |acc, it| acc.checked_add(it.maybe_eval_to_i64(values)?)),
269            Mul(terms) => terms
270                .iter()
271                .try_fold(1i64, |acc, it| acc.checked_mul(it.maybe_eval_to_i64(values)?)),
272            Min(terms) => terms
273                .iter()
274                .try_fold(i64::MAX, |acc, it| Some(acc.min(it.maybe_eval_to_i64(values)?))),
275            Max(terms) => terms
276                .iter()
277                .try_fold(i64::MIN, |acc, it| Some(acc.max(it.maybe_eval_to_i64(values)?))),
278            Broadcast(terms) => terms.iter().try_fold(1i64, |acc, it| {
279                (acc as usize)
280                    .broadcast(it.maybe_eval_to_i64(values)? as usize)
281                    .ok()
282                    .map(|x| x as i64)
283            }),
284            Div(a, q) => Some(a.maybe_eval_to_i64(values)? / *q as i64),
285            MulInt(p, a) => a.maybe_eval_to_i64(values)?.checked_mul(*p),
286            Ge(a, b) => Some((a.maybe_eval_to_i64(values)? >= b.maybe_eval_to_i64(values)?) as i64),
287            Eq(a, b) => Some((a.maybe_eval_to_i64(values)? == b.maybe_eval_to_i64(values)?) as i64),
288        }
289    }
290
291    pub fn eval_to_i64(&self, values: &SymbolValues) -> TractResult<i64> {
292        match self {
293            Sym(sym) => {
294                let Some(v) = values.get(sym) else {
295                    Err(TooEarly::UndeterminedSymbol(self.to_string()))?
296                };
297                Ok(v)
298            }
299            Val(v) => Ok(*v),
300            Add(terms) => terms.iter().try_fold(0i64, |acc, it| {
301                let x = it.eval_to_i64(values)?;
302                acc.checked_add(x)
303                    .with_context(|| format!("Overflow in TDim addition ({acc} + {x})"))
304            }),
305            Mul(terms) => terms.iter().try_fold(1i64, |acc, it| {
306                let x = it.eval_to_i64(values)?;
307                acc.checked_mul(x)
308                    .with_context(|| format!("Overflow in TDim multiplication ({acc} * {x})"))
309            }),
310            Min(terms) => terms
311                .iter()
312                .try_fold(i64::MAX, |acc, it| it.eval_to_i64(values).map(|x| acc.min(x))),
313            Max(terms) => terms
314                .iter()
315                .try_fold(i64::MIN, |acc, it| it.eval_to_i64(values).map(|x| acc.max(x))),
316            Broadcast(terms) => terms.iter().try_fold(1i64, |acc, it| {
317                it.eval_to_i64(values)
318                    .and_then(|x| ((acc as usize).broadcast(x as usize)).map(|x| x as i64))
319            }),
320            Div(a, q) => Ok(a.eval_to_i64(values)? / *q as i64),
321            MulInt(p, a) => {
322                let x = a.eval_to_i64(values)?;
323                x.checked_mul(*p)
324                    .with_context(|| format!("Overflow in TDim multiplication ({x} * {p})"))
325            }
326            Ge(a, b) => Ok(if a.eval_to_i64(values)? >= b.eval_to_i64(values)? { 1 } else { 0 }),
327            Eq(a, b) => Ok(if a.eval_to_i64(values)? == b.eval_to_i64(values)? { 1 } else { 0 }),
328        }
329    }
330
331    pub fn eval(&self, values: &SymbolValues) -> TDim {
332        match self {
333            Sym(sym) => values.get(sym).map(Val).unwrap_or_else(|| Sym(sym.clone())),
334            Val(v) => Val(*v),
335            Add(terms) => terms.iter().fold(Val(0), |acc, it| -> TDim { acc + it.eval(values) }),
336            Mul(terms) => terms.iter().fold(Val(1), |acc, it| -> TDim { acc * it.eval(values) }),
337            Min(terms) => {
338                terms.iter().fold(Val(i64::MAX), |acc, it| -> TDim { acc.mini(it.eval(values)) })
339            }
340            Max(terms) => {
341                terms.iter().fold(Val(i64::MIN), |acc, it| -> TDim { acc.maxi(it.eval(values)) })
342            }
343            Broadcast(terms) => terms.iter().fold(Val(1), |acc, it| -> TDim {
344                acc.broadcast(it.eval(values)).unwrap_or_else(|_| self.clone())
345            }),
346            Div(a, q) => a.eval(values) / *q as i64,
347            MulInt(p, a) => a.eval(values) * *p,
348            Ge(a, b) => {
349                let a2 = a.eval(values);
350                let b2 = b.eval(values);
351                if let (Val(av), Val(bv)) = (&a2, &b2) {
352                    Val(if av >= bv { 1 } else { 0 })
353                } else {
354                    Ge(b!(a2), b!(b2))
355                }
356            }
357            Eq(a, b) => {
358                let a2 = a.eval(values);
359                let b2 = b.eval(values);
360                if let (Val(av), Val(bv)) = (&a2, &b2) {
361                    Val(if av == bv { 1 } else { 0 })
362                } else {
363                    Eq(b!(a2), b!(b2))
364                }
365            }
366        }
367    }
368
369    pub fn eval_with_scenario(&self, scenario: &str) -> TDim {
370        if let Val(v) = self {
371            return Val(*v);
372        }
373        let scope = self.find_scope().unwrap();
374        let scope = scope.0;
375        let locked = scope.lock();
376        let scope = locked.borrow();
377        self.clone().simplify_rec(&scope, Some(scenario), &[])
378    }
379
380    pub fn substitute(&self, from: &Symbol, to: &Self) -> TractResult<Self> {
381        self.substitute_all(&std::collections::HashMap::from([(from.clone(), to.clone())]))
382    }
383
384    pub fn substitute_all(
385        &self,
386        map: &std::collections::HashMap<Symbol, Self>,
387    ) -> TractResult<Self> {
388        match self {
389            Sym(sym) => Ok(map.get(sym).cloned().unwrap_or_else(|| self.clone())),
390            Val(v) => Ok(Val(*v)),
391            Add(terms) => terms.iter().try_fold(Val(0), |acc, it| -> TractResult<TDim> {
392                Ok(acc + it.substitute_all(map)?)
393            }),
394            Mul(terms) => terms.iter().try_fold(Val(1), |acc, it| -> TractResult<TDim> {
395                Ok(acc * it.substitute_all(map)?)
396            }),
397            Broadcast(terms) => terms.iter().try_fold(Val(1), |acc, it| -> TractResult<TDim> {
398                acc.broadcast(it.substitute_all(map)?)
399            }),
400            Min(terms) => terms.iter().try_fold(Val(i64::MAX), |acc, it| -> TractResult<TDim> {
401                Ok(acc.mini(it.substitute_all(map)?))
402            }),
403            Max(terms) => terms.iter().try_fold(Val(i64::MIN), |acc, it| -> TractResult<TDim> {
404                Ok(acc.maxi(it.substitute_all(map)?))
405            }),
406            Div(a, q) => Ok(a.substitute_all(map)? / *q as i64),
407            MulInt(p, a) => Ok(a.substitute_all(map)? * *p),
408            Ge(a, b) => Ok(Ge(b!(a.substitute_all(map)?), b!(b.substitute_all(map)?))),
409            Eq(a, b) => Ok(Eq(b!(a.substitute_all(map)?), b!(b.substitute_all(map)?))),
410        }
411    }
412
413    pub fn reduce(self) -> TDim {
414        self.simplify()
415            .wiggle()
416            .into_iter()
417            .sorted_by(tdim_lexi_order)
418            .unique()
419            .map(|e| e.simplify())
420            .min_by_key(|e| e.cost())
421            .unwrap()
422    }
423
424    fn cost(&self) -> usize {
425        use self::TDim::*;
426        match self {
427            Sym(_) | Val(_) => 1,
428            Add(terms) => 2 * terms.iter().map(TDim::cost).sum::<usize>(),
429            Mul(terms) => 3 * terms.iter().map(TDim::cost).sum::<usize>(),
430            Broadcast(terms) => 4 * terms.iter().map(TDim::cost).sum::<usize>(),
431            Min(terms) | Max(terms) => 5 * terms.iter().map(TDim::cost).sum::<usize>(),
432            Div(a, _) => 3 * a.cost(),
433            MulInt(_, a) => 2 * a.cost(),
434            Ge(a, b) | Eq(a, b) => 5 * (a.cost() + b.cost()),
435        }
436    }
437
438    fn wiggle(&self) -> Vec<TDim> {
439        use self::TDim::*;
440        match self {
441            Sym(_) | Val(_) | Mul(_) | Broadcast(_) | Min(_) | Max(_) | Ge(_, _) | Eq(_, _) => {
442                vec![self.clone()]
443            }
444            Add(terms) => {
445                let mut forms = vec![];
446                let sub_exprs = terms.iter().map(|e| e.wiggle()).multi_cartesian_product();
447
448                fn first_div_term(terms: &[TDim]) -> Option<(usize, &TDim, u64)> {
449                    terms.iter().enumerate().find_map(|(index, t)| match t {
450                        Div(numerator, quotient) => Some((index, &**numerator, *quotient)),
451                        _ => None,
452                    })
453                }
454
455                fn generate_new_numerator(
456                    div_index: usize,
457                    numerator: &TDim,
458                    quotient: u64,
459                    expr: &[TDim],
460                ) -> Vec<TDim> {
461                    expr.iter()
462                        .enumerate()
463                        .map(|(index, term)| {
464                            if index == div_index {
465                                numerator.clone()
466                            } else {
467                                MulInt(quotient as i64, Box::new(term.clone()))
468                            }
469                        })
470                        .collect()
471                }
472
473                for expr in sub_exprs {
474                    if let Some((div_index, numerator, quotient)) = first_div_term(&expr) {
475                        let new_numerator =
476                            generate_new_numerator(div_index, numerator, quotient, &expr);
477                        forms.push(Div(Box::new(Add(new_numerator)), quotient))
478                    }
479
480                    forms.push(Add(expr));
481                }
482                forms
483            }
484            MulInt(p, a) => a.wiggle().into_iter().map(|a| MulInt(*p, b!(a))).collect(),
485            Div(a, q) => {
486                let mut forms = vec![];
487                for num in a.wiggle() {
488                    if let Add(terms) = &num {
489                        let (integer, non_integer): (Vec<_>, Vec<_>) =
490                            terms.iter().cloned().partition(|a| a.gcd() % q == 0);
491                        // Skip when the non-integer bucket holds a constant:
492                        // under tract's truncating `/`, splitting (k·X+c)/k →
493                        // X + c/k is unsound for negative X (X=-1, k=2, c=1:
494                        // (-1)/2 = 0 ≠ X). The sound version, gated on
495                        // prove_positive_or_zero, lives in simplify_rec::Div
496                        // via try_divide_multiple_plus_remainder. Cases where
497                        // the remainder is purely symbolic (e.g. A%2 → /2
498                        // lowers to (A − 2·(A/2))/2, non_integer=[A]) stay
499                        // here: the emitted Div(non_integer, q) cancels with
500                        // the extracted quotient and reduces to zero.
501                        if !non_integer.iter().any(|t| matches!(t, Val(_))) {
502                            let mut new_terms =
503                                integer.iter().map(|i| i.div(*q)).collect::<Vec<_>>();
504                            if non_integer.len() > 0 {
505                                new_terms.push(Div(b!(Add(non_integer)), *q));
506                            }
507                            forms.push(Add(new_terms))
508                        }
509                    }
510                    forms.push(Div(b!(num), *q))
511                }
512                forms
513            }
514        }
515    }
516
517    fn find_any_sym(tdim: &TDim) -> Option<&Symbol> {
518        match tdim {
519            Val(_) => None,
520            Sym(s) => Some(s),
521            Add(terms) | Mul(terms) | Min(terms) | Max(terms) | Broadcast(terms) => {
522                terms.iter().find_map(Self::find_any_sym)
523            }
524            MulInt(_, t) | Div(t, _) => Self::find_any_sym(t),
525            Ge(a, b) | Eq(a, b) => Self::find_any_sym(a).or_else(|| Self::find_any_sym(b)),
526        }
527    }
528
529    pub fn find_scope(&self) -> Option<SymbolScope> {
530        Self::find_any_sym(self).and_then(|s| s.scope().clone())
531    }
532
533    /// Fully distribute every `Mul` of `Add`s in `self` into a flat sum of
534    /// products, then `simplify`.  Used to compare two algebraically equal
535    /// but differently-factored TDims for equality (e.g. Reshape volume
536    /// checks on graphs where the same dimension is built two ways).
537    ///
538    /// Cost can blow up combinatorially on very deeply factored expressions
539    /// — call this only at boundaries where structural equality is needed,
540    /// not as a general-purpose simplifier.
541    pub fn expand_polynomial(self) -> TDim {
542        use self::TDim::*;
543        match self {
544            Mul(terms) => {
545                let terms: Vec<TDim> = terms.into_iter().map(Self::expand_polynomial).collect();
546                if let Some(add_idx) = terms.iter().position(|t| matches!(t, Add(_))) {
547                    let Add(add_terms) = terms[add_idx].clone() else { unreachable!() };
548                    let others: Vec<TDim> = terms
549                        .iter()
550                        .enumerate()
551                        .filter(|(i, _)| *i != add_idx)
552                        .map(|(_, t)| t.clone())
553                        .collect();
554                    Add(add_terms
555                        .into_iter()
556                        .map(|t| {
557                            let mut product = others.clone();
558                            product.push(t);
559                            Mul(product).expand_polynomial()
560                        })
561                        .collect())
562                    .simplify()
563                } else {
564                    Mul(terms).simplify()
565                }
566            }
567            MulInt(c, inner) => MulInt(c, Box::new(inner.expand_polynomial())).simplify(),
568            Add(terms) => Add(terms.into_iter().map(Self::expand_polynomial).collect()).simplify(),
569            Div(a, q) => Div(Box::new(a.expand_polynomial()), q).simplify(),
570            Min(terms) => Min(terms.into_iter().map(Self::expand_polynomial).collect()).simplify(),
571            Max(terms) => Max(terms.into_iter().map(Self::expand_polynomial).collect()).simplify(),
572            Broadcast(terms) => {
573                Broadcast(terms.into_iter().map(Self::expand_polynomial).collect()).simplify()
574            }
575            Ge(a, b) => {
576                Ge(Box::new(a.expand_polynomial()), Box::new(b.expand_polynomial())).simplify()
577            }
578            Eq(a, b) => {
579                Eq(Box::new(a.expand_polynomial()), Box::new(b.expand_polynomial())).simplify()
580            }
581            it @ (Sym(_) | Val(_)) => it,
582        }
583    }
584
585    pub fn simplify(self) -> TDim {
586        use self::TDim::*;
587        if let Some(v) = self.maybe_eval_to_i64(&SymbolValues::default()) {
588            return Val(v);
589        }
590        let Some(scope) = self.find_scope() else {
591            return self;
592        };
593        let scope = scope.0;
594        let locked = scope.lock();
595        let scope = locked.borrow();
596        let it = self.simplify_rec(&scope, None, &[]);
597        let mut current: Option<TDim> = None;
598        for scenario in scope.scenarios() {
599            let v = it.clone().simplify_rec(&scope, Some(scenario), &[]);
600            if current.is_some_and(|c| c != v) {
601                return it;
602            } else {
603                current = Some(v);
604            }
605        }
606        current.unwrap_or(it)
607    }
608
609    pub fn simplify_with_extra_assertions(self, extra: &[Assertion]) -> TDim {
610        use self::TDim::*;
611        if extra.is_empty() {
612            return self.simplify();
613        }
614        if let Some(v) = self.maybe_eval_to_i64(&SymbolValues::default()) {
615            return Val(v);
616        }
617        let Some(scope) = self.find_scope() else {
618            return self;
619        };
620        let scope = scope.0;
621        let locked = scope.lock();
622        let scope = locked.borrow();
623        let it = self.simplify_rec(&scope, None, extra);
624        let mut current: Option<TDim> = None;
625        for scenario in scope.scenarios() {
626            let v = it.clone().simplify_rec(&scope, Some(scenario), extra);
627            if current.is_some_and(|c| c != v) {
628                return it;
629            } else {
630                current = Some(v);
631            }
632        }
633        current.unwrap_or(it)
634    }
635
636    fn simplify_rec(
637        self,
638        scope: &SymbolScopeData,
639        scenario: Option<&str>,
640        extra: &[Assertion],
641    ) -> TDim {
642        match self {
643            Add(mut terms) => {
644                #[allow(clippy::mutable_key_type)]
645                let mut simplified_terms: HashMap<TDim, i64> = HashMap::new();
646                // factorize common sub-expr
647                while let Some(term) = terms.pop() {
648                    let simplified = term.simplify_rec(scope, scenario, extra);
649                    match simplified {
650                        Val(0) => {} // ignore
651                        Add(members) => {
652                            terms.extend(members);
653                            continue;
654                        }
655                        Val(value) => *simplified_terms.entry(Val(1)).or_insert(0) += value,
656                        MulInt(value, factor) => {
657                            *simplified_terms.entry((*factor).clone()).or_insert(0) += value;
658                        }
659                        n => *simplified_terms.entry(n).or_insert(0) += 1,
660                    };
661                }
662
663                pub fn evaluate_count(term: TDim, count: i64) -> Option<TDim> {
664                    match count {
665                        0 => None,
666                        _ if term == TDim::Val(1) => Some(TDim::Val(count)),
667                        1 => Some(term),
668                        _ => Some(TDim::MulInt(count, Box::new(term))),
669                    }
670                }
671
672                // Pull the integer GCD of all term coefficients out as a
673                // common factor: e.g. Add([Val(6), MulInt(14, S)]) becomes
674                // MulInt(2, Add([Val(3), MulInt(7, S)])).  The downstream
675                // Div(MulInt(p, a), q) arm then cancels (p, q) gcd, so
676                // (6 + 14·S) / 8 reduces to (3 + 7·S) / 4 with no special
677                // Div-over-Add rule needed.
678                //
679                // Only consider entries with non-zero counts — zero-count
680                // entries (canceled-out factors) get filtered later, but
681                // would otherwise drag the gcd to spurious values.  Only
682                // factor when at least one surviving entry has a
683                // non-constant key, otherwise the Add reduces to a single
684                // `Val` and wrapping it in `MulInt(g, Val(c/g))` is a
685                // strict regression in canonical form.
686                let has_non_const =
687                    simplified_terms.iter().any(|(k, &c)| c != 0 && !matches!(k, Val(_)));
688                let coef_gcd = if has_non_const {
689                    simplified_terms
690                        .values()
691                        .filter(|&&c| c != 0)
692                        .map(|c| c.unsigned_abs() as i64)
693                        .reduce(|a, b| a.gcd(&b))
694                        .unwrap_or(0)
695                } else {
696                    0
697                };
698                let outer_factor = if coef_gcd > 1 {
699                    for v in simplified_terms.values_mut() {
700                        *v /= coef_gcd;
701                    }
702                    Some(coef_gcd)
703                } else {
704                    None
705                };
706
707                let mut members: Vec<TDim> = simplified_terms
708                    .into_iter()
709                    .filter_map(|(term, count)| evaluate_count(term, count))
710                    .collect();
711                members.sort_by(tdim_lexi_order);
712
713                let inner = match members.len() {
714                    0 => TDim::Val(0),
715                    1 => members.into_iter().next().unwrap(),
716                    _ => TDim::Add(members),
717                };
718                match outer_factor {
719                    None => inner,
720                    Some(_) if matches!(inner, TDim::Val(0)) => TDim::Val(0),
721                    Some(g) => TDim::MulInt(g, Box::new(inner)),
722                }
723            }
724            Mul(terms) => {
725                // Distribute over Add: if exactly one factor is an Add,
726                // expand Mul([a, Add([b, c])]) => Add([Mul([a, b]), Mul([a, c])]).
727                // This lets (T+1)*P simplify to T*P + P, which is needed for
728                // cancellation in expressions like (T+1)*P - T*P.
729                //
730                // Multi-Add Muls are *not* eagerly expanded here — keeping them
731                // factored matters for `maybe_div`'s bag-of-factors path, which
732                // cancels common Add factors symbolically (e.g. dividing
733                // 16B·(1+Y)² by 8B·(1+Y) needs the (1+Y)s to be visible as
734                // factors, not melted into a polynomial sum).  Use
735                // `expand_polynomial` if you need a fully distributed canonical
736                // form for equality comparisons (see Reshape volume check).
737                {
738                    let add_indices: Vec<usize> = terms
739                        .iter()
740                        .enumerate()
741                        .filter(|(_, t)| matches!(t, Add(_)))
742                        .map(|(i, _)| i)
743                        .collect();
744                    if add_indices.len() == 1 {
745                        let add_idx = add_indices[0];
746                        let Add(add_terms) = &terms[add_idx] else { unreachable!() };
747                        let other_factors: Vec<TDim> = terms
748                            .iter()
749                            .enumerate()
750                            .filter(|(i, _)| *i != add_idx)
751                            .map(|(_, t)| t.clone())
752                            .collect();
753                        let distributed: Vec<TDim> = add_terms
754                            .iter()
755                            .map(|at| {
756                                let mut product = other_factors.clone();
757                                product.push(at.clone());
758                                Mul(product)
759                            })
760                            .collect();
761                        return Add(distributed).simplify_rec(scope, scenario, extra);
762                    }
763                }
764
765                // in case a term is a multiplication itself, flatten it
766                // e.g., (a*b)*c => a*b*c, and MulInt(k, x) => Val(k)*x
767                let mut flattened_terms = vec![];
768                for t in terms {
769                    match t.clone().reduce() {
770                        Mul(inner_terms) => flattened_terms.extend(inner_terms),
771                        MulInt(k, inner) => {
772                            flattened_terms.push(Val(k));
773                            flattened_terms.push(*inner);
774                        }
775                        other => flattened_terms.push(other),
776                    }
777                }
778                let mut terms = flattened_terms;
779
780                let mut gcd = Mul(terms.clone()).gcd() as i64;
781                if gcd == 0 {
782                    return Val(0);
783                }
784                terms = if gcd != 1 {
785                    terms
786                        .into_iter()
787                        .map(|t| {
788                            let gcd = t.gcd();
789                            (t / gcd).simplify_rec(scope, scenario, extra)
790                        })
791                        .collect()
792                } else {
793                    terms
794                };
795                if terms.iter().filter(|t| t == &&Val(-1)).count() % 2 == 1 {
796                    gcd = -gcd;
797                }
798                terms.retain(|t| !t.is_one() && t != &Val(-1));
799                terms.sort_by(tdim_lexi_order);
800
801                match (gcd, terms.len()) {
802                    (_, 0) => Val(gcd), // Case #1: If 0 variables, return product
803                    (0, _) => Val(0),   // Case #2: Result is 0 if coef is 0 (actually
804                    // unreachable as we check at the beginning)
805                    (1, 1) => terms.remove(0), // Case #3: Product is 1, so return the only term
806                    (1, _) => Mul(terms), // Case #4: Product is 1, so return the non-integer terms
807                    (_, 1) => MulInt(gcd, Box::new(terms.remove(0))), // Case #5: Single variable, convert to 1 MulInt
808                    _ => MulInt(gcd, Box::new(Mul(terms))), // Case #6: Multiple variables, convert to MulInt
809                }
810            }
811            MulInt(coef, expr) => {
812                match *expr {
813                    MulInt(c2, inner) => {
814                        if let Some(c) = coef.checked_mul(c2) {
815                            return MulInt(c, inner).simplify_rec(scope, scenario, extra);
816                        } else {
817                            return MulInt(coef, Box::new(MulInt(c2, inner)));
818                        }
819                    }
820                    Val(v) => {
821                        return coef
822                            .checked_mul(v)
823                            .map(Val)
824                            .unwrap_or_else(|| MulInt(coef, Box::new(Val(v))));
825                    }
826                    _ => {}
827                }
828
829                let simplified = expr.simplify_rec(scope, scenario, extra);
830                match (coef, simplified) {
831                    (0, _) => Val(0), // Case #1: If coef is 0, return 0
832                    (1, s) => s,      // Case #2: If coef is 1, return the simplified expression
833                    (_, Add(terms)) => Add(terms
834                        .into_iter()
835                        .map(|term| {
836                            MulInt(coef, Box::new(term)).simplify_rec(scope, scenario, extra)
837                        })
838                        .collect()), // Case #3: If expression is an addition, distribute the coef
839                    (c, Val(v)) => {
840                        c.checked_mul(v).map(Val).unwrap_or_else(|| MulInt(c, Box::new(Val(v))))
841                    } // Case #4: If expression is a value, combine coefs
842                    (c, MulInt(v, inner)) => {
843                        if let Some(cv) = c.checked_mul(v) {
844                            MulInt(cv, inner) // Case #5: If expression is a MulInt, combine coefs
845                        } else {
846                            MulInt(c, Box::new(MulInt(v, inner)))
847                        }
848                    }
849                    (_, s) => MulInt(coef, Box::new(s)), // Case #6: Otherwise, return the original
850                }
851            }
852            Div(a, q) => {
853                if q == 1 {
854                    return a.simplify_rec(scope, scenario, extra);
855                } else if let Div(a, q2) = *a {
856                    return Div(a, q * q2).simplify_rec(scope, scenario, extra);
857                }
858                let a = a.simplify_rec(scope, scenario, extra);
859                if let Val(a) = a {
860                    Val(a / q as i64)
861                } else if let MulInt(-1, a) = a {
862                    MulInt(-1, b!(Div(a, q)))
863                } else if let Add(mut terms) = a {
864                    if terms
865                        .iter()
866                        .any(|t| if let MulInt(-1, s) = t { matches!(&**s, Sym(_)) } else { false })
867                    {
868                        MulInt(
869                            -1,
870                            b!(Div(
871                                b!(Add(terms.into_iter().map(|t| MulInt(-1, b!(t))).collect())
872                                    .simplify_rec(scope, scenario, extra)),
873                                q
874                            )),
875                        )
876                    } else if let Some(val) = terms
877                        .iter()
878                        .find_map(|t| if let Val(v) = t { Some(*v) } else { None })
879                        .and_then(|v| {
880                            if v >= q as i64 {
881                                Some(v / q as i64)
882                            } else if v < 0 {
883                                Some(-Integer::div_ceil(&-v, &(q as i64)))
884                            } else {
885                                None
886                            }
887                        })
888                    {
889                        terms.push(Val(-val * q as i64));
890                        // simplify_rec the inner Div too so that follow-up rules
891                        // (e.g. divide-multiple-plus-remainder below) can collapse
892                        // it once the Val extraction has tidied up the residual.
893                        let inner = Div(b!(Add(terms).simplify_rec(scope, scenario, extra)), q)
894                            .simplify_rec(scope, scenario, extra);
895                        Add(vec![Val(val), inner])
896                    } else if let Some(simplified) =
897                        try_divide_multiple_plus_remainder(&terms, q, scope, extra)
898                    {
899                        // Match `Div(Add([k·X, …, c]), k)` where:
900                        //   - one or more terms have a coefficient that is a multiple of q,
901                        //   - the rest sum to a constant in [0, q),
902                        //   - every extracted X is provably non-negative.
903                        // Then `(k·X + c)/k = X + 0 = X` under tract's truncating
904                        // division.  This is sound for X ≥ 0 only — at X = -1
905                        // the truncation rounds toward zero, not floor, breaking
906                        // the identity.  We use prove_positive_or_zero to gate.
907                        simplified.simplify_rec(scope, scenario, extra)
908                    } else if let Some(found_idx) = terms.iter().position(|term| {
909                        // Rule: (Y − q·(Y/q)) / q = 0  [i.e. (Y mod q) / q = 0]
910                        // Always sound: |Y mod q| < q so (Y mod q)/q = 0 under
911                        // truncating division regardless of sign of Y.
912                        matches!(term, MulInt(p, inner)
913                            if *p == -(q as i64)
914                            && matches!(inner.as_ref(), Div(_, q2) if *q2 == q))
915                    }) {
916                        let MulInt(_, inner) = &terms[found_idx] else { unreachable!() };
917                        let Div(y, _) = inner.as_ref() else { unreachable!() };
918                        let remaining: Vec<TDim> = terms
919                            .iter()
920                            .enumerate()
921                            .filter(|&(i, _)| i != found_idx)
922                            .map(|(_, t)| t.clone())
923                            .collect();
924                        let remaining_sum = match remaining.len() {
925                            0 => Val(0),
926                            1 => remaining.into_iter().next().unwrap(),
927                            _ => Add(remaining),
928                        };
929                        if eq_structural(&remaining_sum, y) {
930                            Val(0)
931                        } else {
932                            Div(b!(Add(terms)), q)
933                        }
934                    } else {
935                        Div(b!(Add(terms)), q)
936                    }
937                } else if let MulInt(p, a) = a {
938                    if p == q as i64 {
939                        a.simplify()
940                    } else {
941                        let gcd = p.abs().gcd(&(q as i64));
942                        if gcd == p {
943                            Div(a, q / gcd as u64)
944                        } else if gcd == q as i64 {
945                            MulInt(p / gcd, a)
946                        } else if gcd > 1 {
947                            Div(b!(MulInt(p / gcd, a)), q / gcd as u64)
948                                .simplify_rec(scope, scenario, extra)
949                        } else {
950                            Div(b!(MulInt(p, a)), q)
951                        }
952                    }
953                } else {
954                    Div(b!(a), q)
955                }
956            }
957            Broadcast(terms) => {
958                let mut terms: Vec<TDim> = terms
959                    .iter()
960                    .map(|s| s.clone().simplify_rec(scope, scenario, extra))
961                    .flat_map(|t| if let Broadcast(t) = t { t } else { vec![t] })
962                    .filter(|t| !t.is_one())
963                    .sorted_by(tdim_lexi_order)
964                    .dedup()
965                    .collect_vec();
966                // a#min(a,b) if a>0 && b>0 => a
967                match &*terms {
968                    [] => Val(1),
969                    [_] => terms.remove(0),
970                    [a, Min(m)] | [Min(m), a]
971                        if m.contains(a)
972                            && m.iter()
973                                .all(|t| scope.prove_strict_positive_with_extra(t, extra)) =>
974                    {
975                        a.clone()
976                    }
977                    _ => Broadcast(terms),
978                }
979            }
980
981            Min(terms) => {
982                let mut flatten: Vec<TDim> = terms
983                    .into_iter()
984                    .map(|t| t.simplify_rec(scope, scenario, extra))
985                    .flat_map(|t| if let Min(t) = t { t } else { vec![t] })
986                    .filter(|t| t != &Val(i64::MAX))
987                    .sorted_by(tdim_lexi_order)
988                    .dedup()
989                    .collect();
990                #[allow(clippy::mutable_key_type)]
991                let mut redundant = HashSet::<TDim>::default();
992                for pair in flatten.iter().permutations(2) {
993                    let (a, b) = (pair[0], pair[1]);
994                    if redundant.contains(a) || redundant.contains(b) {
995                        continue;
996                    }
997                    let diff = a.clone() - b;
998                    if diff.as_i64().is_some_and(|i| i >= 0)
999                        || scope.prove_positive_or_zero_with_extra(&diff, extra)
1000                    {
1001                        redundant.insert(a.clone());
1002                    }
1003                }
1004                flatten.retain(|t| !redundant.contains(t));
1005                if flatten.len() == 0 {
1006                    i64::MAX.to_dim()
1007                } else if flatten.len() == 1 {
1008                    flatten.into_iter().next().unwrap()
1009                } else {
1010                    Min(flatten)
1011                }
1012            }
1013            Max(terms) => {
1014                let mut flatten: Vec<TDim> = terms
1015                    .into_iter()
1016                    .map(|t| t.simplify_rec(scope, scenario, extra))
1017                    .flat_map(|t| if let Max(t) = t { t } else { vec![t] })
1018                    .filter(|t| t != &Val(i64::MIN))
1019                    .sorted_by(tdim_lexi_order)
1020                    .dedup()
1021                    .collect();
1022                #[allow(clippy::mutable_key_type)]
1023                let mut redundant = HashSet::<TDim>::default();
1024                for pair in flatten.iter().permutations(2) {
1025                    let (a, b) = (pair[0], pair[1]);
1026                    if redundant.contains(a) || redundant.contains(b) {
1027                        continue;
1028                    }
1029                    let diff = a.clone() - b;
1030                    if diff.as_i64().is_some_and(|i| i >= 0)
1031                        || scope.prove_positive_or_zero_with_extra(&diff, extra)
1032                    {
1033                        redundant.insert(b.clone());
1034                    }
1035                }
1036                flatten.retain(|t| !redundant.contains(t));
1037                if flatten.len() == 0 {
1038                    i64::MIN.to_dim()
1039                } else if flatten.len() == 1 {
1040                    flatten.into_iter().next().unwrap()
1041                } else {
1042                    Max(flatten)
1043                }
1044            }
1045            Sym(s) => scope
1046                .assertions(scenario)
1047                .find_map(|a| match a {
1048                    Assertion::Eq(Sym(sym), v) if sym == &s => Some(v.clone()),
1049                    _ => None,
1050                })
1051                .unwrap_or(Sym(s)),
1052            Val(_) => self,
1053            Ge(a, b) => {
1054                let a = a.simplify_rec(scope, scenario, extra);
1055                let b = b.simplify_rec(scope, scenario, extra);
1056                match (&a, &b) {
1057                    (Val(av), Val(bv)) => Val(if av >= bv { 1 } else { 0 }),
1058                    _ => {
1059                        let diff = a.clone() - b.clone();
1060                        if scope.prove_positive_or_zero_with_extra(&diff, extra) {
1061                            Val(1)
1062                        } else if scope
1063                            .prove_strict_positive_with_extra(&(b.clone() - a.clone()), extra)
1064                        {
1065                            Val(0)
1066                        } else {
1067                            Ge(b!(a), b!(b))
1068                        }
1069                    }
1070                }
1071            }
1072            Eq(a, b) => {
1073                let a = a.simplify_rec(scope, scenario, extra);
1074                let b = b.simplify_rec(scope, scenario, extra);
1075                match (&a, &b) {
1076                    (Val(av), Val(bv)) => Val(if av == bv { 1 } else { 0 }),
1077                    _ => {
1078                        let diff = a.clone() - b.clone();
1079                        if scope.prove_strict_positive_with_extra(&diff, extra)
1080                            || scope
1081                                .prove_strict_positive_with_extra(&(b.clone() - a.clone()), extra)
1082                        {
1083                            Val(0)
1084                        } else {
1085                            // When one side is 0 or 1 and the other is
1086                            // provably in [0,1], reduce to boolean algebra:
1087                            //   Eq(expr, 0) → 1 - expr
1088                            //   Eq(expr, 1) → expr
1089                            let boolean_case = match (&a, &b) {
1090                                (Val(0), e) | (e, Val(0)) => Some((e, false)),
1091                                (Val(1), e) | (e, Val(1)) => Some((e, true)),
1092                                _ => None,
1093                            };
1094                            if let Some((expr, equals_one)) = boolean_case
1095                                && scope.prove_positive_or_zero_with_extra(expr, extra)
1096                                && scope.prove_positive_or_zero_with_extra(
1097                                    &(Val(1) - expr.clone()),
1098                                    extra,
1099                                )
1100                            {
1101                                return if equals_one {
1102                                    expr.clone()
1103                                } else {
1104                                    (Val(1) - expr.clone()).simplify_rec(scope, scenario, extra)
1105                                };
1106                            }
1107                            Eq(b!(a), b!(b))
1108                        }
1109                    }
1110                }
1111            }
1112        }
1113    }
1114
1115    pub(super) fn inclusive_bound(&self, scope: &SymbolScopeData, upper: bool) -> Option<i64> {
1116        use self::TDim::*;
1117        match self {
1118            Val(n) => Some(*n),
1119            Sym(_) => {
1120                if upper {
1121                    scope
1122                        .all_assertions()
1123                        .iter()
1124                        .filter_map(|assert| match &assert {
1125                            Assertion::LT(left, right)
1126                                if left == self && right.as_i64().is_some() =>
1127                            {
1128                                Some(right.as_i64().unwrap() - 1)
1129                            }
1130                            Assertion::LTE(left, right)
1131                                if left == self && right.as_i64().is_some() =>
1132                            {
1133                                Some(right.as_i64().unwrap())
1134                            }
1135                            _ => None,
1136                        })
1137                        .min()
1138                } else {
1139                    scope
1140                        .all_assertions()
1141                        .iter()
1142                        .filter_map(|assert| match &assert {
1143                            Assertion::GT(left, right)
1144                                if left == self && right.as_i64().is_some() =>
1145                            {
1146                                Some(right.as_i64().unwrap() + 1)
1147                            }
1148                            Assertion::GTE(left, right)
1149                                if left == self && right.as_i64().is_some() =>
1150                            {
1151                                Some(right.as_i64().unwrap())
1152                            }
1153                            _ => None,
1154                        })
1155                        .max()
1156                }
1157            }
1158            Add(terms) => {
1159                let mut bound: i64 = 0;
1160                for t in terms {
1161                    {
1162                        let b = t.inclusive_bound(scope, upper)?;
1163                        bound = bound.checked_add(b)?;
1164                    }
1165                }
1166                Some(bound)
1167            }
1168            MulInt(p, a) => match p.cmp(&0) {
1169                Ordering::Equal => Some(0),
1170                Ordering::Greater => {
1171                    a.inclusive_bound(scope, upper).and_then(|x| x.checked_mul(*p))
1172                }
1173                Ordering::Less => a.inclusive_bound(scope, !upper).and_then(|x| x.checked_mul(*p)),
1174            },
1175            Mul(terms) => {
1176                // If all factors have known non-negative bounds, we can bound the product.
1177                let mut lo: i64 = 1;
1178                let mut hi: i64 = 1;
1179                for t in terms {
1180                    let t_lo = t.inclusive_bound(scope, false)?;
1181                    let t_hi = t.inclusive_bound(scope, true)?;
1182                    if t_lo < 0 {
1183                        return None;
1184                    }
1185                    lo = lo.checked_mul(t_lo)?;
1186                    hi = hi.checked_mul(t_hi)?;
1187                }
1188                Some(if upper { hi } else { lo })
1189            }
1190            Min(terms) if !upper => {
1191                // All terms must have known lower bounds; if any is unknown,
1192                // the Min lower bound is unknown.
1193                let bounds: Option<Vec<i64>> =
1194                    terms.iter().map(|t| t.inclusive_bound(scope, false)).collect();
1195                bounds.map(|b| b.into_iter().min().unwrap_or(i64::MAX))
1196            }
1197            Max(terms) if upper => {
1198                // All terms must have known upper bounds; if any is unknown,
1199                // the Max upper bound is unknown.
1200                let bounds: Option<Vec<i64>> =
1201                    terms.iter().map(|t| t.inclusive_bound(scope, true)).collect();
1202                bounds.map(|b| b.into_iter().max().unwrap_or(i64::MIN))
1203            }
1204            Min(terms) => terms.iter().filter_map(|t| t.inclusive_bound(scope, true)).min(),
1205            Max(terms) => terms.iter().filter_map(|t| t.inclusive_bound(scope, false)).max(),
1206            Div(a, q) => a.inclusive_bound(scope, upper).map(|x| x / (*q as i64)),
1207            Broadcast(terms) => {
1208                if upper {
1209                    Max(terms.clone()).inclusive_bound(scope, true)
1210                } else {
1211                    Min(terms.clone()).inclusive_bound(scope, false)
1212                }
1213            }
1214            Ge(_, _) | Eq(_, _) => {
1215                if upper {
1216                    Some(1)
1217                } else {
1218                    Some(0)
1219                }
1220            }
1221        }
1222    }
1223
1224    pub fn low_inclusive_bound(&self) -> Option<i64> {
1225        if let TDim::Val(v) = self {
1226            return Some(*v);
1227        }
1228        let scope = self.find_scope()?;
1229        let data = scope.0.lock();
1230        let data = data.borrow();
1231        self.inclusive_bound(&data, false)
1232    }
1233
1234    pub fn high_inclusive_bound(&self) -> Option<i64> {
1235        if let TDim::Val(v) = self {
1236            return Some(*v);
1237        }
1238        let scope = self.find_scope()?;
1239        let data = scope.0.lock();
1240        let data = data.borrow();
1241        self.inclusive_bound(&data, true)
1242    }
1243
1244    pub fn prove_positive_or_zero(&self) -> bool {
1245        if let TDim::Val(v) = self {
1246            return *v >= 0;
1247        }
1248        let Some(scope) = self.find_scope() else { return false };
1249        let data = scope.0.lock();
1250        let data = data.borrow();
1251        data.prove_positive_or_zero(self)
1252    }
1253
1254    pub fn prove_strict_positive(&self) -> bool {
1255        if let TDim::Val(v) = self {
1256            return *v > 0;
1257        }
1258        (self.clone() - 1).prove_positive_or_zero()
1259    }
1260
1261    pub fn prove_negative_or_zero(&self) -> bool {
1262        if let TDim::Val(v) = self {
1263            return *v <= 0;
1264        }
1265        self.clone().neg().prove_positive_or_zero()
1266    }
1267
1268    pub fn prove_strict_negative(&self) -> bool {
1269        if let TDim::Val(v) = self {
1270            return *v < 0;
1271        }
1272        self.clone().neg().prove_strict_positive()
1273    }
1274
1275    /// Least common multiple of two `TDim`s when both reduce to positive
1276    /// integers.
1277    ///
1278    /// Returns `Val(0)` if either operand is `0`, and `None` if either is
1279    /// symbolic, negative, or if the LCM would overflow `i64`. Callers
1280    /// that need a safe answer for symbolic operands should fall back at
1281    /// the call site.
1282    pub fn lcm(&self, other: &TDim) -> Option<TDim> {
1283        match (self.as_i64(), other.as_i64()) {
1284            (Some(a), Some(b)) if a > 0 && b > 0 => {
1285                let g = (a as u64).gcd(&(b as u64));
1286                let l = (a as u64 / g).saturating_mul(b as u64);
1287                if l > i64::MAX as u64 { None } else { Some(TDim::Val(l as i64)) }
1288            }
1289            (Some(0), _) | (_, Some(0)) => Some(TDim::Val(0)),
1290            _ => None,
1291        }
1292    }
1293
1294    pub fn gcd(&self) -> u64 {
1295        use self::TDim::*;
1296        match self {
1297            Val(v) => v.unsigned_abs(),
1298            Sym(_) => 1,
1299            Add(terms) => {
1300                let (head, tail) = terms.split_first().unwrap();
1301                tail.iter().fold(head.gcd(), |a, b| a.gcd(&b.gcd()))
1302            }
1303            MulInt(p, a) => a.gcd().saturating_mul(p.unsigned_abs()),
1304            Mul(terms) => terms.iter().map(|t| t.gcd()).fold(1u64, |a, b| a.saturating_mul(b)),
1305            Min(terms) => terms.iter().map(|t| t.gcd()).reduce(|a, b| a.gcd(&b)).unwrap(),
1306            Max(terms) => terms.iter().map(|t| t.gcd()).reduce(|a, b| a.gcd(&b)).unwrap(),
1307            Div(a, q) => {
1308                if a.gcd() % *q == 0 {
1309                    a.gcd() / *q
1310                } else {
1311                    1
1312                }
1313            }
1314            Broadcast(terms) => terms.iter().map(|t| t.gcd()).reduce(|a, b| a.gcd(&b)).unwrap_or(1),
1315            Ge(_, _) | Eq(_, _) => 1,
1316        }
1317    }
1318
1319    fn div(&self, d: u64) -> TDim {
1320        use self::TDim::*;
1321        if d == 1 {
1322            return self.clone();
1323        }
1324        match self {
1325            Val(v) => Val(v / d as i64),
1326            Sym(_) => panic!(),
1327            Add(terms) => Add(terms.iter().map(|t| t.div(d)).collect()),
1328            Min(terms) => Min(terms.iter().map(|t| t.div(d)).collect()),
1329            Max(terms) => Max(terms.iter().map(|t| t.div(d)).collect()),
1330            Broadcast(terms) => Broadcast(terms.iter().map(|t| t.div(d)).collect()),
1331            Mul(_) => Div(Box::new(self.clone()), d),
1332            MulInt(p, a) => {
1333                if *p == d as i64 {
1334                    (**a).clone()
1335                } else {
1336                    let gcd = p.unsigned_abs().gcd(&d);
1337                    MulInt(p / gcd as i64, b!(a.div(d / gcd)))
1338                }
1339            }
1340            Div(a, q) => Div(a.clone(), q * d),
1341            Ge(_, _) | Eq(_, _) => Div(Box::new(self.clone()), d),
1342        }
1343    }
1344
1345    pub fn div_ceil(self, rhs: u64) -> TDim {
1346        TDim::Div(Box::new(Add(vec![self, Val(rhs as i64 - 1)])), rhs).reduce()
1347    }
1348
1349    pub fn guess_slope(&self, sym: &Symbol) -> (i64, u64) {
1350        fn slope_rec(d: &TDim, sym: &Symbol) -> (i64, i64) {
1351            match d {
1352                Val(_) => (0, 1),
1353                Sym(s) => ((sym == s) as i64, 1),
1354                Add(terms) => terms
1355                    .iter()
1356                    .map(|d| slope_rec(d, sym))
1357                    .fold((0, 1), |a, b| ((a.0 * b.1 + a.1 * b.0), (b.1 * a.1))),
1358                Mul(terms) => terms
1359                    .iter()
1360                    .map(|d| slope_rec(d, sym))
1361                    .fold((1, 1), |a, b| ((a.0 * b.0), (b.1 * a.1))),
1362                MulInt(p, a) => {
1363                    let (n, d) = slope_rec(a, sym);
1364                    (p * n, d)
1365                }
1366                Div(a, q) => {
1367                    let (n, d) = slope_rec(a, sym);
1368                    (n, d * *q as i64)
1369                }
1370                Broadcast(terms) => slope_rec(&terms[0], sym),
1371                Min(terms) => slope_rec(&terms[0], sym),
1372                Max(terms) => slope_rec(&terms[0], sym),
1373                Ge(_, _) | Eq(_, _) => (0, 1),
1374            }
1375        }
1376        let (p, q) = slope_rec(self, sym);
1377        reduce_ratio(p, q)
1378    }
1379
1380    #[allow(clippy::mutable_key_type)]
1381    pub fn symbols(&self) -> std::collections::HashSet<Symbol> {
1382        match self {
1383            Val(_) => maplit::hashset!(),
1384            Sym(s) => maplit::hashset!(s.clone()),
1385            Add(terms) | Mul(terms) | Broadcast(terms) | Min(terms) | Max(terms) => {
1386                terms.iter().fold(maplit::hashset!(), |mut set, v| {
1387                    set.extend(v.symbols());
1388                    set
1389                })
1390            }
1391            MulInt(_, a) => a.symbols(),
1392            Div(a, _) => a.symbols(),
1393            Ge(a, b) | Eq(a, b) => {
1394                let mut set = a.symbols();
1395                set.extend(b.symbols());
1396                set
1397            }
1398        }
1399    }
1400
1401    pub fn compatible_with(&self, other: &TDim) -> bool {
1402        if let Some(x) = (self.clone() - other).as_i64() {
1403            return x == 0;
1404        }
1405        true // maybe ? :)
1406    }
1407}
1408
1409pub(super) fn reduce_ratio(mut p: i64, mut q: i64) -> (i64, u64) {
1410    let gcd = p.abs().gcd(&q.abs());
1411    if gcd > 1 {
1412        p /= gcd;
1413        q /= gcd;
1414    }
1415    if q < 0 { (-p, (-q) as u64) } else { (p, q as u64) }
1416}
1417
1418impl Zero for TDim {
1419    fn zero() -> Self {
1420        Val(0)
1421    }
1422    fn is_zero(&self) -> bool {
1423        matches!(self, Val(0))
1424    }
1425}
1426
1427impl Default for TDim {
1428    fn default() -> TDim {
1429        Val(0)
1430    }
1431}
1432
1433impl num_traits::Bounded for TDim {
1434    fn min_value() -> Self {
1435        TDim::Val(i64::MIN)
1436    }
1437
1438    fn max_value() -> Self {
1439        TDim::Val(i64::MAX)
1440    }
1441}
1442
1443impl num_traits::One for TDim {
1444    fn one() -> Self {
1445        TDim::Val(1)
1446    }
1447}
1448
1449impl ::std::iter::Sum for TDim {
1450    fn sum<I: Iterator<Item = TDim>>(iter: I) -> TDim {
1451        iter.fold(0.into(), |a, b| a + b)
1452    }
1453}
1454
1455impl<'a> ::std::iter::Sum<&'a TDim> for TDim {
1456    fn sum<I: Iterator<Item = &'a TDim>>(iter: I) -> TDim {
1457        iter.fold(0.into(), |a, b| a + b)
1458    }
1459}
1460
1461impl std::iter::Product for TDim {
1462    fn product<I: Iterator<Item = TDim>>(iter: I) -> Self {
1463        iter.fold(TDim::Val(1), |a, b| a * b)
1464    }
1465}
1466
1467impl<'a> ::std::iter::Product<&'a TDim> for TDim {
1468    fn product<I: Iterator<Item = &'a TDim>>(iter: I) -> TDim {
1469        iter.fold(1.into(), |a, b| a * b)
1470    }
1471}
1472
1473macro_rules! from_i {
1474    ($i: ty) => {
1475        impl From<$i> for TDim {
1476            fn from(v: $i) -> TDim {
1477                TDim::Val(v as _)
1478            }
1479        }
1480        impl<'a> From<&'a $i> for TDim {
1481            fn from(v: &'a $i) -> TDim {
1482                TDim::Val(*v as _)
1483            }
1484        }
1485    };
1486}
1487
1488from_i!(i32);
1489from_i!(i64);
1490from_i!(u64);
1491from_i!(isize);
1492from_i!(usize);
1493
1494impl From<Symbol> for TDim {
1495    fn from(it: Symbol) -> Self {
1496        TDim::Sym(it)
1497    }
1498}
1499
1500impl<'a> From<&'a Symbol> for TDim {
1501    fn from(it: &'a Symbol) -> Self {
1502        TDim::Sym(it.clone())
1503    }
1504}
1505
1506impl ops::Neg for TDim {
1507    type Output = Self;
1508    fn neg(self) -> Self {
1509        if let Val(v) = self { Val(-v) } else { TDim::MulInt(-1, Box::new(self)).reduce() }
1510    }
1511}
1512
1513impl<'a> ops::AddAssign<&'a TDim> for TDim {
1514    fn add_assign(&mut self, rhs: &'a TDim) {
1515        if rhs.is_zero() {
1516        } else if self.is_zero() {
1517            *self = rhs.clone();
1518        } else if let (Val(s), Val(o)) = (&mut *self, &rhs) {
1519            *s += o;
1520        } else {
1521            *self = TDim::Add(vec![std::mem::take(self), rhs.clone()]).reduce()
1522        }
1523    }
1524}
1525
1526impl<I> ops::AddAssign<I> for TDim
1527where
1528    I: Into<TDim>,
1529{
1530    fn add_assign(&mut self, rhs: I) {
1531        let rhs = rhs.into();
1532        if rhs.is_zero() {
1533        } else if self.is_zero() {
1534            *self = rhs;
1535        } else if let (Val(s), Val(o)) = (&mut *self, &rhs) {
1536            *s += o;
1537        } else {
1538            *self = TDim::Add(vec![std::mem::take(self), rhs]).reduce()
1539        }
1540    }
1541}
1542
1543impl<I> ops::Add<I> for TDim
1544where
1545    I: Into<TDim>,
1546{
1547    type Output = Self;
1548    fn add(mut self, rhs: I) -> Self {
1549        self += rhs;
1550        self
1551    }
1552}
1553
1554impl<'a> ops::Add<&'a TDim> for TDim {
1555    type Output = Self;
1556    fn add(mut self, rhs: &'a TDim) -> Self {
1557        self += rhs;
1558        self
1559    }
1560}
1561
1562#[allow(clippy::suspicious_op_assign_impl)]
1563impl<'a> ops::SubAssign<&'a TDim> for TDim {
1564    fn sub_assign(&mut self, rhs: &'a TDim) {
1565        if rhs.is_zero() {
1566        } else if self.is_zero() {
1567            *self = rhs.clone().neg();
1568        } else if let (Val(s), Val(o)) = (&mut *self, &rhs) {
1569            *s -= o;
1570        } else {
1571            *self = TDim::Add(vec![std::mem::take(self), rhs.clone().neg()]).reduce()
1572        }
1573    }
1574}
1575
1576impl<I> ops::SubAssign<I> for TDim
1577where
1578    I: Into<TDim>,
1579{
1580    fn sub_assign(&mut self, rhs: I) {
1581        let rhs = rhs.into();
1582        if rhs.is_zero() {
1583        } else if self.is_zero() {
1584            *self = rhs.neg();
1585        } else if let (Val(s), Val(o)) = (&mut *self, &rhs) {
1586            *s -= o;
1587        } else {
1588            *self = TDim::Add(vec![std::mem::take(self), rhs.neg()]).reduce()
1589        }
1590    }
1591}
1592
1593impl<I> ops::Sub<I> for TDim
1594where
1595    I: Into<TDim>,
1596{
1597    type Output = Self;
1598    fn sub(mut self, rhs: I) -> Self {
1599        self -= rhs;
1600        self
1601    }
1602}
1603
1604impl<'a> ops::Sub<&'a TDim> for TDim {
1605    type Output = Self;
1606    fn sub(mut self, rhs: &'a TDim) -> Self {
1607        self -= rhs;
1608        self
1609    }
1610}
1611
1612impl<I: Into<TDim>> ops::MulAssign<I> for TDim {
1613    fn mul_assign(&mut self, rhs: I) {
1614        let rhs = rhs.into();
1615        if self.is_one() {
1616            *self = rhs
1617        } else if rhs.is_one() {
1618        } else {
1619            *self = TDim::Mul(vec![rhs, std::mem::take(self)]).reduce()
1620        }
1621    }
1622}
1623
1624impl<'a> ops::MulAssign<&'a TDim> for TDim {
1625    fn mul_assign(&mut self, rhs: &'a TDim) {
1626        if self.is_one() {
1627            *self = rhs.clone()
1628        } else if rhs.is_one() {
1629        } else {
1630            *self = TDim::Mul(vec![std::mem::take(self), rhs.clone()]).reduce()
1631        }
1632    }
1633}
1634
1635impl<I: Into<TDim>> ops::Mul<I> for TDim {
1636    type Output = Self;
1637    fn mul(mut self, rhs: I) -> Self {
1638        self *= rhs.into();
1639        self
1640    }
1641}
1642
1643impl<'a> ops::Mul<&'a TDim> for TDim {
1644    type Output = Self;
1645    fn mul(mut self, rhs: &'a TDim) -> Self {
1646        self *= rhs;
1647        self
1648    }
1649}
1650
1651impl<I: AsPrimitive<u64> + PrimInt> ops::DivAssign<I> for TDim {
1652    fn div_assign(&mut self, rhs: I) {
1653        *self = TDim::Div(Box::new(std::mem::take(self)), rhs.as_()).reduce()
1654    }
1655}
1656
1657impl<I: AsPrimitive<u64> + PrimInt> ops::Div<I> for TDim {
1658    type Output = Self;
1659    fn div(mut self, rhs: I) -> Self {
1660        self /= rhs.as_();
1661        self
1662    }
1663}
1664
1665impl<I: AsPrimitive<u64> + PrimInt> ops::RemAssign<I> for TDim {
1666    fn rem_assign(&mut self, rhs: I) {
1667        *self += -(self.clone() / rhs.as_() * rhs.as_());
1668    }
1669}
1670
1671impl<I: AsPrimitive<u64> + PrimInt> ops::Rem<I> for TDim {
1672    type Output = Self;
1673    fn rem(mut self, rhs: I) -> Self {
1674        self %= rhs;
1675        self
1676    }
1677}
1678
1679#[cfg(test)]
1680mod tests {
1681    use super::*;
1682
1683    macro_rules! b( ($e:expr) => { Box::new($e) } );
1684
1685    lazy_static::lazy_static! {
1686        static ref table: SymbolScope = SymbolScope::default();
1687        static ref A: Symbol = table.sym("a");
1688        static ref B: Symbol = table.sym("b");
1689        static ref C: Symbol = table.sym("c");
1690        static ref D: Symbol = table.sym("d");
1691        static ref E: Symbol = table.sym("e");
1692    }
1693
1694    fn neg(a: &TDim) -> TDim {
1695        mul(-1, a)
1696    }
1697
1698    fn add(a: &TDim, b: &TDim) -> TDim {
1699        TDim::Add(vec![a.clone(), b.clone()])
1700    }
1701
1702    fn mul(a: i64, b: &TDim) -> TDim {
1703        TDim::MulInt(a, b![b.clone()])
1704    }
1705
1706    fn div(a: &TDim, b: u64) -> TDim {
1707        TDim::Div(b!(a.clone()), b)
1708    }
1709
1710    #[test]
1711    fn reduce_add() {
1712        assert_eq!(add(&A.to_dim(), &neg(&A.to_dim())).reduce(), Val(0))
1713    }
1714
1715    #[test]
1716    fn max_low_bound_from_any_term() {
1717        let a = A.to_dim();
1718        let pad = TDim::Max(vec![Val(0), a.clone() - 4]);
1719        assert_eq!(pad.low_inclusive_bound(), Some(0));
1720        assert!(pad.prove_positive_or_zero());
1721        let crop = TDim::Min(vec![Val(4), a]);
1722        assert_eq!(crop.high_inclusive_bound(), Some(4));
1723    }
1724
1725    #[test]
1726    fn lcm_basic() {
1727        assert_eq!(Val(16).lcm(&Val(32)), Some(Val(32)));
1728        assert_eq!(Val(32).lcm(&Val(16)), Some(Val(32)));
1729        assert_eq!(Val(6).lcm(&Val(8)), Some(Val(24)));
1730        assert_eq!(Val(7).lcm(&Val(7)), Some(Val(7)));
1731        // Symbolic: not computable; callers fall back.
1732        assert_eq!(Val(16).lcm(&A.to_dim()), None);
1733    }
1734
1735    #[test]
1736    fn reduce_neg_mul() {
1737        assert_eq!(neg(&mul(2, &A.to_dim())).reduce(), mul(-2, &A.to_dim()))
1738    }
1739
1740    #[test]
1741    fn reduce_cplx_ex_2() {
1742        assert_eq!(
1743            add(
1744                &add(&Val(-4), &mul(-2, &div(&A.to_dim(), 4))),
1745                &mul(-2, &mul(-1, &div(&A.to_dim(), 4)))
1746            )
1747            .reduce(),
1748            Val(-4)
1749        )
1750    }
1751
1752    #[test]
1753    fn reduce_cplx_ex_3() {
1754        assert_eq!(div(&MulInt(1, b!(MulInt(4, b!(A.to_dim())))), 4).reduce(), A.to_dim())
1755    }
1756
1757    #[test]
1758    fn reduce_cplx_ex_4() {
1759        // (S+1)/2 + (1-S)/2 == 1
1760        assert_eq!(
1761            add(&div(&add(&A.to_dim(), &Val(1)), 2), &div(&add(&neg(&A.to_dim()), &Val(1)), 2))
1762                .reduce(),
1763            1.into()
1764        );
1765    }
1766
1767    #[test]
1768    fn reduce_mul_mul_1() {
1769        assert_eq!(mul(3, &mul(2, &A.to_dim())).reduce(), mul(6, &A.to_dim()))
1770    }
1771
1772    #[test]
1773    fn reduce_mul_mul_2() {
1774        assert_eq!(mul(-2, &mul(-1, &A.to_dim())).reduce(), mul(2, &A.to_dim()))
1775    }
1776
1777    #[test]
1778    fn reduce_mul_div_1() {
1779        assert_eq!(mul(2, &div(&mul(-1, &A.to_dim()), 3)).reduce(), mul(-2, &div(&A.to_dim(), 3)))
1780    }
1781
1782    #[test]
1783    fn const_and_add() {
1784        let e: TDim = 2i64.into();
1785        assert_eq!(e.eval(&SymbolValues::default()).to_i64().unwrap(), 2);
1786        let e: TDim = TDim::from(2) + 3;
1787        assert_eq!(e.eval(&SymbolValues::default()).to_i64().unwrap(), 5);
1788        let e: TDim = TDim::from(2) - 3;
1789        assert_eq!(e.eval(&SymbolValues::default()).to_i64().unwrap(), -1);
1790        let e: TDim = -TDim::from(2);
1791        assert_eq!(e.eval(&SymbolValues::default()).to_i64().unwrap(), -2);
1792    }
1793
1794    #[test]
1795    fn substitution() {
1796        let a: TDim = A.to_dim();
1797        assert_eq!(a.eval(&SymbolValues::default().with(&A, 2)).to_i64().unwrap(), 2);
1798        let e = a + 3;
1799        assert_eq!(e.eval(&SymbolValues::default().with(&A, 2)).to_i64().unwrap(), 5);
1800    }
1801
1802    #[test]
1803    fn reduce_adds() {
1804        let e: TDim = TDim::from(2) + 1;
1805        assert_eq!(e, TDim::from(3));
1806        let e: TDim = TDim::from(3) + 2;
1807        assert_eq!(e, TDim::from(5));
1808        let e: TDim = TDim::from(3) + 0;
1809        assert_eq!(e, TDim::from(3));
1810        let e: TDim = TDim::from(3) + 2 + 1;
1811        assert_eq!(e, TDim::from(6));
1812    }
1813
1814    #[test]
1815    fn reduce_muls() {
1816        let e: TDim = Val(1) * A.to_dim();
1817        assert_eq!(e, A.to_dim());
1818        let e: TDim = A.to_dim() * &B.to_dim() * 1;
1819        assert_eq!(e, A.to_dim() * &B.to_dim());
1820    }
1821
1822    #[test]
1823    fn reduce_divs() {
1824        let e: TDim = TDim::from(2) / 1;
1825        assert_eq!(e, TDim::from(2));
1826        let e: TDim = TDim::from(3) / 2;
1827        assert_eq!(e, TDim::from(1));
1828        let e: TDim = TDim::from(3) % 2;
1829        assert_eq!(e, TDim::from(1));
1830        let e: TDim = TDim::from(5) / 2;
1831        assert_eq!(e, TDim::from(2));
1832        let e: TDim = TDim::from(5) % 2;
1833        assert_eq!(e, TDim::from(1));
1834    }
1835
1836    #[test]
1837    fn reduce_div_bug_0() {
1838        let e1: TDim = (A.to_dim() + 23) / 2 - 1;
1839        let e2: TDim = (A.to_dim() + 21) / 2;
1840        assert_eq!(e1, e2);
1841    }
1842
1843    #[test]
1844    fn reduce_div_bug_1() {
1845        let e1: TDim = (A.to_dim() + -1) / 2;
1846        let e2: TDim = (A.to_dim() + 1) / 2 - 1;
1847        assert_eq!(e1, e2);
1848    }
1849
1850    #[test]
1851    fn reduce_div_bug_2() {
1852        let e1: TDim = ((A.to_dim() + 1) / 2 + 1) / 2;
1853        let e2: TDim = (A.to_dim() + 3) / 4;
1854        assert_eq!(e1, e2);
1855    }
1856
1857    #[test]
1858    fn divide_multiple_plus_remainder() {
1859        // (k·X + r)/k → X under truncating division when 0 ≤ r < k AND X ≥ 0.
1860        let scope = SymbolScope::default().with_assertion("S>=0").unwrap();
1861        let s = scope.sym("S");
1862
1863        // (2S+1)/2 → S
1864        let e: TDim = (s.to_dim() * 2 + 1) / 2;
1865        assert_eq!(e.simplify(), s.to_dim());
1866
1867        // -1 + (2S+1)/2 → S - 1
1868        let e: TDim = (s.to_dim() * 2 + 1) / 2 - 1;
1869        assert_eq!(e.simplify(), s.to_dim() - 1);
1870
1871        // (2S-1)/2 → S - 1   (Val rule extracts -1 first, then our rule)
1872        let e: TDim = (s.to_dim() * 2 - 1) / 2;
1873        assert_eq!(e.simplify(), s.to_dim() - 1);
1874
1875        // (4S+3)/2 → 2S + 1   (Val rule extracts 1 = 3/2, then our rule on (4S+1)/2 → 2S)
1876        let e: TDim = (s.to_dim() * 4 + 3) / 2;
1877        assert_eq!(e.simplify(), s.to_dim() * 2 + 1);
1878    }
1879
1880    #[test]
1881    fn divide_multiple_plus_remainder_no_assertion() {
1882        // Without an X≥0 assertion the (k·X+c)/k → X identity does NOT hold
1883        // (X=-1, k=2, c=1 gives -1/2=0 ≠ X under truncating division). The
1884        // wiggle Div arm used to emit that variant unconditionally; reduce()
1885        // would then pick it on cost. Now wiggle skips the variant when the
1886        // remainder bucket contains a Val, leaving only the sound rule
1887        // gated on prove_positive_or_zero in simplify_rec.
1888        let scope = SymbolScope::default();
1889        let s = scope.sym("S");
1890        let e: TDim = (s.to_dim() * 2 + 1) / 2;
1891        assert_ne!(e.simplify(), s.to_dim());
1892    }
1893
1894    #[test]
1895    fn modulo_div_is_zero() {
1896        // (Y − q·(Y/q)) / q = 0 for any Y and any q — the modulo remainder
1897        // divided by the modulus is always zero under truncating division.
1898        let scope = SymbolScope::default();
1899        let s = scope.sym("S");
1900        // Simple case: (S - 2*(S/2)) / 2 = (S mod 2) / 2 = 0
1901        let e: TDim = (s.to_dim() - s.to_dim() / 2 * 2) / 2;
1902        assert_eq!(e.simplify(), TDim::Val(0));
1903        // Composite case: ((S+1) - 2*((S+1)/2)) / 2 = 0
1904        // This is the exact pattern from SameUpper conv padding.
1905        let a = s.to_dim() + 1;
1906        let e2: TDim = (a.clone() - a.clone() / 2 * 2) / 2;
1907        assert_eq!(e2.simplify(), TDim::Val(0));
1908    }
1909
1910    #[test]
1911    fn reduce_div_bug_3() {
1912        let e1: TDim = (A.to_dim() / 2) * -4;
1913        let e2: TDim = (A.to_dim() / 2) * -4 / 1;
1914        assert_eq!(e1, e2);
1915    }
1916
1917    #[test]
1918    fn reduce_mul_div() {
1919        let e: TDim = A.to_dim() * 2 / 2;
1920        assert_eq!(e, A.to_dim());
1921    }
1922
1923    #[test]
1924    fn expand_polynomial_two_add_factors() {
1925        // (a + 2*a*b) * (1 + b)  ==poly==  a * (1 + b) * (1 + 2*b)
1926        // Both fully expand to a + 3*a*b + 2*a*b*b.  We don't auto-expand in
1927        // simplify (it would block maybe_div on factored-form denominators),
1928        // but expand_polynomial does, and Reshape uses it for volume checks.
1929        let a = A.to_dim();
1930        let b = B.to_dim();
1931        let lhs = (a.clone() + a.clone() * &b * 2) * (TDim::from(1) + &b);
1932        let rhs = a.clone() * (TDim::from(1) + &b) * (TDim::from(1) + b.clone() * 2);
1933        assert_eq!(lhs.expand_polynomial(), rhs.expand_polynomial());
1934    }
1935
1936    #[test]
1937    fn reduce_div_mul() {
1938        let e: TDim = A.to_dim() / 2 * 2;
1939        assert_ne!(e, A.to_dim());
1940    }
1941
1942    #[test]
1943    fn reduce_add_div() {
1944        let e: TDim = A.to_dim() / 2 + 1;
1945        assert_eq!(e, ((A.to_dim() + 2) / 2));
1946    }
1947
1948    #[test]
1949    fn reduce_neg_mul_() {
1950        let e: TDim = TDim::from(1) - A.to_dim() * 2;
1951        assert_eq!(e, TDim::from(1) + A.to_dim() * -2);
1952    }
1953
1954    #[test]
1955    fn reduce_add_rem_1() {
1956        assert_eq!(((A.to_dim() + 4) % 2), (A.to_dim() % 2));
1957    }
1958
1959    #[test]
1960    fn reduce_add_rem_2() {
1961        assert_eq!(((A.to_dim() - 4) % 2), (A.to_dim() % 2));
1962    }
1963
1964    #[test]
1965    fn reduce_rem_div() {
1966        let e: TDim = A.to_dim() % 2 / 2;
1967        assert_eq!(e, TDim::from(0));
1968    }
1969
1970    #[test]
1971    fn conv2d_ex_1() {
1972        let e = (TDim::from(1) - 1 + 1).div_ceil(1);
1973        assert_eq!(e, TDim::from(1));
1974    }
1975
1976    #[test]
1977    fn conv2d_ex_2() {
1978        let e = (A.to_dim() - 3 + 1).div_ceil(1);
1979        assert_eq!(e, A.to_dim() + -2);
1980    }
1981
1982    #[test]
1983    fn extract_int_gcd_from_muls() {
1984        let term = (A.to_dim() + 1) / 4;
1985        let mul = (term.clone() * 24 - 24) * (term.clone() * 2 - 2);
1986        let target = (term.clone() - 1) * (term.clone() - 1) * 48;
1987        assert_eq!(mul, target);
1988    }
1989
1990    #[test]
1991    fn equality_of_muls() {
1992        let term = (A.to_dim() + 1) / 4;
1993        let mul1 = (term.clone() * 2 - 3) * (term.clone() - 1);
1994        let mul2 = (term.clone() - 1) * (term.clone() * 2 - 3);
1995        assert_eq!(mul1, mul2);
1996    }
1997
1998    #[test]
1999    fn factorize_complex_expr_times_int() {
2000        let term = (A.to_dim() + 1) / 4;
2001        let e = term.clone() * 2 - &term - 1;
2002        assert_eq!(e, term - 1);
2003    }
2004
2005    #[test]
2006    fn broadcast_over_min() {
2007        // assuming a>0, b>0 then a#min(a,b) can be replaced by a
2008        // proof:
2009        //    if b == 1 => min(a,b)=1 => a#1=a => ok
2010        //    if a <= b => min(a,b)=a => ok
2011        //    if 1 < B < A => expression was invalid, we're generalizing over the non-domain and ignoring the constraint
2012        for a in 1..5 {
2013            for b in 1..5 {
2014                if b > 1 && a > b {
2015                    assert!(a.broadcast(a.min(b)).is_err());
2016                } else {
2017                    assert_eq!(a.broadcast(a.min(b)).unwrap(), a);
2018                }
2019            }
2020        }
2021    }
2022
2023    #[test]
2024    fn min_ints_1() {
2025        assert_eq!(2.to_dim().mini(1.to_dim()), 1.to_dim());
2026    }
2027
2028    #[test]
2029    fn min_ints_2() {
2030        assert_eq!(1.to_dim().mini(2.to_dim()), 1.to_dim());
2031    }
2032
2033    #[test]
2034    fn min_same() {
2035        assert_eq!(A.to_dim().mini(A.to_dim()), A.to_dim());
2036    }
2037
2038    #[test]
2039    fn min_noop() {
2040        assert_eq!(A.to_dim().mini(1.to_dim()), A.to_dim().mini(1.to_dim()));
2041    }
2042
2043    #[test]
2044    fn min_diff_1() {
2045        assert_eq!((A.to_dim() + 1).mini(A.to_dim() + 2), A.to_dim() + 1);
2046    }
2047
2048    #[test]
2049    fn slope_0() {
2050        assert_eq!(12.to_dim().guess_slope(&A), (0, 1));
2051    }
2052
2053    #[test]
2054    fn slope_1() {
2055        assert_eq!(A.to_dim().guess_slope(&A), (1, 1));
2056    }
2057
2058    #[test]
2059    fn slope_2() {
2060        assert_eq!((A.to_dim() * 2).guess_slope(&A), (2, 1));
2061    }
2062
2063    #[test]
2064    fn slope_3() {
2065        assert_eq!((A.to_dim() * 2 + A.to_dim() / 2).guess_slope(&A), (5, 2));
2066    }
2067
2068    #[test]
2069    fn slope_4() {
2070        assert_eq!((A.to_dim()).guess_slope(&B), (0, 1));
2071    }
2072
2073    #[test]
2074    fn slope_5() {
2075        assert_eq!((A.to_dim() + 1).guess_slope(&A), (1, 1));
2076        assert_eq!((A.to_dim() + 1).guess_slope(&B), (0, 1));
2077    }
2078
2079    #[test]
2080    fn slope_6() {
2081        assert_eq!((A.to_dim() + 1).guess_slope(&A), (1, 1));
2082        assert_eq!((A.to_dim() + B.to_dim()).guess_slope(&B), (1, 1));
2083    }
2084
2085    #[test]
2086    fn min_0() -> TractResult<()> {
2087        let symbols = SymbolScope::default();
2088        assert_eq!(
2089            symbols.parse_tdim("min(S+3, S+2)").unwrap().simplify(),
2090            symbols.parse_tdim("S+2").unwrap(),
2091        );
2092        Ok(())
2093    }
2094
2095    #[test]
2096    fn commutative_mul_parens() -> TractResult<()> {
2097        let symbols = SymbolScope::default();
2098        assert_eq!(
2099            symbols.parse_tdim("A*(B*C)").unwrap().simplify(),
2100            symbols.parse_tdim("(B*A)*C").unwrap().simplify(),
2101        );
2102        Ok(())
2103    }
2104
2105    #[test]
2106    fn commutative_in_nemo_parakeet_model() -> TractResult<()> {
2107        let symbols = SymbolScope::default();
2108        assert_eq!(
2109            symbols
2110                .parse_tdim("8*(1+-1*max(0,5000+-1*(S+7)/8)+max(0,4999+(S+7)/8))*((B)*((S+7)/8))")
2111                .unwrap()
2112                .simplify(),
2113            symbols
2114                .parse_tdim("8*((B)*(1+-1*max(0,5000+-1*(S+7)/8)+max(0,4999+(S+7)/8)))*((S+7)/8)")
2115                .unwrap()
2116                .simplify(),
2117        );
2118        Ok(())
2119    }
2120
2121    #[test]
2122    fn commutative_mul_parens_deep() -> TractResult<()> {
2123        let symbols = SymbolScope::default();
2124        let deep_tdim = Mul(vec![
2125            Mul(vec![Mul(vec![Mul(vec![A.to_dim(), B.to_dim()]), C.to_dim()]), D.to_dim()]),
2126            E.to_dim(),
2127        ])
2128        .simplify();
2129        assert_eq!(deep_tdim, symbols.parse_tdim("a*b*c*d*e").unwrap().simplify());
2130        Ok(())
2131    }
2132
2133    // ---- Tests for new comparison/not TDim variants ----
2134
2135    #[test]
2136    fn ge_concrete_true() {
2137        assert_eq!(Ge(b!(Val(5)), b!(Val(3))).reduce(), Val(1));
2138    }
2139
2140    #[test]
2141    fn ge_concrete_false() {
2142        assert_eq!(Ge(b!(Val(2)), b!(Val(3))).reduce(), Val(0));
2143    }
2144
2145    #[test]
2146    fn lt_concrete_true() {
2147        // Lt(2,3) normalizes to Ge(3, 2+1) = Ge(3, 3)
2148        assert_eq!(Ge(b!(Val(3)), b!(Val(3))).reduce(), Val(1));
2149    }
2150
2151    #[test]
2152    fn lt_concrete_false() {
2153        // Lt(5,3) normalizes to Ge(3, 5+1) = Ge(3, 6)
2154        assert_eq!(Ge(b!(Val(3)), b!(Val(6))).reduce(), Val(0));
2155    }
2156
2157    #[test]
2158    fn eq_concrete_true() {
2159        assert_eq!(Eq(b!(Val(3)), b!(Val(3))).reduce(), Val(1));
2160    }
2161
2162    #[test]
2163    fn eq_concrete_false() {
2164        assert_eq!(Eq(b!(Val(3)), b!(Val(4))).reduce(), Val(0));
2165    }
2166
2167    #[test]
2168    fn not_val_0() {
2169        // not(0) = 1 - 0 = 1
2170        assert_eq!((Val(1) - Val(0)).reduce(), Val(1));
2171    }
2172
2173    #[test]
2174    fn not_val_1() {
2175        // not(1) = 1 - 1 = 0
2176        assert_eq!((Val(1) - Val(1)).reduce(), Val(0));
2177    }
2178
2179    #[test]
2180    fn not_lt_becomes_ge() {
2181        // not(Lt(x1, T)) = 1 - Ge(T, x1+1); check it evaluates correctly at boundary
2182        let s = SymbolScope::default();
2183        let t = s.sym("T");
2184        let x1 = s.sym("x1");
2185        // at x1 = T (boundary), Ge(T, T+1) = 0, so 1 - 0 = 1 (not-lt is true when x1 >= T)
2186        let expr = Val(1) - Ge(b!(Sym(t.clone())), b!(Sym(x1.clone()) + Val(1)));
2187        let at_boundary = expr.substitute(&x1, &Sym(t.clone())).unwrap().simplify();
2188        assert_eq!(at_boundary, Val(1));
2189    }
2190
2191    #[test]
2192    fn product_assertion_does_not_prove_its_negation() {
2193        // The slope of MH * MW in MH is not linear: an assertion on the product
2194        // must not let -MH * MW >= 0, nor min(10, 10 + MH * MW) pick the larger.
2195        let s = SymbolScope::default();
2196        for assertion in ["MH >= 1", "MW >= 1", "MH * MW >= 1"] {
2197            s.add_assertion(assertion).unwrap();
2198        }
2199        let product = Sym(s.sym("MH")) * Sym(s.sym("MW"));
2200        assert!(!(-product.clone()).prove_positive_or_zero());
2201        let larger = Val(10) + product;
2202        assert_ne!(Min(vec![Val(10), larger.clone()]).simplify(), larger);
2203    }
2204
2205    #[test]
2206    fn eq_with_assertion_proves_false() {
2207        // Eq(T, 0) should reduce to Val(0) when T >= 1
2208        let s = SymbolScope::default();
2209        s.add_assertion("T >= 1").unwrap();
2210        let t = s.sym("T");
2211        let expr = Eq(b!(Sym(t)), b!(Val(0)));
2212        assert_eq!(expr.simplify(), Val(0));
2213    }
2214
2215    #[test]
2216    fn ge_coord_at_extremes() {
2217        // Ge(x1, T) should not simplify without coordinate substitution
2218        let s = SymbolScope::default();
2219        s.add_assertion("T >= 1").unwrap();
2220        let t = s.sym("T");
2221        let x1 = s.sym("x1");
2222        let expr = Ge(b!(Sym(x1.clone())), b!(Sym(t.clone())));
2223        // simplify() alone can't prove this false (x1 could be > T)
2224        // but with coordinate substitution (x1 = T-1), Ge(T-1, T) = 0
2225        let at_max = expr.substitute(&x1, &(Sym(t.clone()) - Val(1))).unwrap().simplify();
2226        assert_eq!(at_max, Val(0));
2227    }
2228
2229    #[test]
2230    fn eval_to_i64_new_variants() {
2231        use super::super::sym::SymbolValues;
2232        let sv = SymbolValues::default();
2233        assert_eq!(Ge(b!(Val(5)), b!(Val(3))).eval_to_i64(&sv).unwrap(), 1);
2234        assert_eq!(Ge(b!(Val(3)), b!(Val(5))).eval_to_i64(&sv).unwrap(), 0);
2235        assert_eq!(Eq(b!(Val(3)), b!(Val(3))).eval_to_i64(&sv).unwrap(), 1);
2236        assert_eq!(Eq(b!(Val(3)), b!(Val(4))).eval_to_i64(&sv).unwrap(), 0);
2237    }
2238
2239    #[test]
2240    fn eq_boolean_simplifies() {
2241        let s = SymbolScope::default();
2242        s.add_assertion("cw >= 0").unwrap();
2243        s.add_assertion("cw <= 1").unwrap();
2244        let cw = s.sym("cw");
2245        // Eq(1 - cw, 0) → cw
2246        assert_eq!(Eq(b!(Val(1) - Sym(cw.clone())), b!(Val(0))).simplify(), Sym(cw.clone()));
2247        // Eq(cw, 0) → 1 - cw
2248        assert_eq!(Eq(b!(Sym(cw.clone())), b!(Val(0))).simplify(), Val(1) - Sym(cw.clone()));
2249        // Eq(cw, 1) → cw
2250        assert_eq!(Eq(b!(Sym(cw.clone())), b!(Val(1))).simplify(), Sym(cw.clone()));
2251        // Eq(1 - cw, 1) → 1 - cw
2252        assert_eq!(Eq(b!(Val(1) - Sym(cw.clone())), b!(Val(1))).simplify(), Val(1) - Sym(cw));
2253    }
2254
2255    #[test]
2256    fn eq_boolean_mul_of_ge() {
2257        // Product of Ge terms: Ge(a,b) * Ge(c,d) is in [0,1]
2258        // so Eq(product, 0) should simplify to 1 - product
2259        let s = SymbolScope::default();
2260        let x = s.sym("x");
2261        let product =
2262            Mul(vec![Ge(b!(Val(2)), b!(Sym(x.clone()))), Ge(b!(Sym(x.clone())), b!(Val(0)))]);
2263        let eq = Eq(b!(product.clone()), b!(Val(0)));
2264        assert_eq!(eq.simplify(), Val(1) - product);
2265    }
2266
2267    #[test]
2268    fn min_1_max_0_sym() {
2269        // Min(1, Max(0, X)) must not simplify away the Min when X is unconstrained.
2270        let s = SymbolScope::default();
2271        let x = s.sym("X");
2272        let expr = Min(vec![Val(1), Max(vec![Val(0), Sym(x)])]);
2273        let simplified = expr.simplify();
2274        eprintln!("simplified: {simplified}");
2275        assert!(format!("{simplified}").contains("min"), "Min dropped: {simplified}");
2276    }
2277
2278    #[test]
2279    fn min_preserved_in_subtraction_parts() {
2280        // Test that Min([1, X]) simplifies correctly in isolation
2281        let s = SymbolScope::default();
2282        let t = s.sym("T");
2283        let p = s.sym("P");
2284        let ss = s.sym("S");
2285
2286        let cum_after =
2287            Max(vec![Val(0), (Sym(t.clone()) + Val(1)) * Sym(p.clone()) - Sym(ss.clone())]);
2288        let min_after = Min(vec![Val(1), cum_after.clone()]);
2289        let simplified = min_after.simplify();
2290        eprintln!("min_after simplified: {simplified}");
2291        // Must contain "min" — the Min must not be dropped
2292        assert!(format!("{simplified}").contains("min"), "Min wrapper was dropped: {simplified}");
2293    }
2294
2295    #[test]
2296    fn min_preserved_in_subtraction() {
2297        // min(1, X) - min(1, Y) must preserve the min() wrappers.
2298        // This is the pattern used by PulseV2Pad's output_facts for after-padding.
2299        let s = SymbolScope::default();
2300        let t = s.sym("T");
2301        let p = s.sym("P");
2302        let ss = s.sym("S");
2303
2304        let cum_after =
2305            Max(vec![Val(0), (Sym(t.clone()) + Val(1)) * Sym(p.clone()) - Sym(ss.clone())]);
2306        let cum_before = Max(vec![Val(0), Sym(t.clone()) * Sym(p.clone()) - Sym(ss.clone())]);
2307
2308        let ap = Min(vec![Val(1), cum_after.clone()]) - Min(vec![Val(1), cum_before.clone()]);
2309        let simplified = ap.simplify();
2310
2311        // At T=1, P=4, S=3: min(1, max(0, 8-3)) - min(1, max(0, 4-3)) = 1 - 1 = 0
2312        use super::super::sym::SymbolValues;
2313        let sv = SymbolValues::default().with(&t, 1).with(&p, 4).with(&ss, 3);
2314        assert_eq!(simplified.eval_to_i64(&sv).unwrap(), 0, "simplified: {simplified}");
2315
2316        // At T=0, P=4, S=3: min(1, max(0, 4-3)) - min(1, max(0, 0-3)) = 1 - 0 = 1
2317        let sv = SymbolValues::default().with(&t, 0).with(&p, 4).with(&ss, 3);
2318        assert_eq!(simplified.eval_to_i64(&sv).unwrap(), 1, "simplified: {simplified}");
2319
2320        // At T=0, P=1, S=1: min(1, max(0, 1-1)) - min(1, max(0, 0-1)) = 0 - 0 = 0
2321        let sv = SymbolValues::default().with(&t, 0).with(&p, 1).with(&ss, 1);
2322        assert_eq!(simplified.eval_to_i64(&sv).unwrap(), 0, "simplified: {simplified}");
2323    }
2324
2325    #[test]
2326    fn mul_neg_b_by_8() {
2327        let s = SymbolScope::default();
2328        let b = Sym(s.sym("B"));
2329        // 8*(-1*B) should equal -8*B
2330        let a = Mul(vec![Val(8), MulInt(-1, Box::new(b.clone()))]);
2331        let c = MulInt(-8, Box::new(b.clone()));
2332        let a_s = a.simplify();
2333        let c_s = c.simplify();
2334        assert_eq!(a_s, c_s, "8*(-1*B) should simplify the same as -8*B");
2335    }
2336
2337    /// Encoder-pulse case: (6 + 14·S) / 8 == (3 + 7·S) / 4.
2338    /// Both Add terms (Val(6) and MulInt(14, S)) share factor 2 with
2339    /// divisor 8, so the simplifier should reduce both sides by 2.
2340    #[test]
2341    fn reduce_div_by_common_factor_with_divisor() {
2342        let lhs = (A.to_dim() * 14 + 6) / 8;
2343        let rhs = (A.to_dim() * 7 + 3) / 4;
2344        assert_eq!(lhs, rhs);
2345    }
2346
2347    /// Common factor that fully divides the divisor → drop the divisor.
2348    /// (4·a + 8) / 4  ==  a + 2.
2349    #[test]
2350    fn reduce_div_when_factor_equals_divisor() {
2351        let lhs = (A.to_dim() * 4 + 8) / 4;
2352        let rhs = A.to_dim() + 2;
2353        assert_eq!(lhs, rhs);
2354    }
2355
2356    /// No common factor → no reduction (identity check).
2357    /// (3 + 7·a) / 4 stays as-is (gcd(3, 7, 4) = 1).
2358    #[test]
2359    fn no_reduce_when_terms_coprime_with_divisor() {
2360        let e = (A.to_dim() * 7 + 3) / 4;
2361        // We just check it didn't reduce to something weird; the
2362        // canonical form is `Div(Add(...), 4)`.
2363        match &e {
2364            Div(_, q) => assert_eq!(*q, 4),
2365            other => panic!("expected Div(_, 4), got {other:?}"),
2366        }
2367    }
2368
2369    /// Sym without an explicit `MulInt` wrapper has implicit coefficient 1.
2370    /// Any common factor gcd including 1 collapses to 1, so the reduction
2371    /// does nothing — the rule must not silently drop the Sym.
2372    #[test]
2373    fn no_reduce_when_sym_has_implicit_unit_coefficient() {
2374        // (a + 4) / 2 must stay non-trivial — gcd(1, 4, 2) = 1.
2375        let e = (A.to_dim() + 4) / 2;
2376        // It can simplify to other forms but it should still depend on `a`.
2377        // Eval at a=2 → (2+4)/2 = 3.  Eval at a=4 → (4+4)/2 = 4.
2378        let sv2 = SymbolValues::default().with(&A, 2);
2379        let sv4 = SymbolValues::default().with(&A, 4);
2380        assert_eq!(e.eval_to_i64(&sv2).unwrap(), 3);
2381        assert_eq!(e.eval_to_i64(&sv4).unwrap(), 4);
2382    }
2383}