Skip to main content

elinvar_engine/
model.rs

1//! The model builder (LOGIC.md section 12.9, R11): sets with a scope,
2//! subsets, relations and fields, facts, and commands.
3
4use crate::skolem::substitute_formula;
5use crate::solve::{HoldsCore, Options, Outcome, StepLabel, check_with_solver, run_with_solver};
6use elinvar_logic::{
7    Bounds, Code, Decl, Error, Expr, ExprKind, Formula, Multiplicity, Place, Relation, Trace,
8    TupleSet, Universe, Variable, evaluate_trace_at, evaluate_trace_expr_at,
9};
10use std::collections::BTreeMap;
11
12/// The engine's own error codes, beside those of the logic.
13pub const MODEL_CODES: &[Code] = &[
14    Code::new(
15        "model.bitwidth",
16        "a command asks for a bitwidth above 16 in a model with integers, whose `Int` set would have 2^w atoms",
17        "give the command a bitwidth from 1 to 16 with `bitwidth`",
18    ),
19    Code::new(
20        "model.no_scope",
21        "a command leaves a top-level set without a scope",
22        "give the set a scope with `scope`, `scope_of`, or `exactly`",
23    ),
24    Code::new(
25        "model.not_a_set",
26        "a scope is given for something that is not a top-level set of the model, or an ordering for a set that changes over time",
27        "give scopes only to the model's top-level sets",
28    ),
29    Code::new(
30        "model.not_changing",
31        "an action's effect names something that is not a changing relation of the model",
32        "name a relation declared with `changing_field`, `changing_relation`, or `changing_subset`",
33    ),
34    Code::new(
35        "model.changing_after_action",
36        "a changing relation is declared after an action, so that action's frame misses it",
37        "declare every changing relation before the first action",
38    ),
39    Code::new(
40        "model.diff_mismatch",
41        "two models being compared with `diff` do not declare the same signatures and fields with the same arities and mutability",
42        "compare models that share the same signatures, fields, arities, and `var` declarations",
43    ),
44    Code::new(
45        "model.trivial_holds",
46        "a `check` assertion holds from the bounds alone without using any rule of the model",
47        "check whether the promise is a tautology or restates a definition rather than testing a rule",
48    ),
49    Code::new(
50        "model.vacuous_premise",
51        "an implication promise's premise is never satisfied in any allowed case within the scope",
52        "increase the scope or steps, or inspect why the premise can never happen",
53    ),
54    Code::new(
55        "model.premise_unknown",
56        "warning: a `check` of an implication holds, but whether its premise is ever satisfied was not settled within the budget for that question, so the `holds` may be vacuous",
57        "raise `--budget` or `--timeout`, or lower the scope, and check again; or `run` the premise to see a case of it",
58    ),
59    Code::new(
60        "model.invalid_steps",
61        "a command asks for 0 steps; a trace needs at least 1 state",
62        "use at least 1 step (`but 1 steps` or `--steps 1`)",
63    ),
64    Code::new(
65        "model.scope_too_large",
66        "a command asks for more atoms, or more possible tuples, than the bounded checker supports",
67        "lower the command's scope (at most 4096 non-integer atoms, and 16777216 possible tuples over all relations)",
68    ),
69];
70
71pub(crate) fn model_error(code: &'static str, message: String) -> Error {
72    let fix = MODEL_CODES
73        .iter()
74        .find(|c| c.code == code)
75        .map(|c| c.fix)
76        .expect("every model error code is listed in MODEL_CODES");
77    Error::with_fix(code, message, fix)
78}
79
80#[derive(Clone, Debug, PartialEq, Eq)]
81enum SetKind {
82    Top,
83    One,
84    Sub { parent: usize, extends: bool },
85}
86
87#[derive(Clone, Debug)]
88struct SetDecl {
89    relation: Relation,
90    kind: SetKind,
91    is_abstract: bool,
92    /// A subset declared to hold exactly one atom.
93    one: bool,
94    /// The set of integer atoms, `Int` (LOGIC.md 16.1): exactly the
95    /// integers of the command's bitwidth.
96    ints: bool,
97    /// Where the set was declared, when known (such as model text).
98    place: Option<Place>,
99}
100
101/// What an ordering orders: a set, or a subset of a union of sets, which
102/// is a relation of one column over several (LOGIC.md 12.9).
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104enum Ordered {
105    Set(usize),
106    Union(usize),
107}
108
109#[derive(Clone, Debug)]
110struct RelationDecl {
111    relation: Relation,
112    /// Each column, as the union of the sets it ranges over.
113    columns: Vec<Vec<usize>>,
114    multiplicity: Option<Multiplicity>,
115    /// Where the relation was declared, when known (such as model text).
116    place: Option<Place>,
117}
118
119/// A named step with parameters (LOGIC.md 13.5).
120#[derive(Clone, Debug)]
121pub struct Action {
122    name: String,
123    vars: Vec<Variable>,
124    ranges: Vec<Expr>,
125    formula: Formula,
126}
127
128impl Action {
129    /// The action's name.
130    pub fn name(&self) -> &str {
131        &self.name
132    }
133
134    /// That the action happens now with these arguments: its guard, its
135    /// effects, and its frame.
136    pub fn happens(&self, args: &[&Expr]) -> Formula {
137        let map: Vec<(Variable, Expr)> = self
138            .vars
139            .iter()
140            .cloned()
141            .zip(args.iter().map(|&a| a.clone()))
142            .collect();
143        substitute_formula(&self.formula, &map, &mut BTreeMap::new())
144    }
145
146    /// That the action happens now with some arguments.
147    fn happens_somehow(&self) -> Formula {
148        if self.vars.is_empty() {
149            return self.formula.clone();
150        }
151        let decls = self
152            .vars
153            .iter()
154            .zip(&self.ranges)
155            .map(|(v, r)| Decl::new(v, r))
156            .collect();
157        Formula::some(decls, &self.formula)
158    }
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162enum Effect {
163    Add,
164    Remove,
165    Set,
166}
167
168/// What an action does: its guard and its effects (LOGIC.md 13.5).
169#[derive(Debug, Default)]
170pub struct Step {
171    guards: Vec<Formula>,
172    effects: Vec<(Expr, Effect, Expr)>,
173}
174
175impl Step {
176    /// The action can happen only when `f` holds.
177    pub fn when(&mut self, f: Formula) {
178        self.guards.push(f);
179    }
180
181    /// `r' = r + e`, combined with the action's other effects on `r` in
182    /// the order written.
183    pub fn add(&mut self, r: &Expr, e: Expr) {
184        self.effects.push((r.clone(), Effect::Add, e));
185    }
186
187    /// `r' = r - e`
188    pub fn remove(&mut self, r: &Expr, e: Expr) {
189        self.effects.push((r.clone(), Effect::Remove, e));
190    }
191
192    /// `r' = e`
193    pub fn set(&mut self, r: &Expr, e: Expr) {
194        self.effects.push((r.clone(), Effect::Set, e));
195    }
196}
197
198/// One guard condition inside a step predicate (N11, N14).
199#[derive(Clone, Debug)]
200#[non_exhaustive]
201pub struct StepGuard {
202    /// Source-level condition label (or trigger name for SQL imports).
203    pub label: String,
204    /// Guard formula over the step's parameters.
205    pub formula: Formula,
206}
207
208impl StepGuard {
209    /// Creates a guard with its display label and formula.
210    #[must_use]
211    pub fn new(label: impl Into<String>, formula: Formula) -> StepGuard {
212        StepGuard {
213            label: label.into(),
214            formula,
215        }
216    }
217}
218
219/// Structured decomposition of one step arm in a transition fact (N11, N14, W14).
220#[derive(Clone, Debug)]
221#[non_exhaustive]
222pub struct StepSpec {
223    /// Step predicate name (for example `release` or `insert_orders`).
224    pub name: String,
225    /// Quantified parameter variables (`some r: T_row | ...`).
226    pub vars: Vec<Variable>,
227    /// Parameter domains matching `vars`.
228    pub ranges: Vec<Expr>,
229    /// Individual guard conjuncts.
230    pub guards: Vec<StepGuard>,
231    /// Remaining effect and frame conjuncts.
232    pub effect: Formula,
233    /// Label of the transition fact this step belongs to (for example `fact Steps`).
234    pub fact_name: String,
235}
236
237impl StepSpec {
238    /// Builds a structured step specification.
239    #[must_use]
240    pub fn new(
241        name: impl Into<String>,
242        vars: Vec<Variable>,
243        ranges: Vec<Expr>,
244        guards: Vec<StepGuard>,
245        effect: Formula,
246        fact_name: impl Into<String>,
247    ) -> StepSpec {
248        StepSpec {
249            name: name.into(),
250            vars,
251            ranges,
252            guards,
253            effect,
254            fact_name: fact_name.into(),
255        }
256    }
257
258    /// Quantifies `body` existentially over this step's parameters (`some v: r | body`).
259    #[must_use]
260    pub fn quantify(&self, body: Formula) -> Formula {
261        if self.vars.is_empty() {
262            body
263        } else {
264            let decls: Vec<Decl> = self
265                .vars
266                .iter()
267                .zip(&self.ranges)
268                .map(|(v, r)| Decl::new(v, r))
269                .collect();
270            Formula::some(decls, &body)
271        }
272    }
273
274    /// Rebuilds the step arm with only the guards marked active.
275    #[must_use]
276    pub fn with_active_guards(&self, active: &[bool]) -> Formula {
277        let mut parts = Vec::with_capacity(self.guards.len() + 1);
278        for (g, &keep) in self.guards.iter().zip(active) {
279            if keep {
280                parts.push(g.formula.clone());
281            }
282        }
283        parts.push(self.effect.clone());
284        self.quantify(Formula::and_all(parts))
285    }
286
287    /// Full step arm (`some v: r | all_guards and effect`).
288    #[must_use]
289    pub fn full_arm(&self) -> Formula {
290        let active = vec![true; self.guards.len()];
291        self.with_active_guards(&active)
292    }
293}
294
295/// A model: sets, relations, actions, and facts.
296#[derive(Clone, Debug, Default)]
297pub struct Model {
298    sets: Vec<SetDecl>,
299    relations: Vec<RelationDecl>,
300    facts: Vec<(String, Formula)>,
301    actions: Vec<Action>,
302    /// Named step predicates registered solely for labelling trace steps (for
303    /// example from Alloy text's `always (a[...] or b[...] or nothing)`),
304    /// without adding any transition fact.
305    step_labels: Vec<Action>,
306    /// Structured step decompositions for fine-grained cores (N14), model-based
307    /// test generation (N11), and model diagrams (W14).
308    step_specs: Vec<StepSpec>,
309    /// Unmodified/stutter arms per transition fact name (such as `nothing`),
310    /// preserved when rebuilding a transition fact during guard refinement.
311    transition_extras: BTreeMap<String, Vec<Formula>>,
312    /// Orderings: the set, its `first` and `next`, and whether it is an enum
313    /// ordering whose `one` extensions follow declaration order (LOGIC.md 12.9, B27).
314    orderings: Vec<(Ordered, Relation, Relation, bool)>,
315    errors: Vec<Error>,
316}
317
318/// An ordering of a set's atoms (LOGIC.md 12.9): `first` and `next`.
319#[derive(Clone, Debug)]
320pub struct Ordering {
321    /// The set.
322    pub set: Expr,
323    /// Its first atom.
324    pub first: Expr,
325    /// Each atom to the one after it.
326    pub next: Expr,
327}
328
329impl Model {
330    /// An empty model.
331    pub fn new() -> Model {
332        Model::default()
333    }
334
335    fn add_set(&mut self, name: &str, kind: SetKind, is_abstract: bool) -> Expr {
336        self.add_set_changing(name, kind, is_abstract, false)
337    }
338
339    fn note_changing(&mut self, name: &str) {
340        if !self.actions.is_empty() {
341            self.errors.push(model_error(
342                "model.changing_after_action",
343                format!("`{name}` is declared after an action"),
344            ));
345        }
346    }
347
348    fn add_set_changing(
349        &mut self,
350        name: &str,
351        kind: SetKind,
352        is_abstract: bool,
353        changing: bool,
354    ) -> Expr {
355        let relation = if changing {
356            self.note_changing(name);
357            Relation::changing(name, 1)
358        } else {
359            Relation::unary(name)
360        };
361        let e = Expr::relation(&relation);
362        self.sets.push(SetDecl {
363            relation,
364            kind,
365            is_abstract,
366            one: false,
367            ints: false,
368            place: None,
369        });
370        e
371    }
372
373    fn index_of(&self, e: &Expr) -> Option<usize> {
374        match e.kind() {
375            ExprKind::Relation(r) => self.sets.iter().position(|s| &s.relation == r),
376            _ => None,
377        }
378    }
379
380    /// A top-level set: its own atoms, as many as the command's scope.
381    pub fn set(&mut self, name: &str) -> Expr {
382        self.add_set(name, SetKind::Top, false)
383    }
384
385    /// A top-level set whose members may change from state to state; its
386    /// atoms are fixed by the scope as any top-level set's are.
387    pub fn changing_set(&mut self, name: &str) -> Expr {
388        self.add_set_changing(name, SetKind::Top, false, true)
389    }
390
391    /// `Int`, the top-level set of integer atoms: in each command, exactly
392    /// one atom for each integer of its bitwidth, named by the integer, from
393    /// the least (LOGIC.md 12.9 and 16.1). The same set every time it is
394    /// asked for.
395    pub fn ints(&mut self) -> Expr {
396        if let Some(s) = self.sets.iter().find(|s| s.ints) {
397            return Expr::relation(&s.relation);
398        }
399        let e = self.add_set("Int", SetKind::Top, false);
400        if let Some(s) = self.sets.last_mut() {
401            s.ints = true;
402        }
403        e
404    }
405
406    /// A top-level set that is the union of the sets that extend it.
407    pub fn abstract_set(&mut self, name: &str) -> Expr {
408        self.add_set(name, SetKind::Top, true)
409    }
410
411    /// A top-level set of exactly one atom.
412    pub fn one(&mut self, name: &str) -> Expr {
413        self.add_set(name, SetKind::One, false)
414    }
415
416    fn parent(&self, parent: &Expr) -> usize {
417        self.index_of(parent)
418            .expect("the parent of a subset is a set of this model")
419    }
420
421    /// A subset of `parent`.
422    ///
423    /// # Panics
424    ///
425    /// If `parent` is not a set of this model: a mistake in the Rust that
426    /// builds the model, found the first time it runs.
427    pub fn subset(&mut self, name: &str, parent: &Expr) -> Expr {
428        let parent = self.parent(parent);
429        self.add_set(
430            name,
431            SetKind::Sub {
432                parent,
433                extends: false,
434            },
435            false,
436        )
437    }
438
439    /// An extension of `parent` with exactly one atom: Alloy's `one sig X
440    /// extends P`. Its parent's scope makes room for it (LOGIC.md 12.9).
441    ///
442    /// # Panics
443    ///
444    /// As [`Model::subset`].
445    pub fn one_extends(&mut self, name: &str, parent: &Expr) -> Expr {
446        let e = self.extends(name, parent);
447        if let Some(s) = self.sets.last_mut() {
448            s.one = true;
449        }
450        self.fact_named(format!("sig {name}"), e.one());
451        e
452    }
453
454    /// A subset of `parent`, disjoint from the parent's other extensions.
455    ///
456    /// # Panics
457    ///
458    /// As [`Model::subset`].
459    pub fn extends(&mut self, name: &str, parent: &Expr) -> Expr {
460        let parent = self.parent(parent);
461        self.add_set(
462            name,
463            SetKind::Sub {
464                parent,
465                extends: true,
466            },
467            false,
468        )
469    }
470
471    /// A subset of `parent` that may change from state to state.
472    ///
473    /// # Panics
474    ///
475    /// As [`Model::subset`].
476    pub fn changing_subset(&mut self, name: &str, parent: &Expr) -> Expr {
477        let parent = self.parent(parent);
478        self.add_set_changing(
479            name,
480            SetKind::Sub {
481                parent,
482                extends: false,
483            },
484            false,
485            true,
486        )
487    }
488
489    /// A relation over columns that may change from state to state.
490    pub fn changing_relation(&mut self, name: &str, columns: &[&Expr]) -> Expr {
491        self.add_relation_changing(name, columns, None, true)
492    }
493
494    /// A field that may change from state to state.
495    pub fn changing_field(&mut self, name: &str, domain: &Expr, range: &Expr) -> Expr {
496        self.add_relation_changing(name, &[domain, range], None, true)
497    }
498
499    /// A field with a multiplicity that may change from state to state; the
500    /// multiplicity holds in every state.
501    pub fn changing_field_with(
502        &mut self,
503        name: &str,
504        domain: &Expr,
505        multiplicity: Multiplicity,
506        range: &Expr,
507    ) -> Expr {
508        self.add_relation_changing(name, &[domain, range], Some(multiplicity), true)
509    }
510
511    /// Every set and relation of the model, in declaration order, then the
512    /// relations of orderings.
513    pub fn relations(&self) -> Vec<Relation> {
514        self.sets
515            .iter()
516            .map(|s| s.relation.clone())
517            .chain(self.relations.iter().map(|r| r.relation.clone()))
518            .chain(
519                self.orderings
520                    .iter()
521                    .flat_map(|(_, f, n, _)| [f.clone(), n.clone()]),
522            )
523            .collect()
524    }
525
526    /// The top-level sets a relation's columns range over: a set's own top-
527    /// level set, a relation's columns' (LOGIC.md 12.9). `None` for a
528    /// relation that is not this model's.
529    pub fn column_tops(&self, r: &Relation) -> Option<Vec<Expr>> {
530        let top = |i: usize| Expr::relation(&self.sets[self.top(i)].relation);
531        if let Some(i) = self.sets.iter().position(|s| &s.relation == r) {
532            return Some(vec![top(i)]);
533        }
534        if let Some(d) = self.relations.iter().find(|d| &d.relation == r) {
535            // A column over several top-level sets has none of its own.
536            return d
537                .columns
538                .iter()
539                .map(|c| {
540                    let mut tops: Vec<usize> = c.iter().map(|&i| self.top(i)).collect();
541                    tops.dedup();
542                    match tops.as_slice() {
543                        [one] => Some(top(*one)),
544                        _ => None,
545                    }
546                })
547                .collect();
548        }
549        self.orderings.iter().find_map(|(o, f, n, _)| {
550            if f != r && n != r {
551                return None;
552            }
553            // A union over several top-level sets has none of its own.
554            let t = match *o {
555                Ordered::Set(i) => top(i),
556                Ordered::Union(j) => {
557                    let mut tops: Vec<usize> = self.relations[j].columns[0]
558                        .iter()
559                        .map(|&i| self.top(i))
560                        .collect();
561                    tops.dedup();
562                    match tops.as_slice() {
563                        [one] => top(*one),
564                        _ => return Some(None),
565                    }
566                }
567            };
568            Some(Some(if f == r { vec![t] } else { vec![t.clone(), t] }))
569        })?
570    }
571
572    /// The top-level sets each of a relation's columns ranges over, by
573    /// name and in declaration order, a union having several.
574    pub fn column_sets(&self, r: &Relation) -> Option<Vec<Vec<String>>> {
575        let name = |i: usize| self.sets[self.top(i)].relation.name().to_string();
576        if let Some(d) = self.relations.iter().find(|d| &d.relation == r) {
577            return Some(
578                d.columns
579                    .iter()
580                    .map(|c| {
581                        let mut tops: Vec<String> = Vec::new();
582                        for &i in c {
583                            let t = name(i);
584                            if !tops.contains(&t) {
585                                tops.push(t);
586                            }
587                        }
588                        tops
589                    })
590                    .collect(),
591            );
592        }
593        self.column_tops(r)
594            .map(|t| t.iter().map(|e| vec![e.to_string()]).collect())
595    }
596
597    /// The top-level set a set of this model is inside.
598    pub fn top_of(&self, set: &Expr) -> Option<Expr> {
599        let i = self.index_of(set)?;
600        Some(Expr::relation(&self.sets[self.top(i)].relation))
601    }
602
603    /// An ordering of a set (LOGIC.md 12.9). On a top-level set, its scope
604    /// becomes exact, and `first` and `next` follow its atoms in order. On
605    /// a set that extends or is `in` another, or a subset of a union made
606    /// by `relation_over_unions` with one column, `first` and `next` are a
607    /// total order of it that the solver finds, and its size is fixed as
608    /// LOGIC.md 12.9 says. An ordering on a set that changes over time is
609    /// `model.not_a_set`.
610    ///
611    /// # Panics
612    ///
613    /// If `set` is neither a set of this model nor such a subset of a
614    /// union.
615    pub fn ordering(&mut self, set: &Expr) -> Ordering {
616        self.add_ordering(set, false)
617    }
618
619    /// An ordering for an `enum` set whose `one` extensions are fixed in
620    /// declaration order (`BoundsComputer.java`, `isEnum`, B27).
621    pub fn enum_ordering(&mut self, set: &Expr) -> Ordering {
622        self.add_ordering(set, true)
623    }
624
625    fn add_ordering(&mut self, set: &Expr, is_enum: bool) -> Ordering {
626        let union = match set.kind() {
627            ExprKind::Relation(r) if self.index_of(set).is_none() => self
628                .relations
629                .iter()
630                .position(|d| &d.relation == r && d.columns.len() == 1),
631            _ => None,
632        };
633        let (ordered, relation, free) = match union {
634            Some(j) => (Ordered::Union(j), self.relations[j].relation.clone(), true),
635            None => {
636                let i = self.parent(set);
637                let sub = matches!(self.sets[i].kind, SetKind::Sub { .. });
638                (Ordered::Set(i), self.sets[i].relation.clone(), sub)
639            }
640        };
641        let name = relation.name().to_string();
642        let first = Relation::unary(format!("{name}/first"));
643        let next = Relation::binary(format!("{name}/next"));
644        if free {
645            if relation.is_changing() {
646                self.errors.push(model_error(
647                    "model.not_a_set",
648                    format!("an ordering on `{name}`, which changes over time"),
649                ));
650            } else {
651                // LOGIC.md 12.9: `first` and `next` are free, and a fact
652                // makes them a total order of the set; each command makes
653                // the set's size exact (`scope_facts`).
654                let (s, f, nx) = (
655                    Expr::relation(&relation),
656                    Expr::relation(&first),
657                    Expr::relation(&next),
658                );
659                let x = Variable::new("x");
660                let xe = Expr::variable(&x);
661                let order = Formula::and_all([
662                    f.one(),
663                    f.is_in(&s),
664                    nx.is_in(&s.product(&s)),
665                    nx.join(&f).no(),
666                    Formula::all(
667                        vec![Decl::new(&x, &s)],
668                        &xe.join(&nx).lone().and(&nx.join(&xe).lone()),
669                    ),
670                    s.is_in(&f.join(&nx.reflexive_closure())),
671                    nx.closure().intersection(&Expr::iden()).no(),
672                ]);
673                self.fact_named(format!("ordering {name}"), order);
674            }
675        }
676        self.orderings
677            .push((ordered, first.clone(), next.clone(), is_enum));
678        Ordering {
679            set: set.clone(),
680            first: Expr::relation(&first),
681            next: Expr::relation(&next),
682        }
683    }
684
685    fn is_ordered(&self, i: usize) -> bool {
686        self.orderings
687            .iter()
688            .any(|(o, _, _, _)| *o == Ordered::Set(i))
689    }
690
691    fn is_non_enum_ordered(&self, i: usize) -> bool {
692        self.orderings
693            .iter()
694            .any(|(o, _, _, is_enum)| *o == Ordered::Set(i) && !*is_enum)
695    }
696
697    pub(crate) fn has_changing(&self) -> bool {
698        !self.changing_relations().is_empty()
699    }
700
701    fn changing_relations(&self) -> Vec<Relation> {
702        let sets = self.sets.iter().map(|s| &s.relation);
703        let rels = self.relations.iter().map(|r| &r.relation);
704        sets.chain(rels)
705            .filter(|r| r.is_changing())
706            .cloned()
707            .collect()
708    }
709
710    /// An action: a named step with parameters, one per set in `params`
711    /// (LOGIC.md 13.5). `body` gets the step and the parameters, and says
712    /// when the action can happen and what it changes. Every changing
713    /// relation it does not change stays as it was.
714    pub fn action<const N: usize>(
715        &mut self,
716        name: &str,
717        params: [&Expr; N],
718        body: impl FnOnce(&mut Step, [Expr; N]),
719    ) -> Action {
720        let vars: Vec<Variable> = (0..N)
721            .map(|i| Variable::new(format!("{name}.{i}")))
722            .collect();
723        let args: [Expr; N] = std::array::from_fn(|i| Expr::variable(&vars[i]));
724        let mut step = Step::default();
725        body(&mut step, args);
726        let mut parts = step.guards;
727        let changing = self.changing_relations();
728        let mut changed: Vec<Relation> = Vec::new();
729        for (target, _, _) in &step.effects {
730            match target.kind() {
731                ExprKind::Relation(r) if changing.contains(r) => {
732                    if !changed.contains(r) {
733                        changed.push(r.clone());
734                    }
735                }
736                _ => self.errors.push(model_error(
737                    "model.not_changing",
738                    format!("the action `{name}` changes `{target}`"),
739                )),
740            }
741        }
742        for r in &changed {
743            let current = Expr::relation(r);
744            let mut next = current.clone();
745            for (target, effect, e) in &step.effects {
746                if matches!(target.kind(), ExprKind::Relation(t) if t == r) {
747                    next = match effect {
748                        Effect::Add => next.union(e),
749                        Effect::Remove => next.difference(e),
750                        Effect::Set => e.clone(),
751                    };
752                }
753            }
754            parts.push(current.prime().equals(&next));
755        }
756        for r in changing.iter().filter(|r| !changed.contains(r)) {
757            let e = Expr::relation(r);
758            parts.push(e.prime().equals(&e));
759        }
760        let action = Action {
761            name: name.to_string(),
762            vars,
763            ranges: params.iter().map(|&p| p.clone()).collect(),
764            formula: Formula::and_all(parts),
765        };
766        self.actions.push(action.clone());
767        action
768    }
769
770    fn add_relation(
771        &mut self,
772        name: &str,
773        columns: &[&Expr],
774        multiplicity: Option<Multiplicity>,
775    ) -> Expr {
776        self.add_relation_changing(name, columns, multiplicity, false)
777    }
778
779    fn add_relation_changing(
780        &mut self,
781        name: &str,
782        columns: &[&Expr],
783        multiplicity: Option<Multiplicity>,
784        changing: bool,
785    ) -> Expr {
786        let columns: Vec<Vec<usize>> = columns.iter().map(|c| vec![self.parent(c)]).collect();
787        self.add_relation_columns(name, columns, multiplicity, changing)
788    }
789
790    /// A relation whose columns each range over a union of sets: Alloy's
791    /// `f: set A + B` (LOGIC.md 15.1).
792    ///
793    /// # Panics
794    ///
795    /// If a column names a set that is not this model's, or is empty.
796    pub fn relation_over_unions(
797        &mut self,
798        name: &str,
799        columns: &[Vec<&Expr>],
800        changing: bool,
801    ) -> Expr {
802        let columns: Vec<Vec<usize>> = columns
803            .iter()
804            .map(|c| {
805                assert!(!c.is_empty(), "a column ranges over at least one set");
806                c.iter().map(|e| self.parent(e)).collect()
807            })
808            .collect();
809        self.add_relation_columns(name, columns, None, changing)
810    }
811
812    fn add_relation_columns(
813        &mut self,
814        name: &str,
815        columns: Vec<Vec<usize>>,
816        multiplicity: Option<Multiplicity>,
817        changing: bool,
818    ) -> Expr {
819        let relation = if changing {
820            self.note_changing(name);
821            Relation::changing(name, columns.len())
822        } else {
823            Relation::new(name, columns.len())
824        };
825        let e = Expr::relation(&relation);
826        self.relations.push(RelationDecl {
827            relation,
828            columns,
829            multiplicity,
830            place: None,
831        });
832        e
833    }
834
835    /// Records the source place of a set or relation declared on this model,
836    /// so any bounds error on it points to that place rather than Elinvar's
837    /// internal source.
838    pub fn set_place(&mut self, expr: &Expr, place: Place) {
839        if let ExprKind::Relation(rel) = expr.kind() {
840            if let Some(s) = self.sets.iter_mut().find(|s| &s.relation == rel) {
841                s.place = Some(place);
842            } else if let Some(r) = self.relations.iter_mut().find(|r| &r.relation == rel) {
843                r.place = Some(place);
844            }
845        }
846    }
847
848    /// A relation over the given columns, each a set of this model.
849    ///
850    /// # Panics
851    ///
852    /// If a column is not a set of this model.
853    pub fn relation(&mut self, name: &str, columns: &[&Expr]) -> Expr {
854        self.add_relation(name, columns, None)
855    }
856
857    /// A field from `domain` to `range`: each `x` of the domain is related
858    /// to any number of the range.
859    pub fn field(&mut self, name: &str, domain: &Expr, range: &Expr) -> Expr {
860        self.add_relation(name, &[domain, range], None)
861    }
862
863    /// A field with a multiplicity: each `x` of the domain is related to
864    /// `one`, `lone`, or `some` of the range.
865    pub fn field_with(
866        &mut self,
867        name: &str,
868        domain: &Expr,
869        multiplicity: Multiplicity,
870        range: &Expr,
871    ) -> Expr {
872        self.add_relation(name, &[domain, range], Some(multiplicity))
873    }
874
875    /// A fact: true in every instance.
876    pub fn fact(&mut self, f: Formula) {
877        let name = format!("fact {}", self.facts.len() + 1);
878        self.facts.push((name, f));
879    }
880
881    /// A named fact: true in every instance, identified by `name` in
882    /// unsat-core explanations ([`Command::explain_holds`]).
883    pub fn fact_named(&mut self, name: impl Into<String>, f: Formula) {
884        self.facts.push((name.into(), f));
885    }
886
887    /// The union of the top-level sets (LOGIC.md 12.9).
888    pub fn univ(&self) -> Expr {
889        let mut tops = self
890            .sets
891            .iter()
892            .filter(|s| !matches!(s.kind, SetKind::Sub { .. }))
893            .map(|s| Expr::relation(&s.relation));
894        let first = tops.next().unwrap_or_else(Expr::none);
895        tops.fold(first, |acc, s| acc.union(&s))
896    }
897
898    /// `iden` restricted to the builder's `univ`.
899    pub fn iden(&self) -> Expr {
900        self.univ().domain_restriction(&Expr::iden())
901    }
902
903    /// A command that looks for an instance of the facts and `f`.
904    pub fn run(&self, f: &Formula) -> Command<'_> {
905        Command::new(self, f.clone(), false)
906    }
907
908    /// A command that looks for a counterexample to `assertion` under the
909    /// facts.
910    pub fn check(&self, assertion: &Formula) -> Command<'_> {
911        Command::new(self, assertion.clone(), true)
912    }
913
914    /// The facts the declarations imply, then the model's own.
915    pub(crate) fn all_facts(&self) -> Formula {
916        let mut fs = Vec::new();
917        for i in 0..self.sets.len() {
918            fs.extend(self.set_facts(i));
919        }
920        for r in &self.relations {
921            fs.extend(self.field_facts(r));
922        }
923        fs.extend(self.step_fact());
924        fs.extend(self.facts.iter().map(|(_, f)| f.clone()));
925        Formula::and_all(fs)
926    }
927
928    /// Every fact of the model paired with a human-readable rule label, for
929    /// unsat-core explanations: the facts of `all_facts`, grouped.
930    pub(crate) fn named_facts(&self) -> Vec<(String, Formula)> {
931        let mut out = Vec::new();
932        for (i, s) in self.sets.iter().enumerate() {
933            let parts = self.set_facts(i);
934            if !parts.is_empty() {
935                out.push((
936                    format!("sig {}", s.relation.name()),
937                    Formula::and_all(parts),
938                ));
939            }
940        }
941        for r in &self.relations {
942            out.push((
943                format!("field {}", r.relation.name()),
944                Formula::and_all(self.field_facts(r)),
945            ));
946        }
947        if let Some(f) = self.step_fact() {
948            out.push(("actions".to_string(), f));
949        }
950        out.extend(self.facts.iter().cloned());
951        out
952    }
953
954    /// `one A` for each set declared `one` (`one sig`, a member of an
955    /// `enum`). The bounds alone make such a set exact, so no fact says it;
956    /// `diff`, which compares facts, needs it said.
957    pub(crate) fn one_set_facts(&self) -> Vec<Formula> {
958        self.sets
959            .iter()
960            .filter(|s| s.kind == SetKind::One)
961            .map(|s| Expr::relation(&s.relation).one())
962            .collect()
963    }
964
965    /// The indices of the sets that extend set `i`, in declaration order.
966    fn extensions(&self, i: usize) -> impl Iterator<Item = usize> + '_ {
967        (0..self.sets.len()).filter(move |&j| {
968            self.sets[j].kind
969                == SetKind::Sub {
970                    parent: i,
971                    extends: true,
972                }
973        })
974    }
975
976    /// The facts set `i`'s declaration implies: inside its parent, its
977    /// extensions disjoint, and, if abstract, the union of its extensions.
978    fn set_facts(&self, i: usize) -> Vec<Formula> {
979        let s = &self.sets[i];
980        let e = Expr::relation(&s.relation);
981        let mut fs = Vec::new();
982        if let SetKind::Sub { parent, .. } = s.kind {
983            let inside = e.is_in(&Expr::relation(&self.sets[parent].relation));
984            // A changing set is inside its parent in every state.
985            fs.push(if s.relation.is_changing() {
986                inside.always()
987            } else {
988                inside
989            });
990        }
991        let extensions: Vec<Expr> = self
992            .extensions(i)
993            .map(|j| Expr::relation(&self.sets[j].relation))
994            .collect();
995        for a in 0..extensions.len() {
996            for b in a + 1..extensions.len() {
997                fs.push(extensions[a].intersection(&extensions[b]).no());
998            }
999        }
1000        if s.is_abstract && !extensions.is_empty() {
1001            let union = extensions[1..]
1002                .iter()
1003                .fold(extensions[0].clone(), |acc, x| acc.union(x));
1004            fs.push(e.equals(&union));
1005        }
1006        fs
1007    }
1008
1009    /// The facts a field's declaration implies: its typing and multiplicity.
1010    fn field_facts(&self, r: &RelationDecl) -> Vec<Formula> {
1011        let e = Expr::relation(&r.relation);
1012        let cols: Vec<Expr> = r
1013            .columns
1014            .iter()
1015            .map(|c| {
1016                let sets: Vec<Expr> = c
1017                    .iter()
1018                    .map(|&i| Expr::relation(&self.sets[i].relation))
1019                    .collect();
1020                sets[1..]
1021                    .iter()
1022                    .fold(sets[0].clone(), |acc, x| acc.union(x))
1023            })
1024            .collect();
1025        let product = cols[1..]
1026            .iter()
1027            .fold(cols[0].clone(), |acc, c| acc.product(c));
1028        let mut typing = vec![e.is_in(&product)];
1029        if let Some(m) = r.multiplicity {
1030            let x = Variable::new("x");
1031            typing.push(Formula::all(
1032                vec![Decl::new(&x, &cols[0])],
1033                &Expr::variable(&x).join(&e).apply_multiplicity(m),
1034            ));
1035        }
1036        // A changing relation is typed in every state.
1037        if r.relation.is_changing() {
1038            typing.into_iter().map(|t| t.always()).collect()
1039        } else {
1040            typing
1041        }
1042    }
1043
1044    /// LOGIC.md 13.5: every step is an action, or nothing changes. `None`
1045    /// for a model without actions.
1046    fn step_fact(&self) -> Option<Formula> {
1047        if self.actions.is_empty() {
1048            return None;
1049        }
1050        let mut steps: Vec<Formula> = self.actions.iter().map(Action::happens_somehow).collect();
1051        steps.push(Formula::and_all(
1052            self.changing_relations()
1053                .iter()
1054                .map(|r| {
1055                    let e = Expr::relation(r);
1056                    e.prime().equals(&e)
1057                })
1058                .collect::<Vec<_>>(),
1059        ));
1060        Some(Formula::or_all(steps).always())
1061    }
1062
1063    /// Registers a named step predicate for labelling trace steps in stories
1064    /// without adding a frame or transition fact to the model.
1065    pub fn register_step_label(
1066        &mut self,
1067        name: impl Into<String>,
1068        vars: Vec<Variable>,
1069        ranges: Vec<Expr>,
1070        formula: Formula,
1071    ) {
1072        self.step_labels.push(Action {
1073            name: name.into(),
1074            vars,
1075            ranges,
1076            formula,
1077        });
1078    }
1079
1080    /// Registers a structured step decomposition (guards + effect) for
1081    /// per-guard unsat cores (N14), test generation (N11), and model diagrams (W14).
1082    pub fn register_step_spec(&mut self, spec: StepSpec) {
1083        self.step_specs.push(spec);
1084    }
1085
1086    /// Records a non-decomposed arm (such as `nothing`) of transition fact
1087    /// `fact_name`, so rebuilding the transition fact during guard refinement
1088    /// preserves it.
1089    pub fn register_transition_extra(&mut self, fact_name: impl Into<String>, arm: Formula) {
1090        self.transition_extras
1091            .entry(fact_name.into())
1092            .or_default()
1093            .push(arm);
1094    }
1095
1096    /// The structured step specifications registered on this model (N11, N14, W14).
1097    #[must_use]
1098    pub fn step_specs(&self) -> &[StepSpec] {
1099        &self.step_specs
1100    }
1101
1102    /// Every fact of the model paired with its rule label (for `accepts` and
1103    /// diagnostic reporting, N12).
1104    #[must_use]
1105    pub fn all_facts_named(&self) -> Vec<(String, Formula)> {
1106        self.named_facts()
1107    }
1108
1109    pub(crate) fn transition_extras_for(&self, fact_name: &str) -> &[Formula] {
1110        self.transition_extras
1111            .get(fact_name)
1112            .map_or(&[], Vec::as_slice)
1113    }
1114
1115    pub(crate) fn replace_fact(&mut self, fact_name: &str, replacement: Formula) {
1116        for (name, f) in &mut self.facts {
1117            if name == fact_name {
1118                *f = replacement.clone();
1119            }
1120        }
1121    }
1122
1123    /// Clones this model with initial-state constraints on changing relations
1124    /// removed (such as `fact StartEmpty` or the `init` conjunct of a
1125    /// transition fact), while keeping every `always` invariant, transition
1126    /// rule, and static-relation fact intact (B22).
1127    pub(crate) fn without_initial_constraints(&self) -> Model {
1128        let mut cloned = self.clone();
1129        for (_, f) in &mut cloned.facts {
1130            let mut parts = Vec::new();
1131            flatten_and_conjuncts(f, &mut parts);
1132            let kept: Vec<Formula> = parts
1133                .into_iter()
1134                .filter(|p| {
1135                    matches!(
1136                        p.kind(),
1137                        elinvar_logic::FormulaKind::Temporal(elinvar_logic::TemporalOp::Always, _)
1138                    ) || !formula_mentions_changing(p)
1139                })
1140                .collect();
1141            *f = if kept.is_empty() {
1142                Formula::truth()
1143            } else {
1144                Formula::and_all(kept)
1145            };
1146        }
1147        cloned
1148    }
1149
1150    /// The sets declared on this model (name, parent name if any, changing).
1151    #[must_use]
1152    pub fn set_summaries(&self) -> Vec<(String, Option<String>, bool)> {
1153        self.sets
1154            .iter()
1155            .filter(|s| !s.ints)
1156            .map(|s| {
1157                let parent = match s.kind {
1158                    SetKind::Sub { parent, .. } => {
1159                        Some(self.sets[parent].relation.name().to_string())
1160                    }
1161                    _ => None,
1162                };
1163                (
1164                    s.relation.name().to_string(),
1165                    parent,
1166                    s.relation.is_changing(),
1167                )
1168            })
1169            .collect()
1170    }
1171
1172    /// The fields/relations declared on this model (name, column set names, changing).
1173    #[must_use]
1174    pub fn relation_summaries(&self) -> Vec<(String, Vec<String>, bool)> {
1175        self.relations
1176            .iter()
1177            .map(|r| {
1178                let cols = r
1179                    .columns
1180                    .iter()
1181                    .map(|c| {
1182                        c.iter()
1183                            .map(|&i| self.sets[i].relation.name())
1184                            .collect::<Vec<_>>()
1185                            .join(" + ")
1186                    })
1187                    .collect();
1188                (
1189                    r.relation.name().to_string(),
1190                    cols,
1191                    r.relation.is_changing(),
1192                )
1193            })
1194            .collect()
1195    }
1196
1197    /// The top-level set a set's atoms come from.
1198    fn top(&self, mut i: usize) -> usize {
1199        while let SetKind::Sub { parent, .. } = self.sets[i].kind {
1200            i = parent;
1201        }
1202        i
1203    }
1204}
1205
1206/// An iterator over every instance (or trace) of a [`Command`] up to symmetry
1207/// breaking (N16). Call [`InstanceIter::hit_budget`] after iteration to check
1208/// whether enumeration finished completely or stopped at the solver budget.
1209#[must_use]
1210pub struct InstanceIter {
1211    finder: crate::solve::Finder,
1212    done: bool,
1213    hit_budget: bool,
1214}
1215
1216impl InstanceIter {
1217    /// Whether enumeration stopped because the solver budget ran out rather
1218    /// than exhausting all instances.
1219    #[must_use]
1220    pub fn hit_budget(&self) -> bool {
1221        self.hit_budget
1222    }
1223}
1224
1225impl Iterator for InstanceIter {
1226    type Item = crate::solve::Next;
1227
1228    fn next(&mut self) -> Option<Self::Item> {
1229        if self.done {
1230            return None;
1231        }
1232        match self.finder.next_instance() {
1233            crate::solve::Next::Done => {
1234                self.done = true;
1235                None
1236            }
1237            crate::solve::Next::Unknown => {
1238                self.done = true;
1239                self.hit_budget = true;
1240                None
1241            }
1242            item => Some(item),
1243        }
1244    }
1245}
1246
1247/// A `run` or `check` with its scope.
1248#[derive(Clone, Debug)]
1249#[must_use]
1250pub struct Command<'m> {
1251    pub(crate) model: &'m Model,
1252    pub(crate) formula: Formula,
1253    pub(crate) is_check: bool,
1254    pub(crate) name: String,
1255    default_scope: Option<usize>,
1256    /// The bitwidth of the integers (LOGIC.md 16.1).
1257    bitwidth: u32,
1258    scopes: Vec<(Expr, usize, bool)>,
1259    pub(crate) options: Options,
1260    /// Errors of this command alone, such as a scope a reader of model
1261    /// text could not give it.
1262    errors: Vec<Error>,
1263    /// Non-fatal warnings attached to this command (such as wrapped integer
1264    /// literals or unconstrained `var` relations).
1265    pub(crate) warnings: Vec<Error>,
1266    /// Optional `expect 0` / `expect 1` annotation from model text (W16).
1267    pub(crate) expect: Option<u64>,
1268    /// Optional k-induction depth (`Some(k)` for `by induction [k]`, N9).
1269    pub(crate) inductive: Option<usize>,
1270    /// Optional helper invariants assumed and proved jointly (`using Q`, N9).
1271    pub(crate) using_invariants: Vec<Formula>,
1272    /// Whether to shrink found counterexamples or instances (W13; true for
1273    /// `check`, false by default for `run`).
1274    pub(crate) shrink: bool,
1275    /// Facts specific to this command (such as `seq/Int` bounds).
1276    extra_facts: Vec<(String, Formula)>,
1277    /// Step labels specific to this command's own trace formula (B12), tried
1278    /// before model-wide `step_labels` so two designs in one file never steal
1279    /// each other's step names.
1280    pub(crate) extra_step_labels: Vec<Action>,
1281    /// Internal replacement for `model.all_facts()` used by `diff` when
1282    /// one-step transition reduction drops unchanged transition arms (W25).
1283    override_model_facts: Option<Formula>,
1284    /// Internal flag to skip `holds_warnings` on internal `diff` checks (W25).
1285    pub(crate) skip_holds_warnings: bool,
1286}
1287
1288impl<'m> Command<'m> {
1289    fn new(model: &'m Model, formula: Formula, is_check: bool) -> Command<'m> {
1290        Command {
1291            model,
1292            formula,
1293            is_check,
1294            name: String::new(),
1295            default_scope: None,
1296            bitwidth: elinvar_logic::DEFAULT_BITWIDTH,
1297            scopes: Vec::new(),
1298            options: Options::default(),
1299            errors: Vec::new(),
1300            warnings: Vec::new(),
1301            expect: None,
1302            inductive: None,
1303            using_invariants: Vec::new(),
1304            shrink: is_check,
1305            extra_facts: Vec::new(),
1306            extra_step_labels: Vec::new(),
1307            override_model_facts: None,
1308            skip_holds_warnings: false,
1309        }
1310    }
1311
1312    pub(crate) fn with_override_model_facts(mut self, facts: Formula) -> Command<'m> {
1313        self.override_model_facts = Some(facts);
1314        self
1315    }
1316
1317    pub(crate) fn without_holds_warnings(mut self) -> Command<'m> {
1318        self.skip_holds_warnings = true;
1319        self
1320    }
1321
1322    /// Registers a named step predicate scoped to this command alone (B12).
1323    pub fn with_step_label(
1324        mut self,
1325        name: impl Into<String>,
1326        vars: Vec<Variable>,
1327        ranges: Vec<Expr>,
1328        formula: Formula,
1329    ) -> Command<'m> {
1330        self.extra_step_labels.push(Action {
1331            name: name.into(),
1332            vars,
1333            ranges,
1334            formula,
1335        });
1336        self
1337    }
1338
1339    /// Enables or disables shrinking of found instances or counterexamples
1340    /// (W13). Defaults to `true` for `check` and `false` for `run`.
1341    pub fn shrink(mut self, yes: bool) -> Command<'m> {
1342        self.shrink = yes;
1343        self
1344    }
1345
1346    /// Proves a `check` of `always P` for any number of steps within the scope
1347    /// using k-induction (`k >= 1`, N9). If the inductive step fails from a
1348    /// possibly unreachable state, falls back to bounded trace checking with a
1349    /// note in the result.
1350    pub fn by_induction(mut self, k: usize) -> Command<'m> {
1351        self.inductive = Some(k.max(1));
1352        self
1353    }
1354
1355    /// Adds a helper invariant `Q` (for `by induction ... using Q`, N9) that is
1356    /// proved jointly with the target promise so that a false helper can never
1357    /// produce a false proof.
1358    pub fn using_invariant(mut self, invariant: Formula) -> Command<'m> {
1359        self.using_invariants.push(invariant);
1360        self
1361    }
1362
1363    /// Records the command's expected outcome (`0` for no instance/counterexample,
1364    /// `1` for an instance/counterexample).
1365    pub fn expect(mut self, expect: u64) -> Command<'m> {
1366        self.expect = Some(expect);
1367        self
1368    }
1369
1370    /// Attaches a non-fatal warning to this command's report.
1371    pub fn with_warning(mut self, warning: Error) -> Command<'m> {
1372        self.warnings.push(warning);
1373        self
1374    }
1375
1376    /// Adds a command-specific fact (used, for example, for `seq/Int` bounds).
1377    pub fn with_fact(mut self, name: impl Into<String>, f: Formula) -> Command<'m> {
1378        self.extra_facts.push((name.into(), f));
1379        self
1380    }
1381
1382    /// The command's name, used in its result and story.
1383    pub fn named(mut self, name: &str) -> Command<'m> {
1384        self.name = name.to_string();
1385        self
1386    }
1387
1388    /// The scope this command gives set `i` itself, the last one given
1389    /// winning: the most atoms and whether that is exact (LOGIC.md 12.9).
1390    fn own_scope(&self, i: usize) -> Option<(usize, bool)> {
1391        self.scopes
1392            .iter()
1393            .rev()
1394            .find(|(e, _, _)| self.model.index_of(e) == Some(i))
1395            .map(|&(_, k, exact)| (k, exact))
1396    }
1397
1398    /// The size of top-level set `i` under this command (LOGIC.md 12.9):
1399    /// the most atoms and whether that is exact, or `None` without a scope.
1400    fn size_of(&self, i: usize) -> Option<(usize, bool)> {
1401        let m = self.model;
1402        let s = &m.sets[i];
1403        let own = self.own_scope(i);
1404        let ordered = m.is_ordered(i);
1405        // `one` subsets must fit, as Alloy's ScopeComputer.computeLowerBound
1406        // makes them.
1407        let ones = (0..m.sets.len())
1408            .filter(|&j| j != i && m.sets[j].one && m.top(j) == i)
1409            .count();
1410        let children: Vec<usize> = m.extensions(i).collect();
1411        let all_one = !children.is_empty() && children.iter().all(|&c| m.sets[c].one);
1412        // Exactly scoped extensions must fit, as `one` ones do.
1413        let exact_below: usize = children
1414            .iter()
1415            .filter_map(|&c| self.own_scope(c))
1416            .filter(|&(_, exact)| exact)
1417            .map(|(k, _)| k)
1418            .sum();
1419        // derive_abstract_scope: an abstract set without a scope of its own,
1420        // each of whose extensions has a scope or is `one`, has their sum.
1421        let children_sum: Option<usize> = children
1422            .iter()
1423            .map(|&c| {
1424                if m.sets[c].one {
1425                    Some(1)
1426                } else {
1427                    self.own_scope(c).map(|(k, _)| k)
1428                }
1429            })
1430            .sum();
1431        if s.ints {
1432            return Some((1usize << self.bitwidth.min(16), true));
1433        }
1434        let (k, exact) = match (&s.kind, own, self.default_scope) {
1435            (SetKind::One, _, _) => (1, true),
1436            (SetKind::Sub { .. }, _, _) => return None,
1437            (SetKind::Top, Some((k, exact)), _) => (k, exact || ordered),
1438            // ScopeComputer.derive_abstract_scope: an abstract set without
1439            // its own scope, whose extensions are all `one`, has their sum.
1440            (SetKind::Top, None, _) if s.is_abstract && all_one => (children.len(), true),
1441            (SetKind::Top, None, _)
1442                if s.is_abstract && !children.is_empty() && children_sum.is_some() =>
1443            {
1444                (children_sum.unwrap_or(0), ordered)
1445            }
1446            (SetKind::Top, None, Some(k)) => (k, ordered),
1447            (SetKind::Top, None, None) => return None,
1448        };
1449        Some((k.max(ones + exact_below), exact))
1450    }
1451
1452    /// ScopeComputer.derive_abstract_scope's second rule: an abstract set with
1453    /// a scope, all of whose extensions but one have a scope and none is
1454    /// `one`, gives the one left the difference (LOGIC.md 12.9).
1455    fn derived_scopes(&self) -> Vec<(Expr, usize, bool)> {
1456        let m = self.model;
1457        let own = |j: usize| self.own_scope(j).map(|(k, _)| k);
1458        let mut out = Vec::new();
1459        for (i, s) in m.sets.iter().enumerate() {
1460            if !s.is_abstract {
1461                continue;
1462            }
1463            let Some(total) = own(i) else { continue };
1464            let children: Vec<usize> = m.extensions(i).collect();
1465            let missing: Vec<usize> = children
1466                .iter()
1467                .copied()
1468                .filter(|&j| own(j).is_none() && !m.sets[j].one)
1469                .collect();
1470            if let [j] = missing.as_slice() {
1471                let given: usize = children
1472                    .iter()
1473                    .filter(|&&c| c != *j)
1474                    .map(|&c| {
1475                        if m.sets[c].one {
1476                            1
1477                        } else {
1478                            own(c).unwrap_or(0)
1479                        }
1480                    })
1481                    .sum();
1482                out.push((
1483                    Expr::relation(&m.sets[*j].relation),
1484                    total.saturating_sub(given),
1485                    false,
1486                ));
1487            }
1488        }
1489        out
1490    }
1491
1492    /// The facts of this command: the model's, and for each set that extends
1493    /// another and has a scope, that it has at most (or exactly) that many
1494    /// atoms, stated as Alloy's `BoundsComputer.size` states it at `59ba203`
1495    /// (LOGIC.md 12.9).
1496    pub fn facts(&self) -> Formula {
1497        self.facts_for(None)
1498    }
1499
1500    pub(crate) fn facts_for(&self, bounds: Option<&Bounds>) -> Formula {
1501        let base = self
1502            .override_model_facts
1503            .clone()
1504            .unwrap_or_else(|| self.model.all_facts());
1505        let mut fs = vec![base];
1506        fs.extend(self.scope_facts(bounds).into_iter().map(|(_, f)| f));
1507        fs.extend(self.extra_facts.iter().map(|(_, f)| f.clone()));
1508        Formula::and_all(fs)
1509    }
1510
1511    /// The size facts of the scoped extensions, labelled `scope <set>`, for
1512    /// `facts_for` and `explain_holds`.
1513    fn scope_facts(&self, bounds: Option<&Bounds>) -> Vec<(String, Formula)> {
1514        let m = self.model;
1515        let mut out = Vec::new();
1516        let mut done: Vec<usize> = Vec::new();
1517        let mut scopes: Vec<(Expr, usize, bool)> = self.scopes.clone();
1518        scopes.extend(self.derived_scopes());
1519        for (e, k, exact) in scopes.iter().rev() {
1520            let Some(i) = m.index_of(e) else { continue };
1521            if done.contains(&i) || !matches!(m.sets[i].kind, SetKind::Sub { extends: true, .. }) {
1522                continue;
1523            }
1524            done.push(i);
1525            // An exact bound of size `k` already enforces `exactly k`.
1526            if *exact
1527                && let Some(b) = bounds
1528                && let (Some(lo), Some(hi)) =
1529                    (b.lower(&m.sets[i].relation), b.upper(&m.sets[i].relation))
1530                && lo == hi
1531                && lo.len() == *k
1532            {
1533                continue;
1534            }
1535            // LOGIC.md 12.9: a scope no smaller than the set's upper bound
1536            // says nothing, as Alloy's BoundsComputer adds no fact when
1537            // `upper.size() <= n`. Without bounds, the top-level set's atoms,
1538            // which hold that upper bound, stand in for it.
1539            let room = match bounds.and_then(|b| b.upper(&m.sets[i].relation)) {
1540                Some(upper) => upper.len(),
1541                None => self.size_of(m.top(i)).map_or(0, |(n, _)| n),
1542            };
1543            if !*exact && *k >= room {
1544                continue;
1545            }
1546            out.push((
1547                format!("scope {}", m.sets[i].relation.name()),
1548                size_fact(e, *k, *exact),
1549            ));
1550        }
1551        out.extend(self.ordering_sizes(bounds));
1552        out
1553    }
1554
1555    /// LOGIC.md 12.9: the sizes orderings fix. util/ordering's parameter is
1556    /// `exactly elem`, so a set that extends another has exactly its own
1557    /// scope, or else its top-level set's. A set `in` another is exact only
1558    /// as Pardinus's `SymmetryBreaker.breakTotalOrder` at `d3e7aea` makes
1559    /// it: when its upper bound lies in one part of the universe that no
1560    /// ordering before it has taken, it is that upper bound. The parts are
1561    /// those of the bounds without the orderings' own relations, which
1562    /// Alloy does not fix in advance, and the orderings are taken in the
1563    /// order the model declares them.
1564    fn ordering_sizes(&self, bounds: Option<&Bounds>) -> Vec<(String, Formula)> {
1565        let m = self.model;
1566        let mut out = Vec::new();
1567        let computed;
1568        let bounds = match bounds {
1569            Some(b) => Some(b),
1570            None => {
1571                computed = self.bounds().ok();
1572                computed.as_ref()
1573            }
1574        };
1575        let own: Vec<&Relation> = m.orderings.iter().flat_map(|(_, f, n, _)| [f, n]).collect();
1576        let mut parts = bounds
1577            .map(|b| crate::symmetry::partition_without(b, &own))
1578            .unwrap_or_default();
1579        for (o, _, _, _) in &m.orderings {
1580            let (relation, kind) = match *o {
1581                Ordered::Set(i) => (&m.sets[i].relation, Some((i, &m.sets[i].kind))),
1582                Ordered::Union(j) => (&m.relations[j].relation, None),
1583            };
1584            let upper: Vec<u64> = bounds
1585                .and_then(|b| b.upper(relation))
1586                .map(|t| t.indices().collect())
1587                .unwrap_or_default();
1588            let part = upper
1589                .first()
1590                .and_then(|a| parts.iter().position(|p| p.contains(a)))
1591                .filter(|&k| upper.iter().all(|a| parts[k].contains(a)));
1592            // A set that extends another has atoms of its own in Alloy,
1593            // and so a part of its own, which nothing else is inside.
1594            let extends = matches!(kind, Some((_, SetKind::Sub { extends: true, .. })));
1595            if let Some(k) = part
1596                && !extends
1597            {
1598                parts.remove(k);
1599            }
1600            let k = match kind {
1601                Some((i, SetKind::Sub { extends: true, .. })) => match self.own_scope(i) {
1602                    Some((k, _)) => Some(k),
1603                    None => self.size_of(m.top(i)).map(|(k, _)| k),
1604                },
1605                Some((_, SetKind::Sub { .. })) | None => part.map(|_| upper.len()),
1606                Some(_) => None,
1607            };
1608            if let Some(k) = k {
1609                let e = Expr::relation(relation);
1610                out.push((
1611                    format!("ordering {}", relation.name()),
1612                    size_fact(&e, k, true),
1613                ));
1614            }
1615        }
1616        out
1617    }
1618
1619    /// The top-level sets with the scope this command gives them: the set,
1620    /// its name, the most atoms, and whether that number is exact (as it
1621    /// is for a `one` set). A set without a scope is left out.
1622    pub(crate) fn top_sizes(&self) -> Vec<(Expr, String, usize, bool)> {
1623        let m = self.model;
1624        m.sets
1625            .iter()
1626            .enumerate()
1627            .filter_map(|(i, s)| {
1628                let (k, exact) = self.size_of(i)?;
1629                Some((
1630                    Expr::relation(&s.relation),
1631                    s.relation.name().to_string(),
1632                    k,
1633                    exact,
1634                ))
1635            })
1636            .collect()
1637    }
1638
1639    /// The same command with set `set` given at most `k` atoms.
1640    pub(crate) fn with_scope(&self, set: &Expr, k: usize) -> Command<'m> {
1641        self.clone().scope_of(set, k)
1642    }
1643
1644    /// At most `k` atoms in every top-level set without its own scope.
1645    pub fn scope(mut self, k: usize) -> Command<'m> {
1646        self.default_scope = Some(k);
1647        self
1648    }
1649
1650    /// At most `k` atoms in `set`.
1651    pub fn scope_of(mut self, set: &Expr, k: usize) -> Command<'m> {
1652        self.scopes.push((set.clone(), k, false));
1653        self
1654    }
1655
1656    /// Exactly `k` atoms in `set`.
1657    pub fn exactly(mut self, set: &Expr, k: usize) -> Command<'m> {
1658        self.scopes.push((set.clone(), k, true));
1659        self
1660    }
1661
1662    /// Integers of `w` bits (LOGIC.md 16.1); 4 by default, as in Alloy.
1663    pub fn bitwidth(mut self, w: u32) -> Command<'m> {
1664        self.bitwidth = w;
1665        self
1666    }
1667
1668    /// At most `n` states in a trace (LOGIC.md 13.4).
1669    pub fn steps(mut self, n: usize) -> Command<'m> {
1670        self.options.steps = n;
1671        self
1672    }
1673
1674    /// Whether a trace shows what this command looks for: for `check`, the
1675    /// facts hold and the assertion fails; for `run`, the facts and the
1676    /// formula hold. The agent suite replays an agent's answer so (DESIGN.md
1677    /// section 9.8). A static instance is a trace of one state.
1678    pub fn witnessed_by(&self, trace: &Trace) -> Result<bool, Vec<Error>> {
1679        let facts = self.facts();
1680        let f = if self.is_check {
1681            facts.and(&self.formula.not())
1682        } else {
1683            facts.and(&self.formula)
1684        };
1685        elinvar_logic::evaluate_trace(trace, &f)
1686    }
1687
1688    /// The same command with an error of its own, reported when it runs.
1689    pub fn with_error(mut self, e: Error) -> Command<'m> {
1690        self.errors.push(e);
1691        self
1692    }
1693
1694    /// Another budget for each solve, keeping the other options.
1695    pub fn budget(mut self, budget: crate::sat::Budget) -> Command<'m> {
1696        self.options.budget = budget;
1697        self
1698    }
1699
1700    /// Slicing on or off (DESIGN.md section 7.9); on by default.
1701    pub fn slicing(mut self, on: bool) -> Command<'m> {
1702        self.options.slicing = on;
1703        self
1704    }
1705
1706    /// Search options: symmetry breaking and the budget.
1707    pub fn options(mut self, options: Options) -> Command<'m> {
1708        self.options = options;
1709        self
1710    }
1711
1712    /// The bounds the scopes give (LOGIC.md 12.9).
1713    ///
1714    /// Errors: `model.no_scope`, `model.not_a_set`.
1715    pub fn bounds(&self) -> Result<Bounds, Vec<Error>> {
1716        let m = self.model;
1717        let mut errors = m.errors.clone();
1718        errors.extend(self.errors.iter().cloned());
1719        let mut sizes: Vec<(usize, bool)> = Vec::new();
1720        for (i, s) in m.sets.iter().enumerate() {
1721            let size = match (&s.kind, self.size_of(i)) {
1722                (SetKind::Sub { .. }, _) => (0, false),
1723                (_, Some(size)) => size,
1724                (_, None) => {
1725                    errors.push(model_error(
1726                        "model.no_scope",
1727                        format!("`{}` has no scope", s.relation),
1728                    ));
1729                    (0, false)
1730                }
1731            };
1732            sizes.push(size);
1733        }
1734        for (e, _, _) in &self.scopes {
1735            // A top-level set, or one that extends another (LOGIC.md 12.9).
1736            let top = m
1737                .index_of(e)
1738                .is_some_and(|i| !matches!(m.sets[i].kind, SetKind::Sub { extends: false, .. }));
1739            if !top {
1740                errors.push(model_error(
1741                    "model.not_a_set",
1742                    format!("`{e}` is given a scope but is not a top-level set of the model"),
1743                ));
1744            }
1745        }
1746        let has_ints = m.sets.iter().any(|s| s.ints);
1747        if has_ints && self.bitwidth > 16 {
1748            errors.push(model_error(
1749                "model.bitwidth",
1750                format!(
1751                    "a bitwidth of {} would give `Int` 2^{} atoms",
1752                    self.bitwidth, self.bitwidth
1753                ),
1754            ));
1755        }
1756        if self.options.steps == 0 {
1757            errors.push(model_error(
1758                "model.invalid_steps",
1759                "a command asks for 0 steps; a trace needs at least 1 state".to_string(),
1760            ));
1761        }
1762        // B35: reject absurdly large scopes before allocating atom pools.
1763        const MAX_SCOPE_ATOMS: usize = 4096;
1764        let non_int_atoms: usize = m
1765            .sets
1766            .iter()
1767            .zip(&sizes)
1768            .filter(|(s, _)| !s.ints && !matches!(s.kind, SetKind::Sub { .. }))
1769            .fold(0usize, |acc, (_, &(k, _))| acc.saturating_add(k));
1770        if non_int_atoms > MAX_SCOPE_ATOMS {
1771            errors.push(model_error(
1772                "model.scope_too_large",
1773                format!("scope asks for {non_int_atoms} atoms (maximum is {MAX_SCOPE_ATOMS})"),
1774            ));
1775        }
1776        if !errors.is_empty() {
1777            return Err(errors);
1778        }
1779        let mut names = Vec::new();
1780        let mut ranges = Vec::new();
1781        let mut ints: Vec<(String, i64)> = Vec::new();
1782        for (s, &(k, _)) in m.sets.iter().zip(&sizes) {
1783            let start = names.len() as u64;
1784            if s.ints {
1785                // LOGIC.md 16.1: one atom per integer, named by it.
1786                let least = -(1i64 << (self.bitwidth.max(1) - 1));
1787                for j in 0..k as i64 {
1788                    let name = (least + j).to_string();
1789                    ints.push((name.clone(), least + j));
1790                    names.push(name);
1791                }
1792            } else if !matches!(s.kind, SetKind::Sub { .. }) {
1793                for j in 0..k {
1794                    names.push(format!("{}{j}", s.relation.name()));
1795                }
1796            }
1797            ranges.push(start..names.len() as u64);
1798        }
1799        if names.is_empty() {
1800            names.push("unused".to_string());
1801        }
1802        let strip = |mut e: Error| {
1803            e.place = None;
1804            vec![e]
1805        };
1806        let u = Universe::new(names).map_err(strip)?;
1807        let u = if has_ints || self.bitwidth != elinvar_logic::DEFAULT_BITWIDTH {
1808            let pairs: Vec<(&str, i64)> = ints.iter().map(|(n, v)| (n.as_str(), *v)).collect();
1809            u.with_ints(self.bitwidth, &pairs).map_err(strip)?
1810        } else {
1811            u
1812        };
1813        // Tight lower and upper atom lists per set (LOGIC.md 12.9): static
1814        // exact extensions of an unordered top-level set get disjoint exact
1815        // atoms, as Alloy's BoundsComputer assigns them.
1816        let mut set_lower: Vec<Vec<u64>> = (0..m.sets.len())
1817            .map(|i| {
1818                if sizes[i].1 {
1819                    ranges[i].clone().collect()
1820                } else {
1821                    Vec::new()
1822                }
1823            })
1824            .collect();
1825        let mut set_upper: Vec<Vec<u64>> = (0..m.sets.len())
1826            .map(|i| ranges[m.top(i)].clone().collect())
1827            .collect();
1828        for (top, s) in m.sets.iter().enumerate() {
1829            if matches!(s.kind, SetKind::Sub { .. }) || m.is_non_enum_ordered(top) || s.ints {
1830                continue;
1831            }
1832            if let Some((lo, hi)) = self.extends_bounds(top, ranges[top].clone(), sizes[top].1) {
1833                for (i, atoms) in lo {
1834                    set_lower[i] = atoms;
1835                }
1836                for (i, atoms) in hi {
1837                    set_upper[i] = atoms;
1838                }
1839            }
1840        }
1841        for (i, s) in m.sets.iter().enumerate() {
1842            if let SetKind::Sub {
1843                parent,
1844                extends: false,
1845            } = s.kind
1846            {
1847                set_upper[i] = set_upper[parent].clone();
1848            }
1849        }
1850        let make_set = |atoms: &[u64]| -> Result<TupleSet, Error> {
1851            let mut t = TupleSet::empty(&u, 1)?;
1852            for &a in atoms {
1853                t.insert_index(a)?;
1854            }
1855            Ok(t)
1856        };
1857        let mut b = Bounds::new(&u);
1858        let at_place = |place: &Option<Place>| {
1859            let p = place.clone();
1860            move |mut e: Error| {
1861                e.place = p;
1862                vec![e]
1863            }
1864        };
1865        for (i, s) in m.sets.iter().enumerate() {
1866            let lower = make_set(&set_lower[i]).map_err(at_place(&s.place))?;
1867            let upper = make_set(&set_upper[i]).map_err(at_place(&s.place))?;
1868            b.bound(&s.relation, lower, upper)
1869                .map_err(at_place(&s.place))?;
1870        }
1871        let n = u.size() as u64;
1872        // Each possible tuple of a relation is a solver variable, so a
1873        // relation of high arity at a large scope would exhaust memory before
1874        // any budget is consulted (AGENTS.md law 22). Count them first.
1875        const MAX_UPPER_TUPLES: u64 = 1 << 24;
1876        let column_atoms = |c: &[usize]| -> u64 {
1877            let mut atoms: Vec<u64> = c
1878                .iter()
1879                .flat_map(|&i| set_upper[i].iter().copied())
1880                .collect();
1881            atoms.sort_unstable();
1882            atoms.dedup();
1883            atoms.len() as u64
1884        };
1885        let mut total: u64 = 0;
1886        for r in &m.relations {
1887            let tuples = r
1888                .columns
1889                .iter()
1890                .fold(1u64, |acc, c| acc.saturating_mul(column_atoms(c)));
1891            total = total.saturating_add(tuples);
1892            if total > MAX_UPPER_TUPLES {
1893                let mut e = model_error(
1894                    "model.scope_too_large",
1895                    format!(
1896                        "the scope gives {} possible tuples over the relations up to `{}`, \
1897                         which has {tuples} (maximum is {MAX_UPPER_TUPLES})",
1898                        total,
1899                        r.relation.name()
1900                    ),
1901                );
1902                e.place = r.place.clone();
1903                return Err(vec![e]);
1904            }
1905        }
1906        for r in &m.relations {
1907            let mut upper = TupleSet::empty(&u, r.columns.len()).map_err(at_place(&r.place))?;
1908            let mut indices = vec![0u64];
1909            for c in &r.columns {
1910                let mut atoms: Vec<u64> = Vec::new();
1911                for &i in c {
1912                    for &a in &set_upper[i] {
1913                        if !atoms.contains(&a) {
1914                            atoms.push(a);
1915                        }
1916                    }
1917                }
1918                atoms.sort_unstable();
1919                indices = indices
1920                    .iter()
1921                    .flat_map(|&i| atoms.iter().map(move |&a| i * n + a))
1922                    .collect();
1923            }
1924            for i in indices {
1925                upper.insert_index(i).map_err(at_place(&r.place))?;
1926            }
1927            b.bound_upper(&r.relation, upper)
1928                .map_err(at_place(&r.place))?;
1929        }
1930        // LOGIC.md 12.9: an ordering follows its set's atoms in order; one
1931        // on a subset ranges over its top-level set's atoms.
1932        for (o, first, next, _) in &m.orderings {
1933            let (i, union) = match *o {
1934                Ordered::Set(i) => (i, None),
1935                Ordered::Union(j) => (m.relations[j].columns[0][0], Some(j)),
1936            };
1937            let place = match union {
1938                Some(j) => &m.relations[j].place,
1939                None => &m.sets[i].place,
1940            };
1941            if union.is_some() || matches!(m.sets[i].kind, SetKind::Sub { .. }) {
1942                // A subset of a union ranges over its sets' top-level sets.
1943                let mut tops: Vec<usize> = match union {
1944                    Some(j) => m.relations[j].columns[0]
1945                        .iter()
1946                        .map(|&c| m.top(c))
1947                        .collect(),
1948                    None => vec![m.top(i)],
1949                };
1950                tops.sort_unstable();
1951                tops.dedup();
1952                let atoms: Vec<u64> = tops.iter().flat_map(|&t| ranges[t].clone()).collect();
1953                let mut f = TupleSet::empty(&u, 1).map_err(at_place(place))?;
1954                let mut nx = TupleSet::empty(&u, 2).map_err(at_place(place))?;
1955                for &a in &atoms {
1956                    f.insert_index(a).map_err(at_place(place))?;
1957                    for &c in &atoms {
1958                        nx.insert_index(a * n + c).map_err(at_place(place))?;
1959                    }
1960                }
1961                b.bound_upper(first, f).map_err(at_place(place))?;
1962                b.bound_upper(next, nx).map_err(at_place(place))?;
1963                continue;
1964            }
1965            let atoms: Vec<u64> = ranges[i].clone().collect();
1966            let mut f = TupleSet::empty(&u, 1).map_err(at_place(place))?;
1967            let mut nx = TupleSet::empty(&u, 2).map_err(at_place(place))?;
1968            if let Some(&a) = atoms.first() {
1969                f.insert_index(a).map_err(at_place(place))?;
1970            }
1971            for w in atoms.windows(2) {
1972                nx.insert_index(w[0] * n + w[1]).map_err(at_place(place))?;
1973            }
1974            b.bound_exactly(first, f).map_err(at_place(place))?;
1975            b.bound_exactly(next, nx).map_err(at_place(place))?;
1976        }
1977        Ok(b)
1978    }
1979
1980    /// Assigns disjoint exact atoms to static `one` and `exactly k`
1981    /// extensions of an unordered top-level set `top`, as Alloy's
1982    /// `BoundsComputer.computeLowerBound` and `computeUpperBound` do.
1983    /// Returns `None` if any set in the extension tree changes over time or
1984    /// if the requested exact sizes conflict with the available atoms.
1985    #[allow(clippy::type_complexity)]
1986    fn extends_bounds(
1987        &self,
1988        top: usize,
1989        range: std::ops::Range<u64>,
1990        top_exact: bool,
1991    ) -> Option<(Vec<(usize, Vec<u64>)>, Vec<(usize, Vec<u64>)>)> {
1992        let m = self.model;
1993        let ext_children = |parent: usize| -> Vec<usize> { m.extensions(parent).collect() };
1994        // Collect every set in `top`'s extension tree; skip if any changes.
1995        let mut tree = vec![top];
1996        let mut cursor = 0;
1997        while cursor < tree.len() {
1998            let cur = tree[cursor];
1999            cursor += 1;
2000            if m.sets[cur].relation.is_changing() {
2001                return None;
2002            }
2003            tree.extend(ext_children(cur));
2004        }
2005        let exact_target = |j: usize| -> Option<usize> {
2006            if j == top {
2007                return None;
2008            }
2009            if m.sets[j].one {
2010                return Some(1);
2011            }
2012            self.own_scope(j).and_then(|(k, exact)| exact.then_some(k))
2013        };
2014        if !tree.iter().any(|&j| exact_target(j).is_some()) {
2015            return None;
2016        }
2017        let mut pool: std::collections::VecDeque<u64> = range.clone().collect();
2018        let mut lower: BTreeMap<usize, Vec<u64>> = BTreeMap::new();
2019        fn compute_lower(
2020            node: usize,
2021            ext_children: &dyn Fn(usize) -> Vec<usize>,
2022            exact_target: &dyn Fn(usize) -> Option<usize>,
2023            pool: &mut std::collections::VecDeque<u64>,
2024            lower: &mut BTreeMap<usize, Vec<u64>>,
2025        ) -> Option<Vec<u64>> {
2026            let mut atoms = Vec::new();
2027            for c in ext_children(node) {
2028                atoms.extend(compute_lower(c, ext_children, exact_target, pool, lower)?);
2029            }
2030            if let Some(k) = exact_target(node) {
2031                if k < atoms.len() {
2032                    return None;
2033                }
2034                let need = k - atoms.len();
2035                if need > pool.len() {
2036                    return None;
2037                }
2038                for _ in 0..need {
2039                    atoms.push(pool.pop_front()?);
2040                }
2041            }
2042            atoms.sort_unstable();
2043            lower.insert(node, atoms.clone());
2044            Some(atoms)
2045        }
2046        compute_lower(top, &ext_children, &exact_target, &mut pool, &mut lower)?;
2047        if top_exact {
2048            lower.insert(top, range.clone().collect());
2049        }
2050        let mut upper: BTreeMap<usize, Vec<u64>> = BTreeMap::new();
2051        upper.insert(top, range.collect());
2052        fn compute_upper(
2053            node: usize,
2054            ext_children: &dyn Fn(usize) -> Vec<usize>,
2055            exact_target: &dyn Fn(usize) -> Option<usize>,
2056            lower: &BTreeMap<usize, Vec<u64>>,
2057            upper: &mut BTreeMap<usize, Vec<u64>>,
2058        ) {
2059            let children = ext_children(node);
2060            let mut claimed: Vec<u64> = children
2061                .iter()
2062                .flat_map(|c| lower[c].iter().copied())
2063                .collect();
2064            claimed.sort_unstable();
2065            let free: Vec<u64> = upper[&node]
2066                .iter()
2067                .copied()
2068                .filter(|a| claimed.binary_search(a).is_err())
2069                .collect();
2070            for c in children {
2071                let hi = if exact_target(c).is_some() {
2072                    lower[&c].clone()
2073                } else {
2074                    let mut u = lower[&c].clone();
2075                    u.extend(&free);
2076                    u.sort_unstable();
2077                    u
2078                };
2079                upper.insert(c, hi);
2080                compute_upper(c, ext_children, exact_target, lower, upper);
2081            }
2082        }
2083        compute_upper(top, &ext_children, &exact_target, &lower, &mut upper);
2084        Some((lower.into_iter().collect(), upper.into_iter().collect()))
2085    }
2086
2087    /// The command's target formula (predicate for `run`, assertion for `check`).
2088    #[must_use]
2089    pub fn formula(&self) -> &Formula {
2090        &self.formula
2091    }
2092
2093    /// Runs the command with the default solver.
2094    ///
2095    /// Errors: those of [`Command::bounds`], then every error of the
2096    /// formulas.
2097    pub fn solve(&self) -> Result<Outcome, Vec<Error>> {
2098        self.solve_with(crate::sat::Cdcl::new)
2099    }
2100
2101    /// Returns an iterator over every instance (or trace) of this command up to
2102    /// symmetry breaking within its scope (N16, R13). Each item is refereed by
2103    /// `elinvar-logic` before being yielded.
2104    ///
2105    /// Errors: those of [`Command::bounds`], then every error of the formulas.
2106    pub fn iter_instances(&self) -> Result<InstanceIter, Vec<Error>> {
2107        let bounds = self.bounds()?;
2108        let facts = self.facts_for(Some(&bounds));
2109        let opts = self.effective_options(&facts);
2110        let formula = if self.is_check {
2111            facts.and(&self.formula.not())
2112        } else {
2113            facts.and(&self.formula)
2114        };
2115        let finder = crate::solve::Finder::new(&bounds, &formula, &opts)?;
2116        Ok(InstanceIter {
2117            finder,
2118            done: false,
2119            hit_budget: false,
2120        })
2121    }
2122
2123    /// Runs the command with a solver built by `make_solver` (R9,
2124    /// DESIGN.md section 7.4). Every returned instance or trace is still
2125    /// refereed by `elinvar-logic`.
2126    ///
2127    /// Errors: those of [`Command::bounds`], then every error of the
2128    /// formulas.
2129    /// B8: when every conjunct of `facts` is either non-temporal or a pure
2130    /// state invariant `always P` (with `P` free of temporal operators and
2131    /// primes), and the command formula itself is free of temporal operators
2132    /// and primes, any valid state extends to a 1-state stuttering trace, so
2133    /// 1 step suffices.
2134    fn effective_options(&self, facts: &Formula) -> Options {
2135        fn is_state_or_always_state(f: &Formula) -> bool {
2136            use elinvar_logic::{FormulaKind, TemporalOp};
2137            if !f.is_temporal() {
2138                return true;
2139            }
2140            match f.kind() {
2141                FormulaKind::And(fs) => fs.iter().all(is_state_or_always_state),
2142                FormulaKind::Temporal(TemporalOp::Always, inner) => !inner.is_temporal(),
2143                _ => false,
2144            }
2145        }
2146        let mut opts = self.options;
2147        if opts.steps > 1 && !self.formula.is_temporal() && is_state_or_always_state(facts) {
2148            opts.steps = 1;
2149        }
2150        opts
2151    }
2152
2153    /// Attempts a `k`-induction proof without falling back to bounded trace
2154    /// checking or counterexample shrinking when induction does not close (W23).
2155    ///
2156    /// Returns:
2157    /// - `Ok(Some(out))` when induction proved the assertion (`Verdict::Proved`),
2158    ///   found the model vacuous (`Verdict::Vacuous`), or ran out of budget
2159    ///   (`Verdict::Unknown`);
2160    /// - `Ok(None)` when the base case or inductive step failed to close.
2161    ///
2162    /// ```
2163    /// use elinvar_engine::{Model, Verdict};
2164    ///
2165    /// let mut m = Model::new();
2166    /// let item = m.set("Item");
2167    /// let kept = m.changing_subset("kept", &item);
2168    /// m.fact(kept.no());
2169    /// m.fact(kept.is_in(&kept.prime()).always());
2170    /// let out = m
2171    ///     .check(&kept.is_in(&kept.prime()).always())
2172    ///     .scope(2)
2173    ///     .prove_by_induction(1)
2174    ///     .unwrap()
2175    ///     .unwrap();
2176    /// assert_eq!(out.verdict, Verdict::Proved);
2177    /// ```
2178    pub fn prove_by_induction(&self, k: usize) -> Result<Option<Outcome>, Vec<Error>> {
2179        if !self.is_check {
2180            return Ok(None);
2181        }
2182        let bounds = self.bounds()?;
2183        let facts = self.facts_for(Some(&bounds));
2184        let opts = self.effective_options(&facts);
2185        let mut make_solver = crate::sat::Cdcl::new;
2186        match self.try_inductive(&bounds, &facts, k.max(1), &opts, &mut make_solver)? {
2187            Ok(out) => Ok(Some(out)),
2188            Err(note) if note.contains("ran out of budget") => Ok(Some(Outcome {
2189                verdict: crate::solve::Verdict::Unknown,
2190                instance: None,
2191                trace: None,
2192                labels: Vec::new(),
2193                note: Some(note),
2194                stats: crate::solve::Stats::default(),
2195            })),
2196            Err(_) => Ok(None),
2197        }
2198    }
2199
2200    pub fn solve_with<S, F>(&self, mut make_solver: F) -> Result<Outcome, Vec<Error>>
2201    where
2202        S: crate::sat::Solver + 'static,
2203        F: FnMut() -> S,
2204    {
2205        let bounds = self.bounds()?;
2206        let facts = self.facts_for(Some(&bounds));
2207        let opts = self.effective_options(&facts);
2208        let mut fallback_note: Option<String> = None;
2209        if self.is_check
2210            && let Some(k) = self.inductive
2211        {
2212            match self.try_inductive(&bounds, &facts, k, &opts, &mut make_solver)? {
2213                Ok(out) => return Ok(out),
2214                Err(note) => fallback_note = Some(note),
2215            }
2216        }
2217        let mut out = if self.is_check {
2218            if let Some(coi_out) =
2219                crate::coi::try_check_coi(&bounds, &facts, &self.formula, &opts, &mut make_solver)?
2220            {
2221                coi_out
2222            } else {
2223                check_with_solver(&bounds, &facts, &self.formula, &opts, make_solver)?
2224            }
2225        } else {
2226            run_with_solver(&bounds, &facts.and(&self.formula), &opts, make_solver)?
2227        };
2228        if let Some(trace) = &out.trace {
2229            out.labels = self.model.labels_with(trace, &self.extra_step_labels);
2230        }
2231        if out.note.is_none() {
2232            out.note = fallback_note;
2233        }
2234        Ok(out)
2235    }
2236
2237    /// Attempts a k-induction proof of `self.formula` (N9).
2238    /// Returns `Ok(Ok(outcome))` when induction settles the check (`Proved` or
2239    /// `Vacuous`), or `Ok(Err(note))` when induction does not close and the
2240    /// caller should fall back to bounded trace checking with `note`.
2241    fn try_inductive<S, F>(
2242        &self,
2243        bounds: &Bounds,
2244        facts: &Formula,
2245        k: usize,
2246        opts: &Options,
2247        make_solver: &mut F,
2248    ) -> Result<Result<Outcome, String>, Vec<Error>>
2249    where
2250        S: crate::sat::Solver + 'static,
2251        F: FnMut() -> S,
2252    {
2253        use crate::solve::{Next, Stats, Verdict, solve_fixed_states};
2254
2255        let Some((extra_init, prop, is_transition)) = extract_always_inductive(&self.formula)
2256        else {
2257            return Ok(Err(
2258                "induction applies only to promises of the form `always P` (where P reads one state or one transition); fell back to bounded traces"
2259                    .to_string(),
2260            ));
2261        };
2262
2263        let mut helper_parts = Vec::new();
2264        for h in &self.using_invariants {
2265            if let Some((None, hp, false)) = extract_always_inductive(h) {
2266                helper_parts.push(hp);
2267            } else if !h.is_temporal() {
2268                helper_parts.push(h.clone());
2269            } else {
2270                return Ok(Err(
2271                    "helper invariant in `using` must be a state invariant `always Q`; fell back to bounded traces"
2272                        .to_string(),
2273                ));
2274            }
2275        }
2276        let joint = if is_transition {
2277            prop.clone()
2278        } else {
2279            let mut all = vec![prop.clone()];
2280            all.extend(helper_parts.iter().cloned());
2281            Formula::and_all(all)
2282        };
2283        let helpers_joint = if helper_parts.is_empty() {
2284            None
2285        } else {
2286            Some(Formula::and_all(helper_parts))
2287        };
2288
2289        let mut coi_seed_parts = vec![joint.clone()];
2290        if let Some(h) = &helpers_joint {
2291            coi_seed_parts.push(h.clone());
2292        }
2293        if let Some(ei) = &extra_init {
2294            coi_seed_parts.push(ei.clone());
2295        }
2296        let coi_seed = Formula::and_all(coi_seed_parts);
2297        let coi_part = crate::coi::partition_coi(bounds, facts, &coi_seed, opts);
2298        let eff_bounds = coi_part.as_ref().map_or(bounds, |p| &p.coi_bounds);
2299        let eff_facts = coi_part.as_ref().map_or(facts, |p| &p.coi_facts);
2300
2301        let mut static_facts = Vec::new();
2302        let mut init_only = Vec::new();
2303        let mut state_invs = Vec::new();
2304        let mut step_rels = Vec::new();
2305        let mut conjuncts = Vec::new();
2306        flatten_and_conjuncts(eff_facts, &mut conjuncts);
2307        for c in conjuncts {
2308            if !c.is_temporal() {
2309                if formula_mentions_changing(&c) {
2310                    init_only.push(c);
2311                } else {
2312                    static_facts.push(c);
2313                }
2314            } else if let elinvar_logic::FormulaKind::Temporal(
2315                elinvar_logic::TemporalOp::Always,
2316                inner,
2317            ) = c.kind()
2318            {
2319                if !inner.is_temporal() {
2320                    state_invs.push(inner.clone());
2321                } else if is_one_step_formula(inner) {
2322                    step_rels.push(inner.clone());
2323                } else {
2324                    return Ok(Err(
2325                        "model has multi-step or liveness temporal facts outside induction; fell back to bounded traces"
2326                            .to_string(),
2327                    ));
2328                }
2329            } else {
2330                return Ok(Err(
2331                    "model has non-invariant temporal facts outside induction; fell back to bounded traces"
2332                        .to_string(),
2333                ));
2334            }
2335        }
2336
2337        let state_inv = Formula::and_all(state_invs);
2338        let step_rel = Formula::and_all(step_rels);
2339        let static_f = Formula::and_all(static_facts);
2340        let init_f = Formula::and_all(init_only);
2341
2342        let after_n = |f: &Formula, n: usize| -> Formula {
2343            let mut cur = f.clone();
2344            for _ in 0..n {
2345                cur = cur.after();
2346            }
2347            cur
2348        };
2349
2350        let mut total_stats = Stats::default();
2351
2352        // Step 1: Base case. State invariants need `k` states (`0..k`);
2353        // 1-step transition invariants need `k + 1` states (`0..=k`) to cover `k` transitions.
2354        let base_states = if is_transition { k + 1 } else { k };
2355        let mut base_parts = vec![static_f.clone(), init_f.clone()];
2356        for t in 0..base_states {
2357            base_parts.push(after_n(&state_inv, t));
2358        }
2359        for t in 0..base_states.saturating_sub(1) {
2360            base_parts.push(after_n(&step_rel, t));
2361        }
2362        let base_facts = Formula::and_all(base_parts);
2363        let base_check_facts = match &extra_init {
2364            Some(ei) => base_facts.and(ei),
2365            None => base_facts.clone(),
2366        };
2367        let mut base_bad_arms: Vec<Formula> = (0..k).map(|t| after_n(&joint, t).not()).collect();
2368        if is_transition && let Some(h) = &helpers_joint {
2369            for t in 0..base_states {
2370                base_bad_arms.push(after_n(h, t).not());
2371            }
2372        }
2373        // B69: share one wall-clock deadline across base case, inductive step,
2374        // non-vacuity check, and COI witness check.
2375        let ind_deadline = opts.budget.time.map(|d| std::time::Instant::now() + d);
2376        let rem_opts = |base: Options| -> Option<Options> {
2377            match ind_deadline {
2378                Some(d) => {
2379                    let rem = d.checked_duration_since(std::time::Instant::now())?;
2380                    if rem.is_zero() {
2381                        return None;
2382                    }
2383                    let mut o = base;
2384                    o.budget.time = Some(rem);
2385                    Some(o)
2386                }
2387                None => Some(base),
2388            }
2389        };
2390        let base_bad = Formula::or_all(base_bad_arms);
2391        let (base_next, st1) = solve_fixed_states(
2392            eff_bounds,
2393            &base_check_facts.and(&base_bad),
2394            base_states,
2395            opts,
2396            &mut *make_solver,
2397        )?;
2398        total_stats.primary_variables = total_stats.primary_variables.max(st1.primary_variables);
2399        total_stats.gates = total_stats.gates.max(st1.gates);
2400        total_stats.conflicts += st1.conflicts;
2401
2402        match base_next {
2403            Next::Unknown => {
2404                return Ok(Err(
2405                    "induction base case ran out of budget; fell back to bounded traces"
2406                        .to_string(),
2407                ));
2408            }
2409            Next::Instance(_) | Next::Trace(_) => {
2410                return Ok(Err(
2411                    "induction base case failed; checking bounded traces for a counterexample"
2412                        .to_string(),
2413                ));
2414            }
2415            Next::Done => {}
2416        }
2417
2418        let Some(step_opts) = rem_opts(*opts) else {
2419            return Ok(Err(
2420                "induction step ran out of time budget; fell back to bounded traces".to_string(),
2421            ));
2422        };
2423
2424        // Step 2: Inductive step over k + 1 states (0..=k) from an arbitrary state 0.
2425        // Run before the non-vacuity witness check so non-inductive candidates fail
2426        // fast without paying for an extra SAT solve (W23).
2427        let mut step_parts = vec![static_f];
2428        for t in 0..=k {
2429            step_parts.push(after_n(&state_inv, t));
2430        }
2431        for t in 0..k {
2432            step_parts.push(after_n(&step_rel, t));
2433        }
2434        let step_bad = if is_transition {
2435            for t in 0..(k - 1) {
2436                step_parts.push(after_n(&joint, t));
2437            }
2438            let mut bad_arms = vec![after_n(&joint, k - 1).not()];
2439            if let Some(h) = &helpers_joint {
2440                for t in 0..k {
2441                    step_parts.push(after_n(h, t));
2442                }
2443                bad_arms.push(after_n(h, k).not());
2444            }
2445            Formula::or_all(bad_arms)
2446        } else {
2447            for t in 0..k {
2448                step_parts.push(after_n(&joint, t));
2449            }
2450            after_n(&joint, k).not()
2451        };
2452        let step_facts = Formula::and_all(step_parts);
2453        let (step_next, st2) = solve_fixed_states(
2454            eff_bounds,
2455            &step_facts.and(&step_bad),
2456            k + 1,
2457            &step_opts,
2458            &mut *make_solver,
2459        )?;
2460        total_stats.primary_variables = total_stats.primary_variables.max(st2.primary_variables);
2461        total_stats.gates = total_stats.gates.max(st2.gates);
2462        total_stats.conflicts += st2.conflicts;
2463
2464        match step_next {
2465            Next::Done => {
2466                // Verify `eff_facts` admits a real infinite lasso trace (without
2467                // `extra_init`) so neither deadlocking initial states nor
2468                // unsatisfiable assertion premises can give a false Vacuous/Proved.
2469                // Fast path: solve `base_facts` (no `fact trace`) and referee its
2470                // 1-state stuttering trace against `eff_facts` in ~1 ms; only fall
2471                // back to full lasso solving when the base witness cannot stutter.
2472                let Some(vac_opts0) = rem_opts(*opts) else {
2473                    return Ok(Err(
2474                        "induction non-vacuity check ran out of time budget; fell back to bounded traces"
2475                            .to_string(),
2476                    ));
2477                };
2478                let (vac_fast, st_vf) = solve_fixed_states(
2479                    eff_bounds,
2480                    &base_facts,
2481                    base_states,
2482                    &vac_opts0,
2483                    &mut *make_solver,
2484                )?;
2485                total_stats.conflicts += st_vf.conflicts;
2486                let fast_ok = match &vac_fast {
2487                    Next::Instance(inst) => {
2488                        elinvar_logic::evaluate_trace(
2489                            &elinvar_logic::Trace::of_instance(inst),
2490                            eff_facts,
2491                        ) == Ok(true)
2492                    }
2493                    Next::Trace(tr) => {
2494                        tr.states().first().is_some_and(|s0| {
2495                            let mut inst = tr.fixed().clone();
2496                            for (rel, ts) in s0.entries() {
2497                                if rel.is_changing() {
2498                                    let _ = inst.set(rel, ts.clone());
2499                                }
2500                            }
2501                            elinvar_logic::evaluate_trace(
2502                                &elinvar_logic::Trace::of_instance(&inst),
2503                                eff_facts,
2504                            ) == Ok(true)
2505                        })
2506                    }
2507                    Next::Done | Next::Unknown => false,
2508                };
2509                if !fast_ok {
2510                    let Some(mut vac_opts) = rem_opts(*opts) else {
2511                        return Ok(Err(
2512                            "induction non-vacuity check ran out of time budget; fell back to bounded traces"
2513                                .to_string(),
2514                        ));
2515                    };
2516                    vac_opts.steps = 1;
2517                    let mut vac_out =
2518                        run_with_solver(eff_bounds, eff_facts, &vac_opts, &mut *make_solver)?;
2519                    total_stats.conflicts += vac_out.stats.conflicts;
2520                    if vac_out.verdict == Verdict::None {
2521                        let Some(mut vac_opts2) = rem_opts(*opts) else {
2522                            return Ok(Err(
2523                                "induction non-vacuity check ran out of time budget; fell back to bounded traces"
2524                                    .to_string(),
2525                            ));
2526                        };
2527                        vac_opts2.steps = opts.steps.max(2);
2528                        vac_out =
2529                            run_with_solver(eff_bounds, eff_facts, &vac_opts2, &mut *make_solver)?;
2530                        total_stats.conflicts += vac_out.stats.conflicts;
2531                    }
2532                    match vac_out.verdict {
2533                        Verdict::Found => {}
2534                        Verdict::None => {
2535                            return Ok(Ok(Outcome {
2536                                verdict: Verdict::Vacuous,
2537                                instance: None,
2538                                trace: None,
2539                                labels: Vec::new(),
2540                                note: None,
2541                                stats: total_stats,
2542                            }));
2543                        }
2544                        _ => {
2545                            return Ok(Err(
2546                                "induction could not confirm a non-vacuous trace; fell back to bounded traces"
2547                                    .to_string(),
2548                            ));
2549                        }
2550                    }
2551                }
2552                // W25: when COI dropped unrelated tables, confirm the dropped
2553                // component admits a 1-state stuttering witness so we never
2554                // mask a vacuous dropped component as `Proved`.
2555                if let Some(part) = &coi_part {
2556                    let Some(coi_opts) = rem_opts(*opts) else {
2557                        return Ok(Err(
2558                            "dropped COI witness check ran out of time budget; fell back to bounded traces"
2559                                .to_string(),
2560                        ));
2561                    };
2562                    if part
2563                        .find_dropped_stutter_witness(bounds, &coi_opts, &mut *make_solver)?
2564                        .is_none()
2565                    {
2566                        return Ok(Err(
2567                            "dropped COI component could not confirm a 1-state witness; fell back to bounded traces"
2568                                .to_string(),
2569                        ));
2570                    }
2571                }
2572                let kind = if k == 1 {
2573                    "induction".to_string()
2574                } else {
2575                    format!("{k}-induction")
2576                };
2577                Ok(Ok(Outcome {
2578                    verdict: Verdict::Proved,
2579                    instance: None,
2580                    trace: None,
2581                    labels: Vec::new(),
2582                    note: Some(format!("proved for any number of steps by {kind}")),
2583                    stats: total_stats,
2584                }))
2585            }
2586            Next::Trace(t) => {
2587                let labels = self.model.labels_with(&t, &self.extra_step_labels);
2588                let step_desc = labels
2589                    .get(k - 1)
2590                    .and_then(|l| l.action.as_ref())
2591                    .map(|a| format!(" (action `{a}`)"))
2592                    .unwrap_or_default();
2593                Ok(Err(format!(
2594                    "inductive step failed{step_desc} from a possibly unreachable state; fell back to bounded traces"
2595                )))
2596            }
2597            Next::Instance(_) => Ok(Err(
2598                "inductive step failed from a possibly unreachable state; fell back to bounded traces"
2599                    .to_string(),
2600            )),
2601            Next::Unknown => Ok(Err(
2602                "inductive step ran out of budget; fell back to bounded traces".to_string(),
2603            )),
2604        }
2605    }
2606
2607    /// Explains why a `check` command holds (or is vacuous) within its scope
2608    /// by extracting a minimal unsatisfiable core of the model's named rules
2609    /// (REQUIREMENTS.md section 8). Returns `Ok(None)` if a counterexample
2610    /// exists, if this is a `run` command, or if the budget runs out.
2611    ///
2612    /// When the rules alone are unsatisfiable (`vacuous`), explains why the
2613    /// rules contradict each other without conjoining `!assertion`.
2614    pub fn explain_holds(&self) -> Result<Option<HoldsCore>, Vec<Error>> {
2615        if !self.is_check {
2616            return Ok(None);
2617        }
2618        let mut remaining = self
2619            .options
2620            .budget
2621            .conflicts
2622            .unwrap_or(crate::solve::DEFAULT_CONFLICTS);
2623        let bounds = self.bounds()?;
2624        let mut rules = self.model.named_facts();
2625        rules.extend(self.scope_facts(Some(&bounds)));
2626        rules.extend(self.extra_facts.iter().cloned());
2627        let facts = self.facts_for(Some(&bounds));
2628        let opts = self.effective_options(&facts);
2629        let mut make_solver = crate::sat::Cdcl::new;
2630
2631        // W25: when COI drops unrelated tables and the dropped component has a
2632        // 1-state stuttering witness, both vacuity and assertion core extraction
2633        // run strictly on the smaller COI slice.
2634        if let Some(part) = crate::coi::partition_coi(&bounds, &facts, &self.formula, &opts)
2635            && part
2636                .find_dropped_stutter_witness(&bounds, &opts, &mut make_solver)?
2637                .is_some()
2638        {
2639            let coi_rules = part.project_named_rules(&rules);
2640            if let crate::solve::CoreResult::Complete(core) = crate::solve::explain_core_budgeted(
2641                &part.coi_bounds,
2642                &coi_rules,
2643                &Formula::falsity(),
2644                &opts,
2645                &mut remaining,
2646            )? {
2647                return Ok(Some(core));
2648            }
2649            let res = crate::solve::explain_core_budgeted(
2650                &part.coi_bounds,
2651                &coi_rules,
2652                &self.formula,
2653                &opts,
2654                &mut remaining,
2655            )?;
2656            if let crate::solve::CoreResult::Complete(mut core) = res {
2657                if self
2658                    .refine_guard_core(
2659                        &part.coi_bounds,
2660                        &coi_rules,
2661                        &opts,
2662                        &mut core,
2663                        &mut remaining,
2664                        Some(&part),
2665                    )
2666                    .is_some()
2667                {
2668                    return Ok(None);
2669                }
2670                return Ok(Some(core));
2671            }
2672            return Ok(None);
2673        }
2674
2675        if let crate::solve::CoreResult::Complete(core) =
2676            self.explain_vacuous_budgeted(&mut remaining)?
2677        {
2678            return Ok(Some(core));
2679        }
2680        match self.explain_assertion_budgeted(&mut remaining)? {
2681            crate::solve::CoreResult::Complete(core) => Ok(Some(core)),
2682            _ => Ok(None),
2683        }
2684    }
2685
2686    pub(crate) fn explain_vacuous_budgeted(
2687        &self,
2688        remaining: &mut u64,
2689    ) -> Result<crate::solve::CoreResult, Vec<Error>> {
2690        if !self.is_check {
2691            return Ok(crate::solve::CoreResult::NotUnsat);
2692        }
2693        let bounds = self.bounds()?;
2694        let mut rules = self.model.named_facts();
2695        rules.extend(self.scope_facts(Some(&bounds)));
2696        rules.extend(self.extra_facts.iter().cloned());
2697        let facts = self.facts_for(Some(&bounds));
2698        let opts = self.effective_options(&facts);
2699        crate::solve::explain_core_budgeted(&bounds, &rules, &Formula::falsity(), &opts, remaining)
2700    }
2701
2702    /// Why a `run` has no instance within its scope (REQUIREMENTS.md
2703    /// section 8): a minimal core of the named rules that, with the run's
2704    /// own constraint, admits none, or, when the rules alone admit none,
2705    /// a minimal core of the rules alone, with `true` beside it.
2706    pub(crate) fn explain_no_instance_budgeted(
2707        &self,
2708        remaining: &mut u64,
2709    ) -> Result<(crate::solve::CoreResult, bool), Vec<Error>> {
2710        if self.is_check {
2711            return Ok((crate::solve::CoreResult::NotUnsat, false));
2712        }
2713        let bounds = self.bounds()?;
2714        let mut rules = self.model.named_facts();
2715        rules.extend(self.scope_facts(Some(&bounds)));
2716        rules.extend(self.extra_facts.iter().cloned());
2717        let facts = self.facts_for(Some(&bounds));
2718        let opts = self.effective_options(&facts);
2719        let alone = crate::solve::explain_core_budgeted(
2720            &bounds,
2721            &rules,
2722            &Formula::falsity(),
2723            &opts,
2724            remaining,
2725        )?;
2726        if !matches!(alone, crate::solve::CoreResult::NotUnsat) {
2727            return Ok((alone, true));
2728        }
2729        // No instance of F is a check of `not F`.
2730        let with_run = crate::solve::explain_core_budgeted(
2731            &bounds,
2732            &rules,
2733            &self.formula.not(),
2734            &opts,
2735            remaining,
2736        )?;
2737        Ok((with_run, false))
2738    }
2739
2740    pub(crate) fn explain_assertion_budgeted(
2741        &self,
2742        remaining: &mut u64,
2743    ) -> Result<crate::solve::CoreResult, Vec<Error>> {
2744        if !self.is_check {
2745            return Ok(crate::solve::CoreResult::NotUnsat);
2746        }
2747        let bounds = self.bounds()?;
2748        let mut rules = self.model.named_facts();
2749        rules.extend(self.scope_facts(Some(&bounds)));
2750        rules.extend(self.extra_facts.iter().cloned());
2751        let facts = self.facts_for(Some(&bounds));
2752        let opts = self.effective_options(&facts);
2753        let coi_part = crate::coi::partition_coi(&bounds, &facts, &self.formula, &opts);
2754        let (eff_bounds, eff_rules, eff_part) = if let Some(part) = &coi_part {
2755            (
2756                &part.coi_bounds,
2757                part.project_named_rules(&rules),
2758                Some(part),
2759            )
2760        } else {
2761            (&bounds, rules, None)
2762        };
2763        let res = crate::solve::explain_core_budgeted(
2764            eff_bounds,
2765            &eff_rules,
2766            &self.formula,
2767            &opts,
2768            remaining,
2769        )?;
2770        match res {
2771            crate::solve::CoreResult::Complete(mut core) => {
2772                // N14 & B13: refine any transition fact in `core.used` down to individual
2773                // step guards under the same shared conflict budget.
2774                if let Some(note) = self.refine_guard_core(
2775                    eff_bounds, &eff_rules, &opts, &mut core, remaining, eff_part,
2776                ) {
2777                    Ok(crate::solve::CoreResult::Incomplete {
2778                        core: Some(core),
2779                        note,
2780                    })
2781                } else {
2782                    Ok(crate::solve::CoreResult::Complete(core))
2783                }
2784            }
2785            other => Ok(other),
2786        }
2787    }
2788
2789    fn refine_guard_core(
2790        &self,
2791        bounds: &Bounds,
2792        rules: &[(String, Formula)],
2793        opts: &Options,
2794        core: &mut HoldsCore,
2795        remaining: &mut u64,
2796        coi_part: Option<&crate::coi::CoiPartition>,
2797    ) -> Option<String> {
2798        if self.model.step_specs.is_empty() {
2799            return None;
2800        }
2801        fn extract_init_conjuncts(f: &Formula, out: &mut Vec<Formula>) {
2802            match f.kind() {
2803                elinvar_logic::FormulaKind::And(fs) => {
2804                    for g in fs {
2805                        extract_init_conjuncts(g, out);
2806                    }
2807                }
2808                elinvar_logic::FormulaKind::Temporal(elinvar_logic::TemporalOp::Always, _) => {}
2809                _ => out.push(f.clone()),
2810            }
2811        }
2812        // Group step specs by their transition fact name.
2813        let mut by_fact: BTreeMap<String, Vec<&StepSpec>> = BTreeMap::new();
2814        for s in &self.model.step_specs {
2815            by_fact.entry(s.fact_name.clone()).or_default().push(s);
2816        }
2817        for (fact_name, specs) in by_fact {
2818            if !core.used.contains(&fact_name) {
2819                continue;
2820            }
2821            if specs.iter().all(|s| s.guards.is_empty()) {
2822                continue;
2823            }
2824            let other_used: Vec<Formula> = rules
2825                .iter()
2826                .filter(|(n, _)| n != &fact_name && core.used.contains(n))
2827                .map(|(_, f)| f.clone())
2828                .collect();
2829            let mut init_conjuncts = Vec::new();
2830            for (n, f) in rules {
2831                if n == &fact_name {
2832                    extract_init_conjuncts(f, &mut init_conjuncts);
2833                }
2834            }
2835            let extras: Vec<Formula> = self
2836                .model
2837                .transition_extras
2838                .get(&fact_name)
2839                .cloned()
2840                .unwrap_or_default()
2841                .into_iter()
2842                .filter_map(|arm| match coi_part {
2843                    Some(part) => part.strip_arm_to_coi(&arm),
2844                    None => Some(arm),
2845                })
2846                .collect();
2847            let specs: Vec<&StepSpec> = if let Some(part) = coi_part {
2848                specs
2849                    .into_iter()
2850                    .filter(|s| part.strip_arm_to_coi(&s.full_arm()).is_some())
2851                    .collect()
2852            } else {
2853                specs
2854            };
2855
2856            let rebuild = |active: &[Vec<bool>], include_init: bool| -> Formula {
2857                let mut arms = extras.clone();
2858                for (spec, flags) in specs.iter().zip(active) {
2859                    let arm = spec.with_active_guards(flags);
2860                    if let Some(part) = coi_part {
2861                        if let Some(stripped) = part.strip_arm_to_coi(&arm) {
2862                            arms.push(stripped);
2863                        }
2864                    } else {
2865                        arms.push(arm);
2866                    }
2867                }
2868                let trans = Formula::or_all(arms).always();
2869                if include_init && !init_conjuncts.is_empty() {
2870                    let mut parts = init_conjuncts.clone();
2871                    parts.push(trans);
2872                    Formula::and_all(parts)
2873                } else {
2874                    trans
2875                }
2876            };
2877
2878            let mut active: Vec<Vec<bool>> =
2879                specs.iter().map(|s| vec![true; s.guards.len()]).collect();
2880
2881            let probe =
2882                |parts: Vec<Formula>, remaining: &mut u64| -> Option<crate::solve::Verdict> {
2883                    if *remaining == 0 {
2884                        return Some(crate::solve::Verdict::Unknown);
2885                    }
2886                    let mut check_opts = *opts;
2887                    check_opts.budget = crate::sat::Budget {
2888                        conflicts: Some(*remaining),
2889                        time: opts.budget.time,
2890                    };
2891                    let out = run_with_solver(
2892                        bounds,
2893                        &Formula::and_all(parts),
2894                        &check_opts,
2895                        crate::sat::Cdcl::new,
2896                    )
2897                    .ok()?;
2898                    *remaining = remaining.saturating_sub(out.stats.conflicts);
2899                    Some(out.verdict)
2900                };
2901
2902            // Verify our reconstructed transition fact (with init conjuncts!)
2903            // matches the UNSAT core before testing guards.
2904            let mut base_parts = other_used.clone();
2905            base_parts.push(rebuild(&active, true));
2906            base_parts.push(self.formula.not());
2907            match probe(base_parts, remaining) {
2908                Some(crate::solve::Verdict::None) => {}
2909                Some(crate::solve::Verdict::Unknown) => {
2910                    return Some("guard core refinement did not finish within budget".to_string());
2911                }
2912                _ => continue,
2913            }
2914
2915            let mut needed_guards = Vec::new();
2916            let mut unused_guards = Vec::new();
2917            for (si, spec) in specs.iter().enumerate() {
2918                for (gi, guard) in spec.guards.iter().enumerate() {
2919                    active[si][gi] = false;
2920                    let mut trial_parts = other_used.clone();
2921                    trial_parts.push(rebuild(&active, true));
2922                    trial_parts.push(self.formula.not());
2923                    let label = format!("{}: `{}`", spec.name, guard.label);
2924                    match probe(trial_parts, remaining) {
2925                        Some(crate::solve::Verdict::None) => {
2926                            unused_guards.push(label);
2927                        }
2928                        Some(crate::solve::Verdict::Unknown) => {
2929                            active[si][gi] = true;
2930                            return Some(
2931                                "guard core refinement did not finish within budget".to_string(),
2932                            );
2933                        }
2934                        _ => {
2935                            active[si][gi] = true;
2936                            needed_guards.push(label);
2937                        }
2938                    }
2939                }
2940            }
2941            let init_needed = if !init_conjuncts.is_empty() && !needed_guards.is_empty() {
2942                let mut trial_parts = other_used.clone();
2943                trial_parts.push(rebuild(&active, false));
2944                trial_parts.push(self.formula.not());
2945                !matches!(
2946                    probe(trial_parts, remaining),
2947                    Some(crate::solve::Verdict::None)
2948                )
2949            } else {
2950                false
2951            };
2952            if !needed_guards.is_empty()
2953                && let Some(pos) = core.used.iter().position(|n| n == &fact_name)
2954            {
2955                core.used.remove(pos);
2956                let mut replacements = Vec::new();
2957                if init_needed {
2958                    replacements.push(format!("{fact_name} (init)"));
2959                }
2960                replacements.extend(needed_guards);
2961                for (offset, g) in replacements.into_iter().enumerate() {
2962                    core.used.insert(pos + offset, g);
2963                }
2964            }
2965            for g in unused_guards {
2966                if !core.unused.contains(&g) {
2967                    core.unused.push(g);
2968                }
2969            }
2970        }
2971        None
2972    }
2973
2974    /// N13: checks whether a `holds` or `proved` check held without using any
2975    /// rule of the model (`model.trivial_holds`) or because its implication
2976    /// premise can never be satisfied (`model.vacuous_premise`).
2977    pub(crate) fn holds_warnings<S, F>(&self, make_solver: &mut F) -> Vec<Error>
2978    where
2979        S: crate::sat::Solver + 'static,
2980        F: FnMut() -> S,
2981    {
2982        if !self.is_check {
2983            return Vec::new();
2984        }
2985        let Ok(bounds) = self.bounds() else {
2986            return Vec::new();
2987        };
2988        let facts = self.facts_for(Some(&bounds));
2989        let mut out = Vec::new();
2990        let cap = |b: crate::sat::Budget| -> crate::sat::Budget {
2991            let max_c = 50_000u64;
2992            let c = b.conflicts.map_or(max_c, |v| v.min(max_c));
2993            crate::sat::Budget {
2994                conflicts: Some(c),
2995                time: b.time,
2996            }
2997        };
2998
2999        // 1. Rule-free holds: `!assertion` is UNSAT under bounds alone (no facts).
3000        // W27/W29: with no facts, only relations mentioned in each decomposed
3001        // obligation matter, and `!(always P)` for non-temporal `P` is SAT iff
3002        // `!P` is SAT in 1 step.
3003        let (triv_assert, triv_single_step) = match self.formula.kind() {
3004            elinvar_logic::FormulaKind::Temporal(elinvar_logic::TemporalOp::Always, inner)
3005                if !inner.is_temporal() =>
3006            {
3007                (inner.clone(), true)
3008            }
3009            _ => (self.formula.clone(), !self.formula.is_temporal()),
3010        };
3011        let mut triv_opts = self.effective_options(&Formula::truth());
3012        if triv_single_step {
3013            triv_opts.steps = 1;
3014        }
3015        triv_opts.budget = cap(triv_opts.budget);
3016        let triv_obligations = if triv_single_step {
3017            crate::coi::decompose_check_obligations(&triv_assert)
3018        } else {
3019            vec![triv_assert]
3020        };
3021        let mut all_triv_unsat = !triv_obligations.is_empty();
3022        for ob in &triv_obligations {
3023            let neg_ob = ob.not();
3024            let triv_proj = crate::coi::project_bounds_for_formula(&bounds, &neg_ob);
3025            let triv_bounds = triv_proj.as_ref().unwrap_or(&bounds);
3026            match run_with_solver(triv_bounds, &neg_ob, &triv_opts, &mut *make_solver) {
3027                Ok(res) if res.verdict == crate::solve::Verdict::None => {}
3028                _ => {
3029                    all_triv_unsat = false;
3030                    break;
3031                }
3032            }
3033        }
3034        if all_triv_unsat {
3035            out.push(
3036                model_error(
3037                    "model.trivial_holds",
3038                    format!(
3039                        "assertion `{}` holds from bounds alone without using any rule of the model",
3040                        self.name
3041                    ),
3042                )
3043                .at(self.formula.place().clone()),
3044            );
3045        }
3046
3047        // 2. Vacuous premise: for `A implies B` (under optional `always` / `all`),
3048        //    check whether `A` can ever hold in any allowed case.
3049        //    W27: `facts and eventually P` is UNSAT iff `facts => always (not P)`
3050        //    holds, so reuse `try_check_coi` to drop unread tables and collapse
3051        //    stutter-admitting transitions before falling back to full solving.
3052        if let Some(witness) = premise_witness(&self.formula) {
3053            let mut prem_opts = self.effective_options(&facts);
3054            prem_opts.budget = cap(prem_opts.budget);
3055            let neg_witness = match witness.kind() {
3056                elinvar_logic::FormulaKind::Temporal(
3057                    elinvar_logic::TemporalOp::Eventually,
3058                    inner,
3059                ) if !inner.is_temporal() => inner.not().always(),
3060                _ => witness.not(),
3061            };
3062            use crate::solve::Verdict as V;
3063            // `Some(true)` the premise never holds, `Some(false)` it can,
3064            // `None` the capped budget ran out before either was known.
3065            let vacuous = match crate::coi::try_check_coi(
3066                &bounds,
3067                &facts,
3068                &neg_witness,
3069                &prem_opts,
3070                &mut *make_solver,
3071            ) {
3072                Ok(Some(res)) if res.verdict == V::Unknown => None,
3073                Ok(Some(res)) => Some(res.verdict == V::Holds),
3074                _ => {
3075                    let prem_part =
3076                        crate::coi::partition_coi(&bounds, &facts, &witness, &prem_opts);
3077                    let (p_bounds, p_facts) = prem_part
3078                        .as_ref()
3079                        .map_or((&bounds, &facts), |p| (&p.coi_bounds, &p.coi_facts));
3080                    match run_with_solver(
3081                        p_bounds,
3082                        &p_facts.and(&witness),
3083                        &prem_opts,
3084                        &mut *make_solver,
3085                    ) {
3086                        Ok(res) if res.verdict == V::Unknown => None,
3087                        Ok(res) => Some(res.verdict == V::None),
3088                        // The check's own solve reports the error.
3089                        Err(_) => Some(false),
3090                    }
3091                }
3092            };
3093            if vacuous.is_none() {
3094                // AGENTS.md laws 14 and 20: a `holds` over a premise that may
3095                // never happen is not left to look like a plain `holds`.
3096                out.push(
3097                    model_error(
3098                        "model.premise_unknown",
3099                        format!(
3100                            "whether the premise of `{}` can ever be satisfied was not found \
3101                             within {} conflicts, so this `holds` may be vacuous",
3102                            self.name,
3103                            prem_opts.budget.conflicts.unwrap_or(0)
3104                        ),
3105                    )
3106                    .at(self.formula.place().clone()),
3107                );
3108            }
3109            if vacuous == Some(true) {
3110                out.push(
3111                    model_error(
3112                        "model.vacuous_premise",
3113                        format!(
3114                            "the premise of `{}` is never satisfied in any allowed case within the scope",
3115                            self.name
3116                        ),
3117                    )
3118                    .at(self.formula.place().clone()),
3119                );
3120            }
3121        }
3122        out
3123    }
3124}
3125
3126/// Extracts a formula that witnesses the premise of an implication promise
3127/// being satisfied at least once (N13).
3128fn premise_witness(f: &Formula) -> Option<Formula> {
3129    use elinvar_logic::{FormulaKind, Quantifier, TemporalOp};
3130    match f.kind() {
3131        FormulaKind::Implies(a, b) => {
3132            if let Some(inner) = premise_witness(b) {
3133                Some(a.and(&inner))
3134            } else {
3135                Some(a.clone())
3136            }
3137        }
3138        FormulaKind::Quantified(Quantifier::All, decls, body) => {
3139            let inner = premise_witness(body)?;
3140            Some(Formula::some(decls.clone(), &inner))
3141        }
3142        FormulaKind::Temporal(TemporalOp::Always, inner) => {
3143            let w = premise_witness(inner)?;
3144            Some(w.eventually())
3145        }
3146        FormulaKind::And(fs) if fs.len() == 1 => premise_witness(&fs[0]),
3147        _ => None,
3148    }
3149}
3150
3151impl Model {
3152    /// LOGIC.md 13.5: each step of the trace, labelled with the first
3153    /// action or registered step predicate and arguments that happen at it,
3154    /// trying command-scoped `extra` step predicates before model-wide
3155    /// `step_labels`, and leaving no-change steps unlabelled (`nothing changes`)
3156    /// for Alloy-text models (B12).
3157    pub(crate) fn labels_with(&self, trace: &Trace, extra: &[Action]) -> Vec<StepLabel> {
3158        let candidates: Vec<&Action> = self
3159            .actions
3160            .iter()
3161            .chain(extra)
3162            .chain(&self.step_labels)
3163            .collect();
3164        if candidates.is_empty() {
3165            return (0..trace.states().len())
3166                .map(|_| StepLabel {
3167                    action: None,
3168                    args: Vec::new(),
3169                })
3170                .collect();
3171        }
3172        let states = trace.states();
3173        (0..states.len())
3174            .map(|k| {
3175                // B12: when using Alloy-text step labels (`self.actions.is_empty()`),
3176                // a step where no changing relation actually changes is always
3177                // `nothing changes`, never an idempotent write predicate.
3178                if self.actions.is_empty() {
3179                    let to = if k + 1 < states.len() {
3180                        k + 1
3181                    } else {
3182                        trace.loop_to()
3183                    };
3184                    let any_changed = states[k]
3185                        .entries()
3186                        .any(|(r, now)| states[to].get(r).is_some_and(|next| next != now));
3187                    if !any_changed {
3188                        return StepLabel {
3189                            action: None,
3190                            args: Vec::new(),
3191                        };
3192                    }
3193                }
3194                for a in &candidates {
3195                    let mut domains: Vec<Vec<usize>> = Vec::with_capacity(a.vars.len());
3196                    let mut empty = false;
3197                    for r in &a.ranges {
3198                        let atoms: Vec<usize> = match evaluate_trace_expr_at(trace, r, k) {
3199                            Ok(ts) => ts.indices().map(|i| i as usize).collect(),
3200                            Err(_) => Vec::new(),
3201                        };
3202                        if atoms.is_empty() {
3203                            empty = true;
3204                            break;
3205                        }
3206                        domains.push(atoms);
3207                    }
3208                    if empty {
3209                        continue;
3210                    }
3211                    let total: usize = domains
3212                        .iter()
3213                        .try_fold(1usize, |acc, d| acc.checked_mul(d.len()))
3214                        .unwrap_or(0);
3215                    // Cap combinatorial enumeration per step so large scopes stay fast.
3216                    if total == 0 || total > 1024 {
3217                        continue;
3218                    }
3219                    for code in 0..total {
3220                        let mut atoms = vec![0usize; domains.len()];
3221                        let mut c = code;
3222                        for (slot, dom) in atoms.iter_mut().zip(&domains).rev() {
3223                            *slot = dom[c % dom.len()];
3224                            c /= dom.len();
3225                        }
3226                        let bindings: Vec<(Variable, usize)> =
3227                            a.vars.iter().cloned().zip(atoms.iter().copied()).collect();
3228                        if evaluate_trace_at(trace, &a.formula, k, &bindings) == Ok(true) {
3229                            return StepLabel {
3230                                action: Some(a.name.clone()),
3231                                args: atoms
3232                                    .iter()
3233                                    .map(|&x| {
3234                                        trace
3235                                            .universe()
3236                                            .atom(x)
3237                                            .expect("an atom of the universe")
3238                                            .to_string()
3239                                    })
3240                                    .collect(),
3241                            };
3242                        }
3243                    }
3244                }
3245                StepLabel {
3246                    action: None,
3247                    args: Vec::new(),
3248                }
3249            })
3250            .collect()
3251    }
3252}
3253
3254/// `s` has at most `k` atoms, or exactly `k`: `no s or some v1, ..., vk: s |
3255/// s = v1 + ... + vk`, the `vi` disjoint when exact, as Alloy's
3256/// `BoundsComputer.size` states it (LOGIC.md 12.9).
3257fn size_fact(s: &Expr, k: usize, exact: bool) -> Formula {
3258    match k {
3259        0 => return s.no(),
3260        1 => return if exact { s.one() } else { s.lone() },
3261        _ => {}
3262    }
3263    let vars: Vec<Variable> = (1..=k).map(|j| Variable::new(format!("v{j}"))).collect();
3264    let es: Vec<Expr> = vars.iter().map(Expr::variable).collect();
3265    let mut sum = es[0].clone();
3266    let mut disjoint = Vec::new();
3267    for e in &es[1..] {
3268        disjoint.push(e.intersection(&sum).no());
3269        sum = e.union(&sum);
3270    }
3271    let decls: Vec<Decl> = vars.iter().map(|v| Decl::new(v, s)).collect();
3272    if exact {
3273        Formula::some(decls, &sum.equals(s).and(&Formula::and_all(disjoint)))
3274    } else {
3275        s.no().or(&Formula::some(decls, &sum.equals(s)))
3276    }
3277}
3278
3279fn extract_always_inductive(f: &Formula) -> Option<(Option<Formula>, Formula, bool)> {
3280    use elinvar_logic::{FormulaKind, TemporalOp};
3281    match f.kind() {
3282        FormulaKind::Temporal(TemporalOp::Always, inner) if !inner.is_temporal() => {
3283            Some((None, inner.clone(), false))
3284        }
3285        FormulaKind::Temporal(TemporalOp::Always, inner) if is_one_step_formula(inner) => {
3286            Some((None, inner.clone(), true))
3287        }
3288        FormulaKind::And(fs) if fs.len() == 1 => extract_always_inductive(&fs[0]),
3289        FormulaKind::Implies(a, b) if !a.is_temporal() => {
3290            let (extra, p, is_trans) = extract_always_inductive(b)?;
3291            let init = match extra {
3292                Some(e) => a.and(&e),
3293                None => a.clone(),
3294            };
3295            Some((Some(init), p, is_trans))
3296        }
3297        _ => None,
3298    }
3299}
3300
3301fn flatten_and_conjuncts(f: &Formula, out: &mut Vec<Formula>) {
3302    match f.kind() {
3303        elinvar_logic::FormulaKind::And(fs) => {
3304            for sub in fs {
3305                flatten_and_conjuncts(sub, out);
3306            }
3307        }
3308        _ => out.push(f.clone()),
3309    }
3310}
3311
3312fn formula_mentions_changing(f: &Formula) -> bool {
3313    use elinvar_logic::{ExprKind, FormulaKind, IntExprKind};
3314    fn expr_ch(e: &Expr) -> bool {
3315        match e.kind() {
3316            ExprKind::Relation(r) => r.is_changing(),
3317            ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
3318            ExprKind::Unary(_, a) | ExprKind::Prime(a) => expr_ch(a),
3319            ExprKind::Binary(_, a, b) => expr_ch(a) || expr_ch(b),
3320            ExprKind::Comprehension(decls, body) => {
3321                decls.iter().any(|d| expr_ch(&d.expr)) || formula_mentions_changing(body)
3322            }
3323            ExprKind::IfThenElse(c, a, b) => {
3324                formula_mentions_changing(c) || expr_ch(a) || expr_ch(b)
3325            }
3326            ExprKind::IntToSet(i) => int_ch(i),
3327        }
3328    }
3329    fn int_ch(i: &elinvar_logic::IntExpr) -> bool {
3330        match i.kind() {
3331            IntExprKind::Constant(_) => false,
3332            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_ch(e),
3333            IntExprKind::Binary(_, a, b) => int_ch(a) || int_ch(b),
3334            IntExprKind::Negate(a) => int_ch(a),
3335            IntExprKind::IfThenElse(c, a, b) => {
3336                formula_mentions_changing(c) || int_ch(a) || int_ch(b)
3337            }
3338            IntExprKind::SumOver(decls, body) => {
3339                decls.iter().any(|d| expr_ch(&d.expr)) || int_ch(body)
3340            }
3341        }
3342    }
3343    match f.kind() {
3344        FormulaKind::Constant(_) => false,
3345        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => expr_ch(a) || expr_ch(b),
3346        FormulaKind::Multiplicity(_, e) => expr_ch(e),
3347        FormulaKind::Not(a) | FormulaKind::Temporal(_, a) => formula_mentions_changing(a),
3348        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(formula_mentions_changing),
3349        FormulaKind::Implies(a, b)
3350        | FormulaKind::Iff(a, b)
3351        | FormulaKind::TemporalBinary(_, a, b) => {
3352            formula_mentions_changing(a) || formula_mentions_changing(b)
3353        }
3354        FormulaKind::Quantified(_, decls, body) => {
3355            decls.iter().any(|d| expr_ch(&d.expr)) || formula_mentions_changing(body)
3356        }
3357        FormulaKind::IntCompare(_, a, b) => int_ch(a) || int_ch(b),
3358    }
3359}
3360
3361/// Whether `f` reads only the current and next state (primes or depth-1
3362/// `after`, with no `always`/`eventually`/`until`/past operators).
3363fn is_one_step_formula(f: &Formula) -> bool {
3364    use elinvar_logic::{ExprKind, FormulaKind, IntExprKind, TemporalOp};
3365    fn expr_non_temporal(e: &Expr) -> bool {
3366        match e.kind() {
3367            ExprKind::Relation(_)
3368            | ExprKind::Variable(_)
3369            | ExprKind::None
3370            | ExprKind::Univ
3371            | ExprKind::Iden => true,
3372            ExprKind::Prime(_) => false,
3373            ExprKind::Unary(_, a) => expr_non_temporal(a),
3374            ExprKind::Binary(_, a, b) => expr_non_temporal(a) && expr_non_temporal(b),
3375            ExprKind::Comprehension(decls, body) => {
3376                decls.iter().all(|d| expr_non_temporal(&d.expr)) && !body.is_temporal()
3377            }
3378            ExprKind::IfThenElse(c, a, b) => {
3379                !c.is_temporal() && expr_non_temporal(a) && expr_non_temporal(b)
3380            }
3381            ExprKind::IntToSet(i) => int_non_temporal(i),
3382        }
3383    }
3384    fn int_non_temporal(i: &elinvar_logic::IntExpr) -> bool {
3385        match i.kind() {
3386            IntExprKind::Constant(_) => true,
3387            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_non_temporal(e),
3388            IntExprKind::Binary(_, a, b) => int_non_temporal(a) && int_non_temporal(b),
3389            IntExprKind::Negate(a) => int_non_temporal(a),
3390            IntExprKind::IfThenElse(c, a, b) => {
3391                !c.is_temporal() && int_non_temporal(a) && int_non_temporal(b)
3392            }
3393            IntExprKind::SumOver(decls, body) => {
3394                decls.iter().all(|d| expr_non_temporal(&d.expr)) && int_non_temporal(body)
3395            }
3396        }
3397    }
3398    fn expr_ok(e: &Expr) -> bool {
3399        match e.kind() {
3400            ExprKind::Relation(_)
3401            | ExprKind::Variable(_)
3402            | ExprKind::None
3403            | ExprKind::Univ
3404            | ExprKind::Iden => true,
3405            ExprKind::Prime(inner) => expr_non_temporal(inner),
3406            ExprKind::Unary(_, a) => expr_ok(a),
3407            ExprKind::Binary(_, a, b) => expr_ok(a) && expr_ok(b),
3408            ExprKind::Comprehension(decls, body) => {
3409                decls.iter().all(|d| expr_ok(&d.expr)) && is_one_step_formula(body)
3410            }
3411            ExprKind::IfThenElse(c, a, b) => is_one_step_formula(c) && expr_ok(a) && expr_ok(b),
3412            ExprKind::IntToSet(i) => int_ok(i),
3413        }
3414    }
3415    fn int_ok(i: &elinvar_logic::IntExpr) -> bool {
3416        match i.kind() {
3417            IntExprKind::Constant(_) => true,
3418            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_ok(e),
3419            IntExprKind::Binary(_, a, b) => int_ok(a) && int_ok(b),
3420            IntExprKind::Negate(a) => int_ok(a),
3421            IntExprKind::IfThenElse(c, a, b) => is_one_step_formula(c) && int_ok(a) && int_ok(b),
3422            IntExprKind::SumOver(decls, body) => {
3423                decls.iter().all(|d| expr_ok(&d.expr)) && int_ok(body)
3424            }
3425        }
3426    }
3427    match f.kind() {
3428        FormulaKind::Constant(_) => true,
3429        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => expr_ok(a) && expr_ok(b),
3430        FormulaKind::Multiplicity(_, e) => expr_ok(e),
3431        FormulaKind::Not(a) => is_one_step_formula(a),
3432        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(is_one_step_formula),
3433        FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
3434            is_one_step_formula(a) && is_one_step_formula(b)
3435        }
3436        FormulaKind::Quantified(_, decls, body) => {
3437            decls.iter().all(|d| expr_ok(&d.expr)) && is_one_step_formula(body)
3438        }
3439        FormulaKind::Temporal(TemporalOp::After, inner) => !inner.is_temporal(),
3440        FormulaKind::Temporal(_, _) | FormulaKind::TemporalBinary(_, _, _) => false,
3441        FormulaKind::IntCompare(_, a, b) => int_ok(a) && int_ok(b),
3442    }
3443}