Skip to main content

elinvar_engine/
diff.rs

1//! Comparing two versions of a design (REQUIREMENTS.md section 8): given
2//! `old` and `new` models sharing the same signatures and fields, find a
3//! minimal shrunk instance or trace allowed by one and forbidden by the
4//! other, or confirm they agree up to the chosen scope.
5
6use crate::model::{Model, model_error};
7use crate::report::{RESULT_VERSION, Report};
8use crate::solve::{Options, Verdict};
9use elinvar_logic::{
10    Decl, Error, Expr, ExprKind, Formula, FormulaKind, IntExpr, IntExprKind, Quantifier, Relation,
11    TemporalOp, Variable,
12};
13use serde::Serialize;
14use std::collections::BTreeMap;
15use std::fmt;
16
17/// How `new` differs from `old` up to the searched scope.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
19#[serde(rename_all = "snake_case")]
20#[non_exhaustive]
21pub enum DiffVerdict {
22    /// Every case up to the scope allowed by one is allowed by the other.
23    Equivalent,
24    /// `new` forbids at least one case `old` allows, and allows nothing extra.
25    Tightened,
26    /// `new` allows at least one case `old` forbids, and forbids nothing `old` allows.
27    Loosened,
28    /// Each model allows at least one case the other forbids.
29    Diverged,
30    /// One of the checks ran out of budget.
31    Unknown,
32    /// `diff --of`: the two models together allow no case, so there is
33    /// nothing to compare the functions on. The rules are wrong, not the
34    /// functions equal (DESIGN.md section 7.6).
35    Vacuous,
36}
37
38impl fmt::Display for DiffVerdict {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        let s = match self {
41            DiffVerdict::Equivalent => "equivalent",
42            DiffVerdict::Tightened => "tightened",
43            DiffVerdict::Loosened => "loosened",
44            DiffVerdict::Diverged => "diverged",
45            DiffVerdict::Unknown => "unknown",
46            DiffVerdict::Vacuous => "vacuous",
47        };
48        f.write_str(s)
49    }
50}
51
52/// The result of comparing two models ([`diff_models`]).
53#[derive(Clone, Debug, Serialize)]
54#[non_exhaustive]
55#[must_use]
56pub struct DiffReport {
57    /// The schema version.
58    pub elinvar: u32,
59    /// How `new` differs from `old`, or `None` when there are errors.
60    pub verdict: Option<DiffVerdict>,
61    /// A minimal case allowed by `old` and forbidden by `new`, if any.
62    pub only_in_old: Option<Report>,
63    /// A minimal case allowed by `new` and forbidden by `old`, if any.
64    pub only_in_new: Option<Report>,
65    /// Errors preventing the comparison (for example, mismatched signatures).
66    pub errors: Vec<Error>,
67    /// Plain-text summary made from the fields above.
68    pub story: String,
69}
70
71impl fmt::Display for DiffReport {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.story)
74    }
75}
76
77fn diff_error(message: String) -> Error {
78    model_error("model.diff_mismatch", message)
79}
80
81fn relation_map(model: &Model) -> BTreeMap<String, Relation> {
82    model
83        .relations()
84        .into_iter()
85        .map(|r| (r.name().to_string(), r))
86        .collect()
87}
88
89fn check_compatible(old: &Model, new: &Model) -> Vec<Error> {
90    let old_map = relation_map(old);
91    let new_map = relation_map(new);
92    let mut errors = Vec::new();
93    for (name, r_old) in &old_map {
94        match new_map.get(name) {
95            None => errors.push(diff_error(format!(
96                "`{name}` is declared in the old model but missing from the new model"
97            ))),
98            Some(r_new) => {
99                if r_old.arity() != r_new.arity() {
100                    errors.push(diff_error(format!(
101                        "`{name}` has arity {} in the old model and {} in the new model",
102                        r_old.arity(),
103                        r_new.arity()
104                    )));
105                }
106                if r_old.is_changing() != r_new.is_changing() {
107                    errors.push(diff_error(format!(
108                        "`{name}` changes in one model and is fixed in the other"
109                    )));
110                }
111            }
112        }
113    }
114    for name in new_map.keys() {
115        if !old_map.contains_key(name) {
116            errors.push(diff_error(format!(
117                "`{name}` is declared in the new model but missing from the old model"
118            )));
119        }
120    }
121    errors
122}
123
124fn rebind_expr(e: &Expr, target: &BTreeMap<String, Relation>) -> Expr {
125    match e.kind() {
126        ExprKind::Relation(r) => match target.get(r.name()) {
127            Some(mapped) => Expr::relation(mapped),
128            None => e.clone(),
129        },
130        ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => e.clone(),
131        ExprKind::Binary(op, a, b) => {
132            rebind_expr(a, target).apply_binary(*op, &rebind_expr(b, target))
133        }
134        ExprKind::Unary(op, a) => rebind_expr(a, target).apply_unary(*op),
135        ExprKind::Prime(a) => rebind_expr(a, target).prime(),
136        ExprKind::Comprehension(decls, body) => {
137            let ds = decls
138                .iter()
139                .map(|d| Decl::with(&d.var, d.mult, &rebind_expr(&d.expr, target)))
140                .collect();
141            Expr::comprehension(ds, &rebind_formula(body, target))
142        }
143        ExprKind::IfThenElse(c, a, b) => Expr::if_then_else(
144            &rebind_formula(c, target),
145            &rebind_expr(a, target),
146            &rebind_expr(b, target),
147        ),
148        ExprKind::IntToSet(v) => rebind_int(v, target).to_set(),
149    }
150}
151
152fn rebind_int(v: &IntExpr, target: &BTreeMap<String, Relation>) -> IntExpr {
153    match v.kind() {
154        IntExprKind::Constant(_) => v.clone(),
155        IntExprKind::Count(e) => rebind_expr(e, target).count(),
156        IntExprKind::Sum(e) => rebind_expr(e, target).sum(),
157        IntExprKind::Binary(op, a, b) => rebind_int(a, target).apply(*op, &rebind_int(b, target)),
158        IntExprKind::Negate(a) => rebind_int(a, target).negate(),
159        IntExprKind::IfThenElse(c, a, b) => IntExpr::if_then_else(
160            &rebind_formula(c, target),
161            &rebind_int(a, target),
162            &rebind_int(b, target),
163        ),
164        IntExprKind::SumOver(decls, body) => {
165            let ds = decls
166                .iter()
167                .map(|d| Decl::with(&d.var, d.mult, &rebind_expr(&d.expr, target)))
168                .collect();
169            IntExpr::sum_over(ds, &rebind_int(body, target))
170        }
171    }
172}
173
174fn rebind_formula(f: &Formula, target: &BTreeMap<String, Relation>) -> Formula {
175    match f.kind() {
176        FormulaKind::Constant(_) => f.clone(),
177        FormulaKind::Subset(a, b) => rebind_expr(a, target).is_in(&rebind_expr(b, target)),
178        FormulaKind::Equal(a, b) => rebind_expr(a, target).equals(&rebind_expr(b, target)),
179        FormulaKind::Multiplicity(m, a) => rebind_expr(a, target).apply_multiplicity(*m),
180        FormulaKind::Not(g) => rebind_formula(g, target).not(),
181        FormulaKind::And(fs) => Formula::and_all(
182            fs.iter()
183                .map(|g| rebind_formula(g, target))
184                .collect::<Vec<_>>(),
185        ),
186        FormulaKind::Or(fs) => Formula::or_all(
187            fs.iter()
188                .map(|g| rebind_formula(g, target))
189                .collect::<Vec<_>>(),
190        ),
191        FormulaKind::Implies(a, b) => rebind_formula(a, target).implies(&rebind_formula(b, target)),
192        FormulaKind::Iff(a, b) => rebind_formula(a, target).iff(&rebind_formula(b, target)),
193        FormulaKind::Quantified(q, decls, body) => {
194            let ds = decls
195                .iter()
196                .map(|d| Decl::with(&d.var, d.mult, &rebind_expr(&d.expr, target)))
197                .collect();
198            Formula::quantified(*q, ds, &rebind_formula(body, target))
199        }
200        FormulaKind::Temporal(op, g) => rebind_formula(g, target).temporal(*op),
201        FormulaKind::TemporalBinary(op, a, b) => {
202            rebind_formula(a, target).temporal_binary(*op, &rebind_formula(b, target))
203        }
204        FormulaKind::IntCompare(op, a, b) => {
205            rebind_int(a, target).compare_with(*op, &rebind_int(b, target))
206        }
207    }
208}
209
210fn diff_story(r: &DiffReport, scope: Option<usize>, steps: Option<usize>) -> String {
211    use std::fmt::Write as _;
212    let mut out = String::new();
213    if !r.errors.is_empty() {
214        for e in &r.errors {
215            let _ = writeln!(out, "error[{}]: {}", e.code, e.message);
216            if !e.fix.is_empty() {
217                let _ = writeln!(out, "  fix: {}", e.fix);
218            }
219        }
220        return out;
221    }
222    let verdict = r.verdict.unwrap_or(DiffVerdict::Unknown);
223    let _ = writeln!(out, "diff: {verdict}");
224    if let Some(old_rep) = &r.only_in_old
225        && old_rep.verdict == Some(Verdict::Counterexample)
226    {
227        let _ = writeln!(out, "\nallowed by old, forbidden by new:");
228        out.push_str(&old_rep.story);
229    }
230    if let Some(new_rep) = &r.only_in_new
231        && new_rep.verdict == Some(Verdict::Counterexample)
232    {
233        let _ = writeln!(out, "\nallowed by new, forbidden by old:");
234        out.push_str(&new_rep.story);
235    }
236    if verdict == DiffVerdict::Equivalent {
237        match (scope, steps) {
238            (Some(sc), Some(st)) => {
239                let _ = writeln!(
240                    out,
241                    "  both designs allow the same cases up to scope {sc}, {st} steps."
242                );
243            }
244            (Some(sc), None) => {
245                let _ = writeln!(out, "  both designs allow the same cases up to scope {sc}.");
246            }
247            _ => {
248                let _ = writeln!(
249                    out,
250                    "  both designs allow the same cases up to the searched scope."
251                );
252            }
253        }
254    }
255    out
256}
257
258/// Compares two models sharing the same signatures and fields, up to `scope`
259/// and `options`, returning a [`DiffReport`] with shrunk witnesses for any
260/// cases allowed by one model and forbidden by the other.
261pub fn diff_models(old: &Model, new: &Model, scope: usize, options: &Options) -> DiffReport {
262    diff_models_with_bitwidth(old, new, scope, elinvar_logic::DEFAULT_BITWIDTH, options)
263}
264
265/// Like [`diff_models`], using `bitwidth` for bounded `Int` atoms on both
266/// sides (used, for example, when comparing two imported SQL schemas whose
267/// integer literals need more than 4 bits).
268pub fn diff_models_with_bitwidth(
269    old: &Model,
270    new: &Model,
271    scope: usize,
272    bitwidth: u32,
273    options: &Options,
274) -> DiffReport {
275    let errors = check_compatible(old, new);
276    if !errors.is_empty() {
277        let mut r = DiffReport {
278            elinvar: RESULT_VERSION,
279            verdict: None,
280            only_in_old: None,
281            only_in_new: None,
282            errors,
283            story: String::new(),
284        };
285        r.story = diff_story(&r, None, None);
286        return r;
287    }
288    let old_map = relation_map(old);
289    let new_map = relation_map(new);
290    let has_changing = old.relations().iter().any(Relation::is_changing)
291        || new.relations().iter().any(Relation::is_changing);
292    let searched_steps = has_changing.then_some(options.steps);
293    let new_in_old = diff_facts_assertion(old, new, &old_map, options.slicing);
294    let old_in_new = diff_facts_assertion(new, old, &new_map, options.slicing);
295
296    // W25: both sides are independent read-only checks; run in parallel and
297    // combine in deterministic `(OnlyInOld, OnlyInNew)` order (AGENTS.md law 16).
298    let (rep_old, rep_new) = std::thread::scope(|s| {
299        let h_old = s.spawn(|| {
300            check_diff_side(
301                old,
302                new,
303                &old_map,
304                &new_in_old,
305                "OnlyInOld",
306                scope,
307                bitwidth,
308                options,
309            )
310        });
311        let rep_new = check_diff_side(
312            new,
313            old,
314            &new_map,
315            &old_in_new,
316            "OnlyInNew",
317            scope,
318            bitwidth,
319            options,
320        );
321        let rep_old = match h_old.join() {
322            Ok(r) => r,
323            Err(_) => check_diff_side(
324                old,
325                new,
326                &old_map,
327                &new_in_old,
328                "OnlyInOld",
329                scope,
330                bitwidth,
331                options,
332            ),
333        };
334        (rep_old, rep_new)
335    });
336
337    let mut errors = Vec::new();
338    errors.extend(rep_old.errors.iter().cloned());
339    errors.extend(rep_new.errors.iter().cloned());
340    if !errors.is_empty() {
341        let mut r = DiffReport {
342            elinvar: RESULT_VERSION,
343            verdict: None,
344            only_in_old: Some(rep_old),
345            only_in_new: Some(rep_new),
346            errors,
347            story: String::new(),
348        };
349        r.story = diff_story(&r, Some(scope), searched_steps);
350        return r;
351    }
352
353    let verdict = match (rep_old.verdict, rep_new.verdict) {
354        (Some(Verdict::Unknown), _) | (_, Some(Verdict::Unknown)) => DiffVerdict::Unknown,
355        (Some(Verdict::Counterexample), Some(Verdict::Counterexample)) => DiffVerdict::Diverged,
356        (Some(Verdict::Counterexample), _) => DiffVerdict::Tightened,
357        (_, Some(Verdict::Counterexample)) => DiffVerdict::Loosened,
358        _ => DiffVerdict::Equivalent,
359    };
360
361    let mut r = DiffReport {
362        elinvar: RESULT_VERSION,
363        verdict: Some(verdict),
364        only_in_old: Some(rep_old),
365        only_in_new: Some(rep_new),
366        errors: Vec::new(),
367        story: String::new(),
368    };
369    r.story = diff_story(&r, Some(scope), searched_steps);
370    r
371}
372
373/// Compares the tuples returned by a function expression `old_expr` in `old`
374/// against `new_expr` in `new` over cases allowed by both models (W10).
375///
376/// - `Tightened`: `new_expr` drops tuples `old_expr` returns (`only_in_old`).
377/// - `Loosened`: `new_expr` gains tuples `old_expr` lacks (`only_in_new`).
378/// - `Diverged`: `new_expr` both loses and gains tuples.
379/// - `Equivalent`: both functions return the same tuples in every shared case.
380pub fn diff_functions(
381    old: &Model,
382    old_expr: &Expr,
383    new: &Model,
384    new_expr: &Expr,
385    scope: usize,
386    bitwidth: u32,
387    options: &Options,
388) -> DiffReport {
389    let errors = check_compatible(old, new);
390    if !errors.is_empty() {
391        let mut r = DiffReport {
392            elinvar: RESULT_VERSION,
393            verdict: None,
394            only_in_old: None,
395            only_in_new: None,
396            errors,
397            story: String::new(),
398        };
399        r.story = diff_story(&r, None, None);
400        return r;
401    }
402    let old_map = relation_map(old);
403    let new_facts_in_old = rebind_formula(&new.all_facts(), &old_map);
404    let new_expr_in_old = rebind_expr(new_expr, &old_map);
405
406    let mut both = old.clone();
407    both.fact_named("new_model_facts", new_facts_in_old);
408
409    let has_changing = old.relations().iter().any(Relation::is_changing);
410    let lost_prop = if has_changing {
411        old_expr.is_in(&new_expr_in_old).always()
412    } else {
413        old_expr.is_in(&new_expr_in_old)
414    };
415    let gained_prop = if has_changing {
416        new_expr_in_old.is_in(old_expr).always()
417    } else {
418        new_expr_in_old.is_in(old_expr)
419    };
420
421    let (rep_old, rep_new) = std::thread::scope(|s| {
422        let h_old = s.spawn(|| {
423            both.check(&lost_prop)
424                .named("LostTuples")
425                .scope(scope)
426                .bitwidth(bitwidth)
427                .options(*options)
428                .without_holds_warnings()
429                .report()
430        });
431        let rep_new = both
432            .check(&gained_prop)
433            .named("GainedTuples")
434            .scope(scope)
435            .bitwidth(bitwidth)
436            .options(*options)
437            .without_holds_warnings()
438            .report();
439        let rep_old = match h_old.join() {
440            Ok(r) => r,
441            Err(_) => both
442                .check(&lost_prop)
443                .named("LostTuples")
444                .scope(scope)
445                .bitwidth(bitwidth)
446                .options(*options)
447                .without_holds_warnings()
448                .report(),
449        };
450        (rep_old, rep_new)
451    });
452
453    let mut errors = Vec::new();
454    errors.extend(rep_old.errors.iter().cloned());
455    errors.extend(rep_new.errors.iter().cloned());
456    if !errors.is_empty() {
457        let mut r = DiffReport {
458            elinvar: RESULT_VERSION,
459            verdict: None,
460            only_in_old: Some(rep_old),
461            only_in_new: Some(rep_new),
462            errors,
463            story: String::new(),
464        };
465        r.story = diff_story(&r, Some(scope), has_changing.then_some(options.steps));
466        return r;
467    }
468
469    let verdict = match (rep_old.verdict, rep_new.verdict) {
470        (Some(Verdict::Unknown), _) | (_, Some(Verdict::Unknown)) => DiffVerdict::Unknown,
471        (Some(Verdict::Counterexample), Some(Verdict::Counterexample)) => DiffVerdict::Diverged,
472        (Some(Verdict::Counterexample), _) => DiffVerdict::Tightened,
473        (_, Some(Verdict::Counterexample)) => DiffVerdict::Loosened,
474        // Both checks share the facts of both models: when those allow no
475        // case, "the same tuples" would claim more than is known (law 14).
476        (Some(Verdict::Vacuous), _) | (_, Some(Verdict::Vacuous)) => DiffVerdict::Vacuous,
477        _ => DiffVerdict::Equivalent,
478    };
479
480    let eval_diff = |rep: &Report, diff_e: &Expr| -> Option<String> {
481        if let Some(inst) = &rep.instance {
482            return elinvar_logic::evaluate_expr(inst, diff_e)
483                .ok()
484                .filter(|ts| !ts.is_empty())
485                .map(|ts| format!("{ts}"));
486        }
487        if let Some(tr) = &rep.trace {
488            let trace =
489                elinvar_logic::Trace::new(tr.fixed.clone(), tr.states.clone(), tr.loop_to).ok()?;
490            let k = rep.broken_at.unwrap_or(0);
491            return elinvar_logic::evaluate_trace_expr_at(&trace, diff_e, k)
492                .ok()
493                .filter(|ts| !ts.is_empty())
494                .map(|ts| format!("{ts}"));
495        }
496        None
497    };
498
499    let mut story = String::new();
500    use std::fmt::Write as _;
501    let _ = writeln!(story, "diff: {verdict}");
502    if rep_old.verdict == Some(Verdict::Counterexample) {
503        let lost = eval_diff(&rep_old, &old_expr.difference(&new_expr_in_old)).unwrap_or_default();
504        let _ = writeln!(story, "\ntuples lost by new: {lost}");
505        story.push_str(&rep_old.story);
506    }
507    if rep_new.verdict == Some(Verdict::Counterexample) {
508        let gained = eval_diff(&rep_new, &new_expr_in_old.difference(old_expr)).unwrap_or_default();
509        let _ = writeln!(story, "\ntuples gained by new: {gained}");
510        story.push_str(&rep_new.story);
511    }
512    if verdict == DiffVerdict::Vacuous {
513        let _ = writeln!(
514            story,
515            "  the two models together allow no case up to scope {scope}, so their functions \
516             cannot be compared: the rules contradict each other."
517        );
518    }
519    if verdict == DiffVerdict::Equivalent {
520        if has_changing {
521            let _ = writeln!(
522                story,
523                "  both functions return the same tuples up to scope {scope}, {} steps.",
524                options.steps
525            );
526        } else {
527            let _ = writeln!(
528                story,
529                "  both functions return the same tuples up to scope {scope}."
530            );
531        }
532    }
533
534    DiffReport {
535        elinvar: RESULT_VERSION,
536        verdict: Some(verdict),
537        only_in_old: Some(rep_old),
538        only_in_new: Some(rep_new),
539        errors: Vec::new(),
540        story,
541    }
542}
543
544/// Runs one side of `diff` (`OnlyInOld` or `OnlyInNew`).
545///
546/// - When the reduced diff assertion is trivially `true`, checks 1-state
547///   non-vacuity first so a pure tightening on a large temporal schema does
548///   not unroll every untouched table just to confirm `Holds` (B23).
549/// - When both models are any-state transition systems (no initial-state-only
550///   facts on changing relations, e.g. SQL diff `--from-any`), applies the
551///   exact One-step Transition Diff Reduction (W25): replaces `assumed`'s
552///   transition disjunction with `always (AssumedOnly or Stutter)` so COI
553///   slices away every untouched table and trigger, and referees any found
554///   counterexample against the FULL unreduced models (AGENTS.md law 13).
555#[allow(clippy::too_many_arguments)]
556fn check_diff_side(
557    assumed: &Model,
558    target: &Model,
559    assumed_map: &BTreeMap<String, Relation>,
560    assertion: &Formula,
561    name: &str,
562    scope: usize,
563    bitwidth: u32,
564    options: &Options,
565) -> Report {
566    let reduced = if options.slicing {
567        reduce_assumed_for_any_state_diff(assumed, target, assumed_map, options.steps)
568    } else {
569        None
570    };
571
572    let run_at_scope = |try_scope: usize| -> Report {
573        if matches!(assertion.kind(), FormulaKind::Constant(true)) && options.steps > 1 {
574            let mut fast = *options;
575            fast.steps = 1;
576            let mut cmd = assumed
577                .check(assertion)
578                .named(name)
579                .scope(try_scope)
580                .bitwidth(bitwidth)
581                .options(fast)
582                .without_holds_warnings();
583            if let Some((ref red_facts, _)) = reduced {
584                cmd = cmd.with_override_model_facts(red_facts.clone());
585            }
586            let rep = cmd.report();
587            if rep.verdict == Some(Verdict::Holds) {
588                return rep;
589            }
590        }
591
592        if let Some((ref reduced_facts, eff_steps)) = reduced {
593            let mut red_opts = *options;
594            red_opts.steps = eff_steps;
595            let rep = assumed
596                .check(assertion)
597                .named(name)
598                .scope(try_scope)
599                .bitwidth(bitwidth)
600                .options(red_opts)
601                .with_override_model_facts(reduced_facts.clone())
602                .without_holds_warnings()
603                .report();
604            // Law 13: referee any counterexample against the FULL unreduced models.
605            let verified = match rep.verdict {
606                Some(Verdict::Counterexample) => {
607                    let target_rebound = rebind_formula(&target.all_facts(), assumed_map);
608                    let full_check = assumed.all_facts().and(&target_rebound.not());
609                    if let Some(tr_rep) = &rep.trace {
610                        elinvar_logic::Trace::new(
611                            tr_rep.fixed.clone(),
612                            tr_rep.states.clone(),
613                            tr_rep.loop_to,
614                        )
615                        .ok()
616                        .is_some_and(|tr| {
617                            elinvar_logic::evaluate_trace(&tr, &full_check) == Ok(true)
618                        })
619                    } else if let Some(inst) = &rep.instance {
620                        elinvar_logic::evaluate(inst, &full_check) == Ok(true)
621                    } else {
622                        false
623                    }
624                }
625                Some(Verdict::Holds | Verdict::Vacuous | Verdict::Unknown) => true,
626                _ => false,
627            };
628            if verified {
629                return rep;
630            }
631        }
632
633        assumed
634            .check(assertion)
635            .named(name)
636            .scope(try_scope)
637            .bitwidth(bitwidth)
638            .options(*options)
639            .without_holds_warnings()
640            .report()
641    };
642
643    // W25: when searching for a counterexample at scope >= 2, probe smaller
644    // scopes (1, then 2 if scope >= 3) first. A verified counterexample at a
645    // smaller scope is already a valid minimal witness at `scope`, avoiding
646    // large full-scope SAT solves when a 1- or 2-row witness exists.
647    // `Holds` is only ever returned after searching the full `scope`.
648    if !matches!(assertion.kind(), FormulaKind::Constant(true)) && scope >= 2 {
649        let probes: &[usize] = if scope >= 3 { &[1, 2] } else { &[1] };
650        for &probe_scope in probes {
651            let rep = run_at_scope(probe_scope);
652            if rep.verdict == Some(Verdict::Counterexample) {
653                return rep;
654            }
655        }
656    }
657
658    run_at_scope(scope)
659}
660
661/// Exact One-step Transition Diff Reduction for any-state models (W25):
662/// when neither `assumed` nor `target` has initial-state-only facts on
663/// changing relations and every temporal fact is either a state invariant
664/// (`always P` with non-temporal `P`) or a 1-step transition disjunction
665/// containing a pure stutter arm, any trace satisfying `assumed ∧ ¬target`
666/// either violates a state invariant at some state `s_i` (witnessed by
667/// stuttering on `s_i`) or takes an arm in `AssumedOnly` at some step
668/// `s_i -> s_{i+1}` (witnessed by `s_i -> s_{i+1} -> s_{i+1}`).
669/// Therefore replacing `assumed`'s transition disjunction with
670/// `always (AssumedOnly ∨ Stutter)` is equisatisfiable with `assumed ∧ ¬target`
671/// and allows COI to slice away every unchanged table and trigger.
672fn reduce_assumed_for_any_state_diff(
673    assumed: &Model,
674    target: &Model,
675    assumed_map: &BTreeMap<String, Relation>,
676    requested_steps: usize,
677) -> Option<(Formula, usize)> {
678    let all_rels = assumed.relations();
679    if !all_rels.iter().any(Relation::is_changing) {
680        return None;
681    }
682    let mut a_conjs = Vec::new();
683    split_and_diff(&assumed.all_facts(), &mut a_conjs);
684    let target_rebound = rebind_formula(&target.all_facts(), assumed_map);
685    let mut t_conjs = Vec::new();
686    split_and_diff(&target_rebound, &mut t_conjs);
687
688    // Check that `target` has no initial-state-only facts on changing relations
689    // and no multi-step temporal facts, and collect its single transition disjunction.
690    let mut target_trans: Option<Vec<Formula>> = None;
691    for tc in &t_conjs {
692        if !tc.is_temporal() {
693            if formula_mentions_changing_diff(tc) {
694                return None;
695            }
696        } else if let FormulaKind::Temporal(TemporalOp::Always, inner) = tc.kind() {
697            if !inner.is_temporal() {
698                continue;
699            }
700            if !is_one_step_diff(inner) {
701                return None;
702            }
703            let arms = extract_always_or_arms(tc)?;
704            if target_trans.is_some() {
705                return None;
706            }
707            target_trans = Some(arms);
708        } else {
709            return None;
710        }
711    }
712    let target_arms = target_trans?;
713
714    // Same check on `assumed`, locating its single transition disjunction.
715    let mut assumed_trans_idx: Option<usize> = None;
716    let mut assumed_arms: Option<Vec<Formula>> = None;
717    for (idx, ac) in a_conjs.iter().enumerate() {
718        if !ac.is_temporal() {
719            if formula_mentions_changing_diff(ac) {
720                return None;
721            }
722        } else if let FormulaKind::Temporal(TemporalOp::Always, inner) = ac.kind() {
723            if !inner.is_temporal() {
724                continue;
725            }
726            if !is_one_step_diff(inner) {
727                return None;
728            }
729            let arms = extract_always_or_arms(ac)?;
730            if assumed_trans_idx.is_some() {
731                return None;
732            }
733            assumed_trans_idx = Some(idx);
734            assumed_arms = Some(arms);
735        } else {
736            return None;
737        }
738    }
739    let trans_idx = assumed_trans_idx?;
740    let assumed_arms = assumed_arms?;
741
742    let mut stutter_arm: Option<Formula> = None;
743    let mut assumed_only = Vec::new();
744    let mut dropped_count = 0usize;
745    for a in &assumed_arms {
746        let exact_in_target = target_arms.iter().any(|t| formula_alpha_eq(a, t, &[]));
747        if exact_in_target {
748            if is_pure_stutter_arm_diff(a, &all_rels) && stutter_arm.is_none() {
749                stutter_arm = Some(a.clone());
750            } else {
751                dropped_count += 1;
752            }
753        } else if target_arms.iter().any(|t| arm_syntactically_implies(a, t)) {
754            dropped_count += 1;
755        } else {
756            assumed_only.push(a.clone());
757        }
758    }
759    // Require a shared pure stutter arm on both sides and at least one dropped arm.
760    let stutter = stutter_arm?;
761    if dropped_count == 0 {
762        return None;
763    }
764
765    let eff_steps = if assumed_only.is_empty() {
766        1
767    } else {
768        requested_steps.clamp(1, 2)
769    };
770    let mut kept_arms = assumed_only;
771    kept_arms.push(stutter);
772    a_conjs[trans_idx] = Formula::or_all(kept_arms).always();
773    Some((Formula::and_all(a_conjs), eff_steps))
774}
775
776fn expr_mentions_changing_diff(e: &Expr) -> bool {
777    match e.kind() {
778        ExprKind::Relation(r) => r.is_changing(),
779        ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
780        ExprKind::Unary(_, a) | ExprKind::Prime(a) => expr_mentions_changing_diff(a),
781        ExprKind::Binary(_, a, b) => {
782            expr_mentions_changing_diff(a) || expr_mentions_changing_diff(b)
783        }
784        ExprKind::Comprehension(ds, body) => {
785            ds.iter().any(|d| expr_mentions_changing_diff(&d.expr))
786                || formula_mentions_changing_diff(body)
787        }
788        ExprKind::IfThenElse(c, a, b) => {
789            formula_mentions_changing_diff(c)
790                || expr_mentions_changing_diff(a)
791                || expr_mentions_changing_diff(b)
792        }
793        ExprKind::IntToSet(i) => int_mentions_changing_diff(i),
794    }
795}
796
797fn int_mentions_changing_diff(i: &IntExpr) -> bool {
798    match i.kind() {
799        IntExprKind::Constant(_) => false,
800        IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_mentions_changing_diff(e),
801        IntExprKind::Binary(_, a, b) => {
802            int_mentions_changing_diff(a) || int_mentions_changing_diff(b)
803        }
804        IntExprKind::Negate(a) => int_mentions_changing_diff(a),
805        IntExprKind::IfThenElse(c, a, b) => {
806            formula_mentions_changing_diff(c)
807                || int_mentions_changing_diff(a)
808                || int_mentions_changing_diff(b)
809        }
810        IntExprKind::SumOver(ds, body) => {
811            ds.iter().any(|d| expr_mentions_changing_diff(&d.expr))
812                || int_mentions_changing_diff(body)
813        }
814    }
815}
816
817fn formula_mentions_changing_diff(f: &Formula) -> bool {
818    match f.kind() {
819        FormulaKind::Constant(_) => false,
820        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
821            expr_mentions_changing_diff(a) || expr_mentions_changing_diff(b)
822        }
823        FormulaKind::Multiplicity(_, a) => expr_mentions_changing_diff(a),
824        FormulaKind::Not(g) | FormulaKind::Temporal(_, g) => formula_mentions_changing_diff(g),
825        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(formula_mentions_changing_diff),
826        FormulaKind::Implies(a, b)
827        | FormulaKind::Iff(a, b)
828        | FormulaKind::TemporalBinary(_, a, b) => {
829            formula_mentions_changing_diff(a) || formula_mentions_changing_diff(b)
830        }
831        FormulaKind::Quantified(_, ds, body) => {
832            ds.iter().any(|d| expr_mentions_changing_diff(&d.expr))
833                || formula_mentions_changing_diff(body)
834        }
835        FormulaKind::IntCompare(_, a, b) => {
836            int_mentions_changing_diff(a) || int_mentions_changing_diff(b)
837        }
838    }
839}
840
841/// Returns true when `f` contains no temporal operators (`always`, `eventually`,
842/// `after`, `until`, etc.) and at most single-prime expressions `e'` (no `e''`).
843fn is_one_step_diff(f: &Formula) -> bool {
844    fn expr_ok(e: &Expr, in_prime: bool) -> bool {
845        match e.kind() {
846            ExprKind::Relation(_)
847            | ExprKind::Variable(_)
848            | ExprKind::None
849            | ExprKind::Univ
850            | ExprKind::Iden => true,
851            ExprKind::Prime(a) => !in_prime && expr_ok(a, true),
852            ExprKind::Unary(_, a) => expr_ok(a, in_prime),
853            ExprKind::Binary(_, a, b) => expr_ok(a, in_prime) && expr_ok(b, in_prime),
854            ExprKind::Comprehension(ds, body) => {
855                ds.iter().all(|d| expr_ok(&d.expr, in_prime)) && form_ok(body, in_prime)
856            }
857            ExprKind::IfThenElse(c, a, b) => {
858                form_ok(c, in_prime) && expr_ok(a, in_prime) && expr_ok(b, in_prime)
859            }
860            ExprKind::IntToSet(i) => int_ok(i, in_prime),
861        }
862    }
863    fn int_ok(i: &IntExpr, in_prime: bool) -> bool {
864        match i.kind() {
865            IntExprKind::Constant(_) => true,
866            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_ok(e, in_prime),
867            IntExprKind::Binary(_, a, b) => int_ok(a, in_prime) && int_ok(b, in_prime),
868            IntExprKind::Negate(a) => int_ok(a, in_prime),
869            IntExprKind::IfThenElse(c, a, b) => {
870                form_ok(c, in_prime) && int_ok(a, in_prime) && int_ok(b, in_prime)
871            }
872            IntExprKind::SumOver(ds, body) => {
873                ds.iter().all(|d| expr_ok(&d.expr, in_prime)) && int_ok(body, in_prime)
874            }
875        }
876    }
877    fn form_ok(f: &Formula, in_prime: bool) -> bool {
878        match f.kind() {
879            FormulaKind::Constant(_) => true,
880            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
881                expr_ok(a, in_prime) && expr_ok(b, in_prime)
882            }
883            FormulaKind::Multiplicity(_, a) => expr_ok(a, in_prime),
884            FormulaKind::Not(g) => form_ok(g, in_prime),
885            FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(|g| form_ok(g, in_prime)),
886            FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
887                form_ok(a, in_prime) && form_ok(b, in_prime)
888            }
889            FormulaKind::Quantified(_, ds, body) => {
890                ds.iter().all(|d| expr_ok(&d.expr, in_prime)) && form_ok(body, in_prime)
891            }
892            FormulaKind::IntCompare(_, a, b) => int_ok(a, in_prime) && int_ok(b, in_prime),
893            FormulaKind::Temporal(_, _) | FormulaKind::TemporalBinary(_, _, _) => false,
894        }
895    }
896    form_ok(f, false)
897}
898
899fn is_pure_stutter_arm_diff(arm: &Formula, all_rels: &[Relation]) -> bool {
900    let mut conjs = Vec::new();
901    split_and_diff(arm, &mut conjs);
902    if conjs.is_empty() {
903        return false;
904    }
905    let mut framed = std::collections::BTreeSet::new();
906    for c in &conjs {
907        let FormulaKind::Equal(a, b) = c.kind() else {
908            return false;
909        };
910        let matched = match (a.kind(), b.kind()) {
911            (ExprKind::Prime(p), ExprKind::Relation(r))
912            | (ExprKind::Relation(r), ExprKind::Prime(p)) => {
913                matches!(p.kind(), ExprKind::Relation(r2) if r2 == r)
914            }
915            _ => false,
916        };
917        if !matched {
918            return false;
919        }
920        if let ExprKind::Relation(r) = b.kind() {
921            framed.insert(r.name().to_string());
922        } else if let ExprKind::Relation(r) = a.kind() {
923            framed.insert(r.name().to_string());
924        }
925    }
926    all_rels
927        .iter()
928        .filter(|r| r.is_changing())
929        .all(|r| framed.contains(r.name()))
930}
931
932/// Builds a logically equivalent assertion for checking `assumed => target`
933/// (with `target` rebound into `assumed`'s relations) that omits facts and
934/// untouched transition arms shared identically by both models, so
935/// `coi::try_check_coi` slices away untouched tables automatically (B23).
936fn diff_facts_assertion(
937    assumed: &Model,
938    target: &Model,
939    assumed_map: &BTreeMap<String, Relation>,
940    reduce: bool,
941) -> Formula {
942    let mut assumed_conjuncts = Vec::new();
943    split_and_diff(&assumed.all_facts(), &mut assumed_conjuncts);
944
945    // A `one` set is exact through the bounds, which differ between the two
946    // sides; say it as a fact so a side without it is compared against it.
947    let mut target_facts = vec![target.all_facts()];
948    target_facts.extend(target.one_set_facts());
949    let target_rebound = rebind_formula(&Formula::and_all(target_facts), assumed_map);
950    let mut target_conjuncts = Vec::new();
951    split_and_diff(&target_rebound, &mut target_conjuncts);
952
953    // Collect `always (arm_1 or ...)` transition conjuncts from `assumed`.
954    let assumed_transitions: Vec<Vec<Formula>> = assumed_conjuncts
955        .iter()
956        .filter_map(extract_always_or_arms)
957        .collect();
958
959    let mut diff_conjuncts = Vec::new();
960    for tc in target_conjuncts {
961        // Any conjunct already present identically in `assumed` is guaranteed true.
962        if assumed_conjuncts
963            .iter()
964            .any(|ac| formula_alpha_eq(ac, &tc, &[]))
965        {
966            continue;
967        }
968        if reduce
969            && let Some(target_arms) = extract_always_or_arms(&tc)
970            && let Some(reduced) = reduce_transition_diff(&assumed_transitions, &target_arms)
971        {
972            if !matches!(reduced.kind(), FormulaKind::Constant(true)) {
973                diff_conjuncts.push(reduced);
974            }
975            continue;
976        }
977        diff_conjuncts.push(tc);
978    }
979
980    if diff_conjuncts.is_empty() {
981        Formula::truth()
982    } else {
983        Formula::and_all(diff_conjuncts)
984    }
985}
986
987fn split_and_diff(f: &Formula, out: &mut Vec<Formula>) {
988    match f.kind() {
989        FormulaKind::And(fs) => {
990            for sub in fs {
991                split_and_diff(sub, out);
992            }
993        }
994        FormulaKind::Constant(true) => {}
995        _ => out.push(f.clone()),
996    }
997}
998
999fn split_or_diff(f: &Formula, out: &mut Vec<Formula>) {
1000    match f.kind() {
1001        FormulaKind::Or(fs) => {
1002            for sub in fs {
1003                split_or_diff(sub, out);
1004            }
1005        }
1006        _ => out.push(f.clone()),
1007    }
1008}
1009
1010fn extract_always_or_arms(f: &Formula) -> Option<Vec<Formula>> {
1011    let FormulaKind::Temporal(TemporalOp::Always, body) = f.kind() else {
1012        return None;
1013    };
1014    let mut arms = Vec::new();
1015    split_or_diff(body, &mut arms);
1016    if arms.len() >= 2 { Some(arms) } else { None }
1017}
1018
1019/// Reduces `always (assumed_arms) => always (target_arms)` using pure
1020/// propositional frame stripping (B23):
1021/// - If `assumed_only` is empty, `assumed => target` is tautologically true.
1022/// - Otherwise, let `s` be a closed conjunctive arm shared by both sides (such
1023///   as `nothing`), `C` the conjuncts of `s` implied by every arm in
1024///   `assumed_only`, and `L = s \ C`. Any shared arm implying `L` is dropped,
1025///   and `C` is stripped from all remaining arms so only changed tables and
1026///   their dependencies remain in the assertion.
1027fn reduce_transition_diff(
1028    assumed_transitions: &[Vec<Formula>],
1029    target_arms: &[Formula],
1030) -> Option<Formula> {
1031    // Pick the assumed transition sharing the most arms with `target_arms`.
1032    let assumed_arms = assumed_transitions.iter().max_by_key(|a_arms| {
1033        a_arms
1034            .iter()
1035            .filter(|a| target_arms.iter().any(|t| formula_alpha_eq(a, t, &[])))
1036            .count()
1037    })?;
1038
1039    let mut shared = Vec::new();
1040    let mut assumed_only = Vec::new();
1041    for a in assumed_arms {
1042        if target_arms.iter().any(|t| formula_alpha_eq(a, t, &[])) {
1043            shared.push(a.clone());
1044        } else if target_arms.iter().any(|t| arm_syntactically_implies(a, t)) {
1045            // `a` syntactically implies an arm of `target_arms` (e.g. a tightened
1046            // trigger with extra guard conjuncts), so `a` can never violate `target`.
1047        } else {
1048            assumed_only.push(a.clone());
1049        }
1050    }
1051    if assumed_only.is_empty() {
1052        return Some(Formula::truth());
1053    }
1054    let target_only: Vec<Formula> = target_arms
1055        .iter()
1056        .filter(|t| !assumed_arms.iter().any(|a| formula_alpha_eq(a, t, &[])))
1057        .cloned()
1058        .collect();
1059
1060    let assumed_only_closed: Vec<Vec<Formula>> =
1061        assumed_only.iter().map(arm_closed_conjuncts).collect();
1062
1063    // Find a shared closed conjunctive arm (typically `nothing` / stutter) that
1064    // shares the most closed conjuncts with every arm in `assumed_only`.
1065    let mut best_stutter: Option<(usize, Vec<Formula>, Vec<Formula>)> = None;
1066    for (idx, s) in shared.iter().enumerate() {
1067        if matches!(s.kind(), FormulaKind::Quantified(Quantifier::Some, _, _)) {
1068            continue;
1069        }
1070        let mut s_conjs = Vec::new();
1071        split_and_diff(s, &mut s_conjs);
1072        if s_conjs.is_empty() || s_conjs.iter().any(formula_has_free_vars) {
1073            continue;
1074        }
1075        let mut common = Vec::new();
1076        let mut local = Vec::new();
1077        for c in s_conjs {
1078            let in_all = assumed_only_closed
1079                .iter()
1080                .all(|ac| ac.iter().any(|x| formula_alpha_eq(x, &c, &[])));
1081            if in_all {
1082                common.push(c);
1083            } else {
1084                local.push(c);
1085            }
1086        }
1087        if common.is_empty() {
1088            continue;
1089        }
1090        let better = match &best_stutter {
1091            None => true,
1092            Some((_, prev_common, _)) => common.len() > prev_common.len(),
1093        };
1094        if better {
1095            best_stutter = Some((idx, common, local));
1096        }
1097    }
1098
1099    let (stutter_idx, common, local) = best_stutter?;
1100    if local.is_empty() {
1101        // Every conjunct of the shared arm `s` is already implied by every
1102        // `assumed_only` arm, so `assumed => target` is tautologically true.
1103        return Some(Formula::truth());
1104    }
1105
1106    let mut reduced_arms = Vec::new();
1107    reduced_arms.push(Formula::and_all(local.clone()));
1108
1109    for (idx, s) in shared.iter().enumerate() {
1110        if idx == stutter_idx {
1111            continue;
1112        }
1113        let s_closed = arm_closed_conjuncts(s);
1114        let implies_local = local
1115            .iter()
1116            .all(|l| s_closed.iter().any(|c| formula_alpha_eq(c, l, &[])));
1117        if implies_local {
1118            // `s => local`, so `local` already covers every transition matching `s`.
1119            continue;
1120        }
1121        reduced_arms.push(strip_closed_conjuncts(s, &common));
1122    }
1123
1124    for b in &target_only {
1125        reduced_arms.push(strip_closed_conjuncts(b, &common));
1126    }
1127
1128    Some(Formula::or_all(reduced_arms).always())
1129}
1130
1131fn arm_closed_conjuncts(arm: &Formula) -> Vec<Formula> {
1132    fn visit(f: &Formula, bound: &mut Vec<Variable>, out: &mut Vec<Formula>) {
1133        match f.kind() {
1134            FormulaKind::And(fs) => {
1135                for sub in fs {
1136                    visit(sub, bound, out);
1137                }
1138            }
1139            FormulaKind::Quantified(Quantifier::Some, decls, body) => {
1140                let saved = bound.len();
1141                for d in decls {
1142                    bound.push(d.var.clone());
1143                }
1144                visit(body, bound, out);
1145                bound.truncate(saved);
1146            }
1147            FormulaKind::Constant(true) => {}
1148            _ => {
1149                if !formula_uses_any_var(f, bound) {
1150                    out.push(f.clone());
1151                }
1152            }
1153        }
1154    }
1155    let mut out = Vec::new();
1156    let mut bound = Vec::new();
1157    visit(arm, &mut bound, &mut out);
1158    out
1159}
1160
1161fn strip_closed_conjuncts(arm: &Formula, to_strip: &[Formula]) -> Formula {
1162    fn visit(f: &Formula, bound: &mut Vec<Variable>, to_strip: &[Formula]) -> Formula {
1163        match f.kind() {
1164            FormulaKind::And(fs) => {
1165                let kept: Vec<Formula> = fs
1166                    .iter()
1167                    .map(|sub| visit(sub, bound, to_strip))
1168                    .filter(|g| !matches!(g.kind(), FormulaKind::Constant(true)))
1169                    .collect();
1170                if kept.is_empty() {
1171                    Formula::truth()
1172                } else {
1173                    Formula::and_all(kept)
1174                }
1175            }
1176            FormulaKind::Quantified(Quantifier::Some, decls, body) => {
1177                let saved = bound.len();
1178                for d in decls {
1179                    bound.push(d.var.clone());
1180                }
1181                let new_body = visit(body, bound, to_strip);
1182                bound.truncate(saved);
1183                Formula::quantified(Quantifier::Some, decls.clone(), &new_body)
1184            }
1185            _ => {
1186                if !formula_uses_any_var(f, bound)
1187                    && to_strip.iter().any(|s| formula_alpha_eq(f, s, &[]))
1188                {
1189                    Formula::truth()
1190                } else {
1191                    f.clone()
1192                }
1193            }
1194        }
1195    }
1196    let mut bound = Vec::new();
1197    visit(arm, &mut bound, to_strip)
1198}
1199
1200fn formula_has_free_vars(f: &Formula) -> bool {
1201    fn visit_f(f: &Formula, bound: &mut Vec<Variable>) -> bool {
1202        match f.kind() {
1203            FormulaKind::Constant(_) => false,
1204            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
1205                visit_e(a, bound) || visit_e(b, bound)
1206            }
1207            FormulaKind::Multiplicity(_, e) => visit_e(e, bound),
1208            FormulaKind::Not(a) | FormulaKind::Temporal(_, a) => visit_f(a, bound),
1209            FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(|g| visit_f(g, bound)),
1210            FormulaKind::Implies(a, b)
1211            | FormulaKind::Iff(a, b)
1212            | FormulaKind::TemporalBinary(_, a, b) => visit_f(a, bound) || visit_f(b, bound),
1213            FormulaKind::Quantified(_, decls, body) => {
1214                let saved = bound.len();
1215                for d in decls {
1216                    if visit_e(&d.expr, bound) {
1217                        bound.truncate(saved);
1218                        return true;
1219                    }
1220                    bound.push(d.var.clone());
1221                }
1222                let res = visit_f(body, bound);
1223                bound.truncate(saved);
1224                res
1225            }
1226            FormulaKind::IntCompare(_, a, b) => visit_i(a, bound) || visit_i(b, bound),
1227        }
1228    }
1229    fn visit_e(e: &Expr, bound: &mut Vec<Variable>) -> bool {
1230        match e.kind() {
1231            ExprKind::Relation(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
1232            ExprKind::Variable(v) => !bound.contains(v),
1233            ExprKind::Unary(_, a) | ExprKind::Prime(a) => visit_e(a, bound),
1234            ExprKind::Binary(_, a, b) => visit_e(a, bound) || visit_e(b, bound),
1235            ExprKind::Comprehension(decls, body) => {
1236                let saved = bound.len();
1237                for d in decls {
1238                    if visit_e(&d.expr, bound) {
1239                        bound.truncate(saved);
1240                        return true;
1241                    }
1242                    bound.push(d.var.clone());
1243                }
1244                let res = visit_f(body, bound);
1245                bound.truncate(saved);
1246                res
1247            }
1248            ExprKind::IfThenElse(c, a, b) => {
1249                visit_f(c, bound) || visit_e(a, bound) || visit_e(b, bound)
1250            }
1251            ExprKind::IntToSet(i) => visit_i(i, bound),
1252        }
1253    }
1254    fn visit_i(i: &IntExpr, bound: &mut Vec<Variable>) -> bool {
1255        match i.kind() {
1256            IntExprKind::Constant(_) => false,
1257            IntExprKind::Count(e) | IntExprKind::Sum(e) => visit_e(e, bound),
1258            IntExprKind::Binary(_, a, b) => visit_i(a, bound) || visit_i(b, bound),
1259            IntExprKind::Negate(a) => visit_i(a, bound),
1260            IntExprKind::IfThenElse(c, a, b) => {
1261                visit_f(c, bound) || visit_i(a, bound) || visit_i(b, bound)
1262            }
1263            IntExprKind::SumOver(decls, body) => {
1264                let saved = bound.len();
1265                for d in decls {
1266                    if visit_e(&d.expr, bound) {
1267                        bound.truncate(saved);
1268                        return true;
1269                    }
1270                    bound.push(d.var.clone());
1271                }
1272                let res = visit_i(body, bound);
1273                bound.truncate(saved);
1274                res
1275            }
1276        }
1277    }
1278    visit_f(f, &mut Vec::new())
1279}
1280
1281fn formula_uses_any_var(f: &Formula, vars: &[Variable]) -> bool {
1282    if vars.is_empty() {
1283        return false;
1284    }
1285    fn visit_f(f: &Formula, vars: &[Variable]) -> bool {
1286        match f.kind() {
1287            FormulaKind::Constant(_) => false,
1288            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
1289                visit_e(a, vars) || visit_e(b, vars)
1290            }
1291            FormulaKind::Multiplicity(_, e) => visit_e(e, vars),
1292            FormulaKind::Not(a) | FormulaKind::Temporal(_, a) => visit_f(a, vars),
1293            FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(|g| visit_f(g, vars)),
1294            FormulaKind::Implies(a, b)
1295            | FormulaKind::Iff(a, b)
1296            | FormulaKind::TemporalBinary(_, a, b) => visit_f(a, vars) || visit_f(b, vars),
1297            FormulaKind::Quantified(_, decls, body) => {
1298                decls.iter().any(|d| visit_e(&d.expr, vars)) || visit_f(body, vars)
1299            }
1300            FormulaKind::IntCompare(_, a, b) => visit_i(a, vars) || visit_i(b, vars),
1301        }
1302    }
1303    fn visit_e(e: &Expr, vars: &[Variable]) -> bool {
1304        match e.kind() {
1305            ExprKind::Relation(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
1306            ExprKind::Variable(v) => vars.contains(v),
1307            ExprKind::Unary(_, a) | ExprKind::Prime(a) => visit_e(a, vars),
1308            ExprKind::Binary(_, a, b) => visit_e(a, vars) || visit_e(b, vars),
1309            ExprKind::Comprehension(decls, body) => {
1310                decls.iter().any(|d| visit_e(&d.expr, vars)) || visit_f(body, vars)
1311            }
1312            ExprKind::IfThenElse(c, a, b) => {
1313                visit_f(c, vars) || visit_e(a, vars) || visit_e(b, vars)
1314            }
1315            ExprKind::IntToSet(i) => visit_i(i, vars),
1316        }
1317    }
1318    fn visit_i(i: &IntExpr, vars: &[Variable]) -> bool {
1319        match i.kind() {
1320            IntExprKind::Constant(_) => false,
1321            IntExprKind::Count(e) | IntExprKind::Sum(e) => visit_e(e, vars),
1322            IntExprKind::Binary(_, a, b) => visit_i(a, vars) || visit_i(b, vars),
1323            IntExprKind::Negate(a) => visit_i(a, vars),
1324            IntExprKind::IfThenElse(c, a, b) => {
1325                visit_f(c, vars) || visit_i(a, vars) || visit_i(b, vars)
1326            }
1327            IntExprKind::SumOver(decls, body) => {
1328                decls.iter().any(|d| visit_e(&d.expr, vars)) || visit_i(body, vars)
1329            }
1330        }
1331    }
1332    visit_f(f, vars)
1333}
1334
1335/// Returns true when transition arm `a` syntactically implies arm `t`
1336/// (e.g. `some r: T | G1 and G2` implies `some r: T | G1`, W25).
1337fn arm_syntactically_implies(a: &Formula, t: &Formula) -> bool {
1338    if formula_alpha_eq(a, t, &[]) {
1339        return true;
1340    }
1341    match (a.kind(), t.kind()) {
1342        (
1343            FormulaKind::Quantified(Quantifier::Some, da, ba),
1344            FormulaKind::Quantified(Quantifier::Some, dt, bt),
1345        ) if da.len() == dt.len() => {
1346            let mut env = Vec::with_capacity(da.len());
1347            for (xa, xt) in da.iter().zip(dt.iter()) {
1348                if xa.mult != xt.mult || !expr_alpha_eq(&xa.expr, &xt.expr, &env) {
1349                    return false;
1350                }
1351                env.push((xa.var.clone(), xt.var.clone()));
1352            }
1353            let mut a_conjs = Vec::new();
1354            let mut t_conjs = Vec::new();
1355            split_and_diff(ba, &mut a_conjs);
1356            split_and_diff(bt, &mut t_conjs);
1357            t_conjs
1358                .iter()
1359                .all(|tc| a_conjs.iter().any(|ac| formula_alpha_eq(ac, tc, &env)))
1360        }
1361        _ => {
1362            let mut a_conjs = Vec::new();
1363            let mut t_conjs = Vec::new();
1364            split_and_diff(a, &mut a_conjs);
1365            split_and_diff(t, &mut t_conjs);
1366            !t_conjs.is_empty()
1367                && t_conjs
1368                    .iter()
1369                    .all(|tc| a_conjs.iter().any(|ac| formula_alpha_eq(ac, tc, &[])))
1370        }
1371    }
1372}
1373
1374fn formula_alpha_eq(a: &Formula, b: &Formula, env: &[(Variable, Variable)]) -> bool {
1375    match (a.kind(), b.kind()) {
1376        (FormulaKind::Constant(x), FormulaKind::Constant(y)) => x == y,
1377        (FormulaKind::Subset(a1, a2), FormulaKind::Subset(b1, b2))
1378        | (FormulaKind::Equal(a1, a2), FormulaKind::Equal(b1, b2)) => {
1379            expr_alpha_eq(a1, b1, env) && expr_alpha_eq(a2, b2, env)
1380        }
1381        (FormulaKind::Multiplicity(m1, e1), FormulaKind::Multiplicity(m2, e2)) => {
1382            m1 == m2 && expr_alpha_eq(e1, e2, env)
1383        }
1384        (FormulaKind::Not(f1), FormulaKind::Not(f2)) => formula_alpha_eq(f1, f2, env),
1385        (FormulaKind::And(fs1), FormulaKind::And(fs2))
1386        | (FormulaKind::Or(fs1), FormulaKind::Or(fs2)) => {
1387            fs1.len() == fs2.len()
1388                && fs1
1389                    .iter()
1390                    .zip(fs2.iter())
1391                    .all(|(x, y)| formula_alpha_eq(x, y, env))
1392        }
1393        (FormulaKind::Implies(a1, a2), FormulaKind::Implies(b1, b2))
1394        | (FormulaKind::Iff(a1, a2), FormulaKind::Iff(b1, b2)) => {
1395            formula_alpha_eq(a1, b1, env) && formula_alpha_eq(a2, b2, env)
1396        }
1397        (FormulaKind::Quantified(q1, d1, b1), FormulaKind::Quantified(q2, d2, b2)) => {
1398            if q1 != q2 || d1.len() != d2.len() {
1399                return false;
1400            }
1401            let mut next_env = env.to_vec();
1402            for (x, y) in d1.iter().zip(d2.iter()) {
1403                if x.mult != y.mult || !expr_alpha_eq(&x.expr, &y.expr, &next_env) {
1404                    return false;
1405                }
1406                next_env.push((x.var.clone(), y.var.clone()));
1407            }
1408            formula_alpha_eq(b1, b2, &next_env)
1409        }
1410        (FormulaKind::Temporal(op1, f1), FormulaKind::Temporal(op2, f2)) => {
1411            op1 == op2 && formula_alpha_eq(f1, f2, env)
1412        }
1413        (FormulaKind::TemporalBinary(op1, a1, a2), FormulaKind::TemporalBinary(op2, b1, b2)) => {
1414            op1 == op2 && formula_alpha_eq(a1, b1, env) && formula_alpha_eq(a2, b2, env)
1415        }
1416        (FormulaKind::IntCompare(op1, a1, a2), FormulaKind::IntCompare(op2, b1, b2)) => {
1417            op1 == op2 && int_alpha_eq(a1, b1, env) && int_alpha_eq(a2, b2, env)
1418        }
1419        _ => false,
1420    }
1421}
1422
1423fn expr_alpha_eq(a: &Expr, b: &Expr, env: &[(Variable, Variable)]) -> bool {
1424    match (a.kind(), b.kind()) {
1425        (ExprKind::Relation(r1), ExprKind::Relation(r2)) => r1 == r2,
1426        (ExprKind::Variable(v1), ExprKind::Variable(v2)) => {
1427            for (x, y) in env.iter().rev() {
1428                if x == v1 || y == v2 {
1429                    return x == v1 && y == v2;
1430                }
1431            }
1432            v1 == v2
1433        }
1434        (ExprKind::None, ExprKind::None)
1435        | (ExprKind::Univ, ExprKind::Univ)
1436        | (ExprKind::Iden, ExprKind::Iden) => true,
1437        (ExprKind::Unary(op1, e1), ExprKind::Unary(op2, e2)) => {
1438            op1 == op2 && expr_alpha_eq(e1, e2, env)
1439        }
1440        (ExprKind::Binary(op1, a1, a2), ExprKind::Binary(op2, b1, b2)) => {
1441            op1 == op2 && expr_alpha_eq(a1, b1, env) && expr_alpha_eq(a2, b2, env)
1442        }
1443        (ExprKind::Prime(e1), ExprKind::Prime(e2)) => expr_alpha_eq(e1, e2, env),
1444        (ExprKind::Comprehension(d1, b1), ExprKind::Comprehension(d2, b2)) => {
1445            if d1.len() != d2.len() {
1446                return false;
1447            }
1448            let mut next_env = env.to_vec();
1449            for (x, y) in d1.iter().zip(d2.iter()) {
1450                if x.mult != y.mult || !expr_alpha_eq(&x.expr, &y.expr, &next_env) {
1451                    return false;
1452                }
1453                next_env.push((x.var.clone(), y.var.clone()));
1454            }
1455            formula_alpha_eq(b1, b2, &next_env)
1456        }
1457        (ExprKind::IfThenElse(c1, t1, e1), ExprKind::IfThenElse(c2, t2, e2)) => {
1458            formula_alpha_eq(c1, c2, env)
1459                && expr_alpha_eq(t1, t2, env)
1460                && expr_alpha_eq(e1, e2, env)
1461        }
1462        (ExprKind::IntToSet(i1), ExprKind::IntToSet(i2)) => int_alpha_eq(i1, i2, env),
1463        _ => false,
1464    }
1465}
1466
1467fn int_alpha_eq(a: &IntExpr, b: &IntExpr, env: &[(Variable, Variable)]) -> bool {
1468    match (a.kind(), b.kind()) {
1469        (IntExprKind::Constant(x), IntExprKind::Constant(y)) => x == y,
1470        (IntExprKind::Count(e1), IntExprKind::Count(e2))
1471        | (IntExprKind::Sum(e1), IntExprKind::Sum(e2)) => expr_alpha_eq(e1, e2, env),
1472        (IntExprKind::Binary(op1, a1, a2), IntExprKind::Binary(op2, b1, b2)) => {
1473            op1 == op2 && int_alpha_eq(a1, b1, env) && int_alpha_eq(a2, b2, env)
1474        }
1475        (IntExprKind::Negate(i1), IntExprKind::Negate(i2)) => int_alpha_eq(i1, i2, env),
1476        (IntExprKind::IfThenElse(c1, t1, e1), IntExprKind::IfThenElse(c2, t2, e2)) => {
1477            formula_alpha_eq(c1, c2, env) && int_alpha_eq(t1, t2, env) && int_alpha_eq(e1, e2, env)
1478        }
1479        (IntExprKind::SumOver(d1, b1), IntExprKind::SumOver(d2, b2)) => {
1480            if d1.len() != d2.len() {
1481                return false;
1482            }
1483            let mut next_env = env.to_vec();
1484            for (x, y) in d1.iter().zip(d2.iter()) {
1485                if x.mult != y.mult || !expr_alpha_eq(&x.expr, &y.expr, &next_env) {
1486                    return false;
1487                }
1488                next_env.push((x.var.clone(), y.var.clone()));
1489            }
1490            int_alpha_eq(b1, b2, &next_env)
1491        }
1492        _ => false,
1493    }
1494}