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    /// Symmetry breaking on or off (DESIGN.md section 7.5); on by default.
1707    pub fn symmetry_breaking(mut self, on: bool) -> Command<'m> {
1708        self.options.symmetry_breaking = on;
1709        self
1710    }
1711
1712    /// Maximum entries compared per symmetry pair (default 20, as in Alloy).
1713    pub fn predicate_length(mut self, length: usize) -> Command<'m> {
1714        self.options.predicate_length = length;
1715        self
1716    }
1717
1718    /// Forbid signed integer overflow (Alloy `noOverflow`); off by default.
1719    pub fn no_overflow(mut self, on: bool) -> Command<'m> {
1720        self.options.no_overflow = on;
1721        self
1722    }
1723
1724    /// Search options: symmetry breaking and the budget.
1725    pub fn options(mut self, options: Options) -> Command<'m> {
1726        self.options = options;
1727        self
1728    }
1729
1730    /// The bounds the scopes give (LOGIC.md 12.9).
1731    ///
1732    /// Errors: `model.no_scope`, `model.not_a_set`.
1733    pub fn bounds(&self) -> Result<Bounds, Vec<Error>> {
1734        let (sizes, has_ints) = self.validate_bounds_inputs()?;
1735        let (u, ranges) = self.build_universe(&sizes, has_ints)?;
1736        let (set_lower, set_upper) = self.compute_set_bounds(&sizes, &ranges);
1737        let mut b = Bounds::new(&u);
1738        self.bind_sets(&mut b, &u, &set_lower, &set_upper)?;
1739        self.bind_relations(&mut b, &u, &set_upper)?;
1740        self.bind_orderings(&mut b, &u, &ranges)?;
1741        Ok(b)
1742    }
1743
1744    #[allow(clippy::type_complexity)]
1745    fn validate_bounds_inputs(&self) -> Result<(Vec<(usize, bool)>, bool), Vec<Error>> {
1746        let m = self.model;
1747        let mut errors = m.errors.clone();
1748        errors.extend(self.errors.iter().cloned());
1749        let mut sizes: Vec<(usize, bool)> = Vec::new();
1750        for (i, s) in m.sets.iter().enumerate() {
1751            let size = match (&s.kind, self.size_of(i)) {
1752                (SetKind::Sub { .. }, _) => (0, false),
1753                (_, Some(size)) => size,
1754                (_, None) => {
1755                    errors.push(model_error(
1756                        "model.no_scope",
1757                        format!("`{}` has no scope", s.relation),
1758                    ));
1759                    (0, false)
1760                }
1761            };
1762            sizes.push(size);
1763        }
1764        for (e, _, _) in &self.scopes {
1765            // A top-level set, or one that extends another (LOGIC.md 12.9).
1766            let top = m
1767                .index_of(e)
1768                .is_some_and(|i| !matches!(m.sets[i].kind, SetKind::Sub { extends: false, .. }));
1769            if !top {
1770                errors.push(model_error(
1771                    "model.not_a_set",
1772                    format!("`{e}` is given a scope but is not a top-level set of the model"),
1773                ));
1774            }
1775        }
1776        let has_ints = m.sets.iter().any(|s| s.ints);
1777        if has_ints && self.bitwidth > 16 {
1778            errors.push(model_error(
1779                "model.bitwidth",
1780                format!(
1781                    "a bitwidth of {} would give `Int` 2^{} atoms",
1782                    self.bitwidth, self.bitwidth
1783                ),
1784            ));
1785        }
1786        if self.options.steps == 0 {
1787            errors.push(model_error(
1788                "model.invalid_steps",
1789                "a command asks for 0 steps; a trace needs at least 1 state".to_string(),
1790            ));
1791        }
1792        // B35: reject absurdly large scopes before allocating atom pools.
1793        const MAX_SCOPE_ATOMS: usize = 4096;
1794        let non_int_atoms: usize = m
1795            .sets
1796            .iter()
1797            .zip(&sizes)
1798            .filter(|(s, _)| !s.ints && !matches!(s.kind, SetKind::Sub { .. }))
1799            .fold(0usize, |acc, (_, &(k, _))| acc.saturating_add(k));
1800        if non_int_atoms > MAX_SCOPE_ATOMS {
1801            errors.push(model_error(
1802                "model.scope_too_large",
1803                format!("scope asks for {non_int_atoms} atoms (maximum is {MAX_SCOPE_ATOMS})"),
1804            ));
1805        }
1806        if !errors.is_empty() {
1807            return Err(errors);
1808        }
1809        Ok((sizes, has_ints))
1810    }
1811
1812    fn build_universe(
1813        &self,
1814        sizes: &[(usize, bool)],
1815        has_ints: bool,
1816    ) -> Result<(Universe, Vec<std::ops::Range<u64>>), Vec<Error>> {
1817        let m = self.model;
1818        let mut names = Vec::new();
1819        let mut ranges = Vec::new();
1820        let mut ints: Vec<(String, i64)> = Vec::new();
1821        for (s, &(k, _)) in m.sets.iter().zip(sizes) {
1822            let start = names.len() as u64;
1823            if s.ints {
1824                // LOGIC.md 16.1: one atom per integer, named by it.
1825                let least = -(1i64 << (self.bitwidth.max(1) - 1));
1826                for j in 0..k as i64 {
1827                    let name = (least + j).to_string();
1828                    ints.push((name.clone(), least + j));
1829                    names.push(name);
1830                }
1831            } else if !matches!(s.kind, SetKind::Sub { .. }) {
1832                for j in 0..k {
1833                    names.push(format!("{}{j}", s.relation.name()));
1834                }
1835            }
1836            ranges.push(start..names.len() as u64);
1837        }
1838        if names.is_empty() {
1839            names.push("unused".to_string());
1840        }
1841        let strip = |mut e: Error| {
1842            e.place = None;
1843            vec![e]
1844        };
1845        let u = Universe::new(names).map_err(strip)?;
1846        let u = if has_ints || self.bitwidth != elinvar_logic::DEFAULT_BITWIDTH {
1847            let pairs: Vec<(&str, i64)> = ints.iter().map(|(n, v)| (n.as_str(), *v)).collect();
1848            u.with_ints(self.bitwidth, &pairs).map_err(strip)?
1849        } else {
1850            u
1851        };
1852        Ok((u, ranges))
1853    }
1854
1855    fn compute_set_bounds(
1856        &self,
1857        sizes: &[(usize, bool)],
1858        ranges: &[std::ops::Range<u64>],
1859    ) -> (Vec<Vec<u64>>, Vec<Vec<u64>>) {
1860        let m = self.model;
1861        // Tight lower and upper atom lists per set (LOGIC.md 12.9): static
1862        // exact extensions of an unordered top-level set get disjoint exact
1863        // atoms, as Alloy's BoundsComputer assigns them.
1864        let mut set_lower: Vec<Vec<u64>> = (0..m.sets.len())
1865            .map(|i| {
1866                if sizes[i].1 {
1867                    ranges[i].clone().collect()
1868                } else {
1869                    Vec::new()
1870                }
1871            })
1872            .collect();
1873        let mut set_upper: Vec<Vec<u64>> = (0..m.sets.len())
1874            .map(|i| ranges[m.top(i)].clone().collect())
1875            .collect();
1876        for (top, s) in m.sets.iter().enumerate() {
1877            if matches!(s.kind, SetKind::Sub { .. }) || m.is_non_enum_ordered(top) || s.ints {
1878                continue;
1879            }
1880            if let Some((lo, hi)) = self.extends_bounds(top, ranges[top].clone(), sizes[top].1) {
1881                for (i, atoms) in lo {
1882                    set_lower[i] = atoms;
1883                }
1884                for (i, atoms) in hi {
1885                    set_upper[i] = atoms;
1886                }
1887            }
1888        }
1889        for (i, s) in m.sets.iter().enumerate() {
1890            if let SetKind::Sub {
1891                parent,
1892                extends: false,
1893            } = s.kind
1894            {
1895                set_upper[i] = set_upper[parent].clone();
1896            }
1897        }
1898        (set_lower, set_upper)
1899    }
1900
1901    fn bind_sets(
1902        &self,
1903        b: &mut Bounds,
1904        u: &Universe,
1905        set_lower: &[Vec<u64>],
1906        set_upper: &[Vec<u64>],
1907    ) -> Result<(), Vec<Error>> {
1908        let make_set = |atoms: &[u64]| -> Result<TupleSet, Error> {
1909            let mut t = TupleSet::empty(u, 1)?;
1910            for &a in atoms {
1911                t.insert_index(a)?;
1912            }
1913            Ok(t)
1914        };
1915        let at_place = |place: &Option<Place>| {
1916            let p = place.clone();
1917            move |mut e: Error| {
1918                e.place = p;
1919                vec![e]
1920            }
1921        };
1922        for (i, s) in self.model.sets.iter().enumerate() {
1923            let lower = make_set(&set_lower[i]).map_err(at_place(&s.place))?;
1924            let upper = make_set(&set_upper[i]).map_err(at_place(&s.place))?;
1925            b.bound(&s.relation, lower, upper)
1926                .map_err(at_place(&s.place))?;
1927        }
1928        Ok(())
1929    }
1930
1931    fn bind_relations(
1932        &self,
1933        b: &mut Bounds,
1934        u: &Universe,
1935        set_upper: &[Vec<u64>],
1936    ) -> Result<(), Vec<Error>> {
1937        let m = self.model;
1938        let n = u.size() as u64;
1939        let at_place = |place: &Option<Place>| {
1940            let p = place.clone();
1941            move |mut e: Error| {
1942                e.place = p;
1943                vec![e]
1944            }
1945        };
1946        // Each possible tuple of a relation is a solver variable, so a
1947        // relation of high arity at a large scope would exhaust memory before
1948        // any budget is consulted (AGENTS.md law 22). Count them first.
1949        const MAX_UPPER_TUPLES: u64 = 1 << 24;
1950        let column_atoms = |c: &[usize]| -> u64 {
1951            let mut atoms: Vec<u64> = c
1952                .iter()
1953                .flat_map(|&i| set_upper[i].iter().copied())
1954                .collect();
1955            atoms.sort_unstable();
1956            atoms.dedup();
1957            atoms.len() as u64
1958        };
1959        let mut total: u64 = 0;
1960        for r in &m.relations {
1961            let tuples = r
1962                .columns
1963                .iter()
1964                .fold(1u64, |acc, c| acc.saturating_mul(column_atoms(c)));
1965            total = total.saturating_add(tuples);
1966            if total > MAX_UPPER_TUPLES {
1967                let mut e = model_error(
1968                    "model.scope_too_large",
1969                    format!(
1970                        "the scope gives {} possible tuples over the relations up to `{}`, \
1971                         which has {tuples} (maximum is {MAX_UPPER_TUPLES})",
1972                        total,
1973                        r.relation.name()
1974                    ),
1975                );
1976                e.place = r.place.clone();
1977                return Err(vec![e]);
1978            }
1979        }
1980        for r in &m.relations {
1981            let mut upper = TupleSet::empty(u, r.columns.len()).map_err(at_place(&r.place))?;
1982            let mut indices = vec![0u64];
1983            for c in &r.columns {
1984                let mut atoms: Vec<u64> = Vec::new();
1985                for &i in c {
1986                    for &a in &set_upper[i] {
1987                        if !atoms.contains(&a) {
1988                            atoms.push(a);
1989                        }
1990                    }
1991                }
1992                atoms.sort_unstable();
1993                indices = indices
1994                    .iter()
1995                    .flat_map(|&i| atoms.iter().map(move |&a| i * n + a))
1996                    .collect();
1997            }
1998            for i in indices {
1999                upper.insert_index(i).map_err(at_place(&r.place))?;
2000            }
2001            b.bound_upper(&r.relation, upper)
2002                .map_err(at_place(&r.place))?;
2003        }
2004        Ok(())
2005    }
2006
2007    fn bind_orderings(
2008        &self,
2009        b: &mut Bounds,
2010        u: &Universe,
2011        ranges: &[std::ops::Range<u64>],
2012    ) -> Result<(), Vec<Error>> {
2013        let m = self.model;
2014        let n = u.size() as u64;
2015        let at_place = |place: &Option<Place>| {
2016            let p = place.clone();
2017            move |mut e: Error| {
2018                e.place = p;
2019                vec![e]
2020            }
2021        };
2022        // LOGIC.md 12.9: an ordering follows its set's atoms in order; one
2023        // on a subset ranges over its top-level set's atoms.
2024        for (o, first, next, _) in &m.orderings {
2025            let (i, union) = match *o {
2026                Ordered::Set(i) => (i, None),
2027                Ordered::Union(j) => (m.relations[j].columns[0][0], Some(j)),
2028            };
2029            let place = match union {
2030                Some(j) => &m.relations[j].place,
2031                None => &m.sets[i].place,
2032            };
2033            if union.is_some() || matches!(m.sets[i].kind, SetKind::Sub { .. }) {
2034                // A subset of a union ranges over its sets' top-level sets.
2035                let mut tops: Vec<usize> = match union {
2036                    Some(j) => m.relations[j].columns[0]
2037                        .iter()
2038                        .map(|&c| m.top(c))
2039                        .collect(),
2040                    None => vec![m.top(i)],
2041                };
2042                tops.sort_unstable();
2043                tops.dedup();
2044                let atoms: Vec<u64> = tops.iter().flat_map(|&t| ranges[t].clone()).collect();
2045                let mut f = TupleSet::empty(u, 1).map_err(at_place(place))?;
2046                let mut nx = TupleSet::empty(u, 2).map_err(at_place(place))?;
2047                for &a in &atoms {
2048                    f.insert_index(a).map_err(at_place(place))?;
2049                    for &c in &atoms {
2050                        nx.insert_index(a * n + c).map_err(at_place(place))?;
2051                    }
2052                }
2053                b.bound_upper(first, f).map_err(at_place(place))?;
2054                b.bound_upper(next, nx).map_err(at_place(place))?;
2055                continue;
2056            }
2057            let atoms: Vec<u64> = ranges[i].clone().collect();
2058            let mut f = TupleSet::empty(u, 1).map_err(at_place(place))?;
2059            let mut nx = TupleSet::empty(u, 2).map_err(at_place(place))?;
2060            if let Some(&a) = atoms.first() {
2061                f.insert_index(a).map_err(at_place(place))?;
2062            }
2063            for w in atoms.windows(2) {
2064                nx.insert_index(w[0] * n + w[1]).map_err(at_place(place))?;
2065            }
2066            b.bound_exactly(first, f).map_err(at_place(place))?;
2067            b.bound_exactly(next, nx).map_err(at_place(place))?;
2068        }
2069        Ok(())
2070    }
2071
2072    /// Assigns disjoint exact atoms to static `one` and `exactly k`
2073    /// extensions of an unordered top-level set `top`, as Alloy's
2074    /// `BoundsComputer.computeLowerBound` and `computeUpperBound` do.
2075    /// Returns `None` if any set in the extension tree changes over time or
2076    /// if the requested exact sizes conflict with the available atoms.
2077    #[allow(clippy::type_complexity)]
2078    fn extends_bounds(
2079        &self,
2080        top: usize,
2081        range: std::ops::Range<u64>,
2082        top_exact: bool,
2083    ) -> Option<(Vec<(usize, Vec<u64>)>, Vec<(usize, Vec<u64>)>)> {
2084        let m = self.model;
2085        let ext_children = |parent: usize| -> Vec<usize> { m.extensions(parent).collect() };
2086        // Collect every set in `top`'s extension tree; skip if any changes.
2087        let mut tree = vec![top];
2088        let mut cursor = 0;
2089        while cursor < tree.len() {
2090            let cur = tree[cursor];
2091            cursor += 1;
2092            if m.sets[cur].relation.is_changing() {
2093                return None;
2094            }
2095            tree.extend(ext_children(cur));
2096        }
2097        let exact_target = |j: usize| -> Option<usize> {
2098            if j == top {
2099                return None;
2100            }
2101            if m.sets[j].one {
2102                return Some(1);
2103            }
2104            self.own_scope(j).and_then(|(k, exact)| exact.then_some(k))
2105        };
2106        if !tree.iter().any(|&j| exact_target(j).is_some()) {
2107            return None;
2108        }
2109        let mut pool: std::collections::VecDeque<u64> = range.clone().collect();
2110        let mut lower: BTreeMap<usize, Vec<u64>> = BTreeMap::new();
2111        fn compute_lower(
2112            node: usize,
2113            ext_children: &dyn Fn(usize) -> Vec<usize>,
2114            exact_target: &dyn Fn(usize) -> Option<usize>,
2115            pool: &mut std::collections::VecDeque<u64>,
2116            lower: &mut BTreeMap<usize, Vec<u64>>,
2117        ) -> Option<Vec<u64>> {
2118            let mut atoms = Vec::new();
2119            for c in ext_children(node) {
2120                atoms.extend(compute_lower(c, ext_children, exact_target, pool, lower)?);
2121            }
2122            if let Some(k) = exact_target(node) {
2123                if k < atoms.len() {
2124                    return None;
2125                }
2126                let need = k - atoms.len();
2127                if need > pool.len() {
2128                    return None;
2129                }
2130                for _ in 0..need {
2131                    atoms.push(pool.pop_front()?);
2132                }
2133            }
2134            atoms.sort_unstable();
2135            lower.insert(node, atoms.clone());
2136            Some(atoms)
2137        }
2138        compute_lower(top, &ext_children, &exact_target, &mut pool, &mut lower)?;
2139        if top_exact {
2140            lower.insert(top, range.clone().collect());
2141        }
2142        let mut upper: BTreeMap<usize, Vec<u64>> = BTreeMap::new();
2143        upper.insert(top, range.collect());
2144        fn compute_upper(
2145            node: usize,
2146            ext_children: &dyn Fn(usize) -> Vec<usize>,
2147            exact_target: &dyn Fn(usize) -> Option<usize>,
2148            lower: &BTreeMap<usize, Vec<u64>>,
2149            upper: &mut BTreeMap<usize, Vec<u64>>,
2150        ) {
2151            let children = ext_children(node);
2152            let mut claimed: Vec<u64> = children
2153                .iter()
2154                .flat_map(|c| lower[c].iter().copied())
2155                .collect();
2156            claimed.sort_unstable();
2157            let free: Vec<u64> = upper[&node]
2158                .iter()
2159                .copied()
2160                .filter(|a| claimed.binary_search(a).is_err())
2161                .collect();
2162            for c in children {
2163                let hi = if exact_target(c).is_some() {
2164                    lower[&c].clone()
2165                } else {
2166                    let mut u = lower[&c].clone();
2167                    u.extend(&free);
2168                    u.sort_unstable();
2169                    u
2170                };
2171                upper.insert(c, hi);
2172                compute_upper(c, ext_children, exact_target, lower, upper);
2173            }
2174        }
2175        compute_upper(top, &ext_children, &exact_target, &lower, &mut upper);
2176        Some((lower.into_iter().collect(), upper.into_iter().collect()))
2177    }
2178
2179    /// The command's target formula (predicate for `run`, assertion for `check`).
2180    #[must_use]
2181    pub fn formula(&self) -> &Formula {
2182        &self.formula
2183    }
2184
2185    /// Runs the command with the default solver.
2186    ///
2187    /// Errors: those of [`Command::bounds`], then every error of the
2188    /// formulas.
2189    pub fn solve(&self) -> Result<Outcome, Vec<Error>> {
2190        self.solve_with(crate::sat::Cdcl::new)
2191    }
2192
2193    /// Returns an iterator over every instance (or trace) of this command up to
2194    /// symmetry breaking within its scope (N16, R13). Each item is refereed by
2195    /// `elinvar-logic` before being yielded.
2196    ///
2197    /// Errors: those of [`Command::bounds`], then every error of the formulas.
2198    pub fn iter_instances(&self) -> Result<InstanceIter, Vec<Error>> {
2199        let bounds = self.bounds()?;
2200        let facts = self.facts_for(Some(&bounds));
2201        let opts = self.effective_options(&facts);
2202        let formula = if self.is_check {
2203            facts.and(&self.formula.not())
2204        } else {
2205            facts.and(&self.formula)
2206        };
2207        let finder = crate::solve::Finder::new(&bounds, &formula, &opts)?;
2208        Ok(InstanceIter {
2209            finder,
2210            done: false,
2211            hit_budget: false,
2212        })
2213    }
2214
2215    /// Runs the command with a solver built by `make_solver` (R9,
2216    /// DESIGN.md section 7.4). Every returned instance or trace is still
2217    /// refereed by `elinvar-logic`.
2218    ///
2219    /// Errors: those of [`Command::bounds`], then every error of the
2220    /// formulas.
2221    /// B8: when every conjunct of `facts` is either non-temporal or a pure
2222    /// state invariant `always P` (with `P` free of temporal operators and
2223    /// primes), and the command formula itself is free of temporal operators
2224    /// and primes, any valid state extends to a 1-state stuttering trace, so
2225    /// 1 step suffices.
2226    fn effective_options(&self, facts: &Formula) -> Options {
2227        fn is_state_or_always_state(f: &Formula) -> bool {
2228            use elinvar_logic::{FormulaKind, TemporalOp};
2229            if !f.is_temporal() {
2230                return true;
2231            }
2232            match f.kind() {
2233                FormulaKind::And(fs) => fs.iter().all(is_state_or_always_state),
2234                FormulaKind::Temporal(TemporalOp::Always, inner) => !inner.is_temporal(),
2235                _ => false,
2236            }
2237        }
2238        let mut opts = self.options;
2239        if opts.steps > 1 && !self.formula.is_temporal() && is_state_or_always_state(facts) {
2240            opts.steps = 1;
2241        }
2242        opts
2243    }
2244
2245    /// Attempts a `k`-induction proof without falling back to bounded trace
2246    /// checking or counterexample shrinking when induction does not close (W23).
2247    ///
2248    /// Returns:
2249    /// - `Ok(Some(out))` when induction proved the assertion (`Verdict::Proved`),
2250    ///   found the model vacuous (`Verdict::Vacuous`), or ran out of budget
2251    ///   (`Verdict::Unknown`);
2252    /// - `Ok(None)` when the base case or inductive step failed to close.
2253    ///
2254    /// ```
2255    /// use elinvar_engine::{Model, Verdict};
2256    ///
2257    /// let mut m = Model::new();
2258    /// let item = m.set("Item");
2259    /// let kept = m.changing_subset("kept", &item);
2260    /// m.fact(kept.no());
2261    /// m.fact(kept.is_in(&kept.prime()).always());
2262    /// let out = m
2263    ///     .check(&kept.is_in(&kept.prime()).always())
2264    ///     .scope(2)
2265    ///     .prove_by_induction(1)
2266    ///     .unwrap()
2267    ///     .unwrap();
2268    /// assert_eq!(out.verdict, Verdict::Proved);
2269    /// ```
2270    pub fn prove_by_induction(&self, k: usize) -> Result<Option<Outcome>, Vec<Error>> {
2271        if !self.is_check {
2272            return Ok(None);
2273        }
2274        let bounds = self.bounds()?;
2275        let facts = self.facts_for(Some(&bounds));
2276        let opts = self.effective_options(&facts);
2277        let mut make_solver = crate::sat::Cdcl::new;
2278        match self.try_inductive(&bounds, &facts, k.max(1), &opts, &mut make_solver)? {
2279            Ok(out) => Ok(Some(out)),
2280            Err(note) if note.contains("ran out of budget") => Ok(Some(Outcome {
2281                verdict: crate::solve::Verdict::Unknown,
2282                instance: None,
2283                trace: None,
2284                labels: Vec::new(),
2285                note: Some(note),
2286                stats: crate::solve::Stats::default(),
2287            })),
2288            Err(_) => Ok(None),
2289        }
2290    }
2291
2292    pub fn solve_with<S, F>(&self, mut make_solver: F) -> Result<Outcome, Vec<Error>>
2293    where
2294        S: crate::sat::Solver + 'static,
2295        F: FnMut() -> S,
2296    {
2297        let bounds = self.bounds()?;
2298        let facts = self.facts_for(Some(&bounds));
2299        let opts = self.effective_options(&facts);
2300        let mut fallback_note: Option<String> = None;
2301        if self.is_check
2302            && let Some(k) = self.inductive
2303        {
2304            match self.try_inductive(&bounds, &facts, k, &opts, &mut make_solver)? {
2305                Ok(out) => return Ok(out),
2306                Err(note) => fallback_note = Some(note),
2307            }
2308        }
2309        let mut out = if self.is_check {
2310            if let Some(coi_out) =
2311                crate::coi::try_check_coi(&bounds, &facts, &self.formula, &opts, &mut make_solver)?
2312            {
2313                coi_out
2314            } else {
2315                check_with_solver(&bounds, &facts, &self.formula, &opts, make_solver)?
2316            }
2317        } else {
2318            run_with_solver(&bounds, &facts.and(&self.formula), &opts, make_solver)?
2319        };
2320        if let Some(trace) = &out.trace {
2321            out.labels = self.model.labels_with(trace, &self.extra_step_labels);
2322        }
2323        if out.note.is_none() {
2324            out.note = fallback_note;
2325        }
2326        Ok(out)
2327    }
2328
2329    /// Attempts a k-induction proof of `self.formula` (N9).
2330    /// Returns `Ok(Ok(outcome))` when induction settles the check (`Proved` or
2331    /// `Vacuous`), or `Ok(Err(note))` when induction does not close and the
2332    /// caller should fall back to bounded trace checking with `note`.
2333    fn try_inductive<S, F>(
2334        &self,
2335        bounds: &Bounds,
2336        facts: &Formula,
2337        k: usize,
2338        opts: &Options,
2339        make_solver: &mut F,
2340    ) -> Result<Result<Outcome, String>, Vec<Error>>
2341    where
2342        S: crate::sat::Solver + 'static,
2343        F: FnMut() -> S,
2344    {
2345        use crate::solve::{Next, Stats, Verdict, solve_fixed_states};
2346
2347        let Some((extra_init, prop, is_transition)) = extract_always_inductive(&self.formula)
2348        else {
2349            return Ok(Err(
2350                "induction applies only to promises of the form `always P` (where P reads one state or one transition); fell back to bounded traces"
2351                    .to_string(),
2352            ));
2353        };
2354
2355        let mut helper_parts = Vec::new();
2356        for h in &self.using_invariants {
2357            if let Some((None, hp, false)) = extract_always_inductive(h) {
2358                helper_parts.push(hp);
2359            } else if !h.is_temporal() {
2360                helper_parts.push(h.clone());
2361            } else {
2362                return Ok(Err(
2363                    "helper invariant in `using` must be a state invariant `always Q`; fell back to bounded traces"
2364                        .to_string(),
2365                ));
2366            }
2367        }
2368        let joint = if is_transition {
2369            prop.clone()
2370        } else {
2371            let mut all = vec![prop.clone()];
2372            all.extend(helper_parts.iter().cloned());
2373            Formula::and_all(all)
2374        };
2375        let helpers_joint = if helper_parts.is_empty() {
2376            None
2377        } else {
2378            Some(Formula::and_all(helper_parts))
2379        };
2380
2381        let mut coi_seed_parts = vec![joint.clone()];
2382        if let Some(h) = &helpers_joint {
2383            coi_seed_parts.push(h.clone());
2384        }
2385        if let Some(ei) = &extra_init {
2386            coi_seed_parts.push(ei.clone());
2387        }
2388        let coi_seed = Formula::and_all(coi_seed_parts);
2389        let coi_part = crate::coi::partition_coi(bounds, facts, &coi_seed, opts);
2390        let eff_bounds = coi_part.as_ref().map_or(bounds, |p| &p.coi_bounds);
2391        let eff_facts = coi_part.as_ref().map_or(facts, |p| &p.coi_facts);
2392
2393        let mut static_facts = Vec::new();
2394        let mut init_only = Vec::new();
2395        let mut state_invs = Vec::new();
2396        let mut step_rels = Vec::new();
2397        let mut conjuncts = Vec::new();
2398        flatten_and_conjuncts(eff_facts, &mut conjuncts);
2399        for c in conjuncts {
2400            if !c.is_temporal() {
2401                if formula_mentions_changing(&c) {
2402                    init_only.push(c);
2403                } else {
2404                    static_facts.push(c);
2405                }
2406            } else if let elinvar_logic::FormulaKind::Temporal(
2407                elinvar_logic::TemporalOp::Always,
2408                inner,
2409            ) = c.kind()
2410            {
2411                if !inner.is_temporal() {
2412                    state_invs.push(inner.clone());
2413                } else if is_one_step_formula(inner) {
2414                    step_rels.push(inner.clone());
2415                } else {
2416                    return Ok(Err(
2417                        "model has multi-step or liveness temporal facts outside induction; fell back to bounded traces"
2418                            .to_string(),
2419                    ));
2420                }
2421            } else {
2422                return Ok(Err(
2423                    "model has non-invariant temporal facts outside induction; fell back to bounded traces"
2424                        .to_string(),
2425                ));
2426            }
2427        }
2428
2429        let state_inv = Formula::and_all(state_invs);
2430        let step_rel = Formula::and_all(step_rels);
2431        let static_f = Formula::and_all(static_facts);
2432        let init_f = Formula::and_all(init_only);
2433
2434        let after_n = |f: &Formula, n: usize| -> Formula {
2435            let mut cur = f.clone();
2436            for _ in 0..n {
2437                cur = cur.after();
2438            }
2439            cur
2440        };
2441
2442        let mut total_stats = Stats::default();
2443
2444        // Step 1: Base case. State invariants need `k` states (`0..k`);
2445        // 1-step transition invariants need `k + 1` states (`0..=k`) to cover `k` transitions.
2446        let base_states = if is_transition { k + 1 } else { k };
2447        let mut base_parts = vec![static_f.clone(), init_f.clone()];
2448        for t in 0..base_states {
2449            base_parts.push(after_n(&state_inv, t));
2450        }
2451        for t in 0..base_states.saturating_sub(1) {
2452            base_parts.push(after_n(&step_rel, t));
2453        }
2454        let base_facts = Formula::and_all(base_parts);
2455        let base_check_facts = match &extra_init {
2456            Some(ei) => base_facts.and(ei),
2457            None => base_facts.clone(),
2458        };
2459        let mut base_bad_arms: Vec<Formula> = (0..k).map(|t| after_n(&joint, t).not()).collect();
2460        if is_transition && let Some(h) = &helpers_joint {
2461            for t in 0..base_states {
2462                base_bad_arms.push(after_n(h, t).not());
2463            }
2464        }
2465        // B69: share one wall-clock deadline across base case, inductive step,
2466        // non-vacuity check, and COI witness check.
2467        let ind_deadline = opts.budget.time.map(|d| std::time::Instant::now() + d);
2468        let rem_opts = |base: Options| -> Option<Options> {
2469            match ind_deadline {
2470                Some(d) => {
2471                    let rem = d.checked_duration_since(std::time::Instant::now())?;
2472                    if rem.is_zero() {
2473                        return None;
2474                    }
2475                    let mut o = base;
2476                    o.budget.time = Some(rem);
2477                    Some(o)
2478                }
2479                None => Some(base),
2480            }
2481        };
2482        let base_bad = Formula::or_all(base_bad_arms);
2483        let (base_next, st1) = solve_fixed_states(
2484            eff_bounds,
2485            &base_check_facts.and(&base_bad),
2486            base_states,
2487            opts,
2488            &mut *make_solver,
2489        )?;
2490        total_stats.primary_variables = total_stats.primary_variables.max(st1.primary_variables);
2491        total_stats.gates = total_stats.gates.max(st1.gates);
2492        total_stats.conflicts += st1.conflicts;
2493
2494        match base_next {
2495            Next::Unknown => {
2496                return Ok(Err(
2497                    "induction base case ran out of budget; fell back to bounded traces"
2498                        .to_string(),
2499                ));
2500            }
2501            Next::Instance(_) | Next::Trace(_) => {
2502                return Ok(Err(
2503                    "induction base case failed; checking bounded traces for a counterexample"
2504                        .to_string(),
2505                ));
2506            }
2507            Next::Done => {}
2508        }
2509
2510        let Some(step_opts) = rem_opts(*opts) else {
2511            return Ok(Err(
2512                "induction step ran out of time budget; fell back to bounded traces".to_string(),
2513            ));
2514        };
2515
2516        // Step 2: Inductive step over k + 1 states (0..=k) from an arbitrary state 0.
2517        // Run before the non-vacuity witness check so non-inductive candidates fail
2518        // fast without paying for an extra SAT solve (W23).
2519        let mut step_parts = vec![static_f];
2520        for t in 0..=k {
2521            step_parts.push(after_n(&state_inv, t));
2522        }
2523        for t in 0..k {
2524            step_parts.push(after_n(&step_rel, t));
2525        }
2526        let step_bad = if is_transition {
2527            for t in 0..(k - 1) {
2528                step_parts.push(after_n(&joint, t));
2529            }
2530            let mut bad_arms = vec![after_n(&joint, k - 1).not()];
2531            if let Some(h) = &helpers_joint {
2532                for t in 0..k {
2533                    step_parts.push(after_n(h, t));
2534                }
2535                bad_arms.push(after_n(h, k).not());
2536            }
2537            Formula::or_all(bad_arms)
2538        } else {
2539            for t in 0..k {
2540                step_parts.push(after_n(&joint, t));
2541            }
2542            after_n(&joint, k).not()
2543        };
2544        let step_facts = Formula::and_all(step_parts);
2545        let (step_next, st2) = solve_fixed_states(
2546            eff_bounds,
2547            &step_facts.and(&step_bad),
2548            k + 1,
2549            &step_opts,
2550            &mut *make_solver,
2551        )?;
2552        total_stats.primary_variables = total_stats.primary_variables.max(st2.primary_variables);
2553        total_stats.gates = total_stats.gates.max(st2.gates);
2554        total_stats.conflicts += st2.conflicts;
2555
2556        match step_next {
2557            Next::Done => {
2558                // Verify `eff_facts` admits a real infinite lasso trace (without
2559                // `extra_init`) so neither deadlocking initial states nor
2560                // unsatisfiable assertion premises can give a false Vacuous/Proved.
2561                // Fast path: solve `base_facts` (no `fact trace`) and referee its
2562                // 1-state stuttering trace against `eff_facts` in ~1 ms; only fall
2563                // back to full lasso solving when the base witness cannot stutter.
2564                let Some(vac_opts0) = rem_opts(*opts) else {
2565                    return Ok(Err(
2566                        "induction non-vacuity check ran out of time budget; fell back to bounded traces"
2567                            .to_string(),
2568                    ));
2569                };
2570                let (vac_fast, st_vf) = solve_fixed_states(
2571                    eff_bounds,
2572                    &base_facts,
2573                    base_states,
2574                    &vac_opts0,
2575                    &mut *make_solver,
2576                )?;
2577                total_stats.conflicts += st_vf.conflicts;
2578                let fast_ok = match &vac_fast {
2579                    Next::Instance(inst) => {
2580                        elinvar_logic::evaluate_trace(
2581                            &elinvar_logic::Trace::of_instance(inst),
2582                            eff_facts,
2583                        ) == Ok(true)
2584                    }
2585                    Next::Trace(tr) => {
2586                        tr.states().first().is_some_and(|s0| {
2587                            let mut inst = tr.fixed().clone();
2588                            for (rel, ts) in s0.entries() {
2589                                if rel.is_changing() {
2590                                    let _ = inst.set(rel, ts.clone());
2591                                }
2592                            }
2593                            elinvar_logic::evaluate_trace(
2594                                &elinvar_logic::Trace::of_instance(&inst),
2595                                eff_facts,
2596                            ) == Ok(true)
2597                        })
2598                    }
2599                    Next::Done | Next::Unknown => false,
2600                };
2601                if !fast_ok {
2602                    let Some(mut vac_opts) = rem_opts(*opts) else {
2603                        return Ok(Err(
2604                            "induction non-vacuity check ran out of time budget; fell back to bounded traces"
2605                                .to_string(),
2606                        ));
2607                    };
2608                    vac_opts.steps = 1;
2609                    let mut vac_out =
2610                        run_with_solver(eff_bounds, eff_facts, &vac_opts, &mut *make_solver)?;
2611                    total_stats.conflicts += vac_out.stats.conflicts;
2612                    if vac_out.verdict == Verdict::None {
2613                        let Some(mut vac_opts2) = rem_opts(*opts) else {
2614                            return Ok(Err(
2615                                "induction non-vacuity check ran out of time budget; fell back to bounded traces"
2616                                    .to_string(),
2617                            ));
2618                        };
2619                        vac_opts2.steps = opts.steps.max(2);
2620                        vac_out =
2621                            run_with_solver(eff_bounds, eff_facts, &vac_opts2, &mut *make_solver)?;
2622                        total_stats.conflicts += vac_out.stats.conflicts;
2623                    }
2624                    match vac_out.verdict {
2625                        Verdict::Found => {}
2626                        Verdict::None => {
2627                            return Ok(Ok(Outcome {
2628                                verdict: Verdict::Vacuous,
2629                                instance: None,
2630                                trace: None,
2631                                labels: Vec::new(),
2632                                note: None,
2633                                stats: total_stats,
2634                            }));
2635                        }
2636                        _ => {
2637                            return Ok(Err(
2638                                "induction could not confirm a non-vacuous trace; fell back to bounded traces"
2639                                    .to_string(),
2640                            ));
2641                        }
2642                    }
2643                }
2644                // W25: when COI dropped unrelated tables, confirm the dropped
2645                // component admits a 1-state stuttering witness so we never
2646                // mask a vacuous dropped component as `Proved`.
2647                if let Some(part) = &coi_part {
2648                    let Some(coi_opts) = rem_opts(*opts) else {
2649                        return Ok(Err(
2650                            "dropped COI witness check ran out of time budget; fell back to bounded traces"
2651                                .to_string(),
2652                        ));
2653                    };
2654                    if part
2655                        .find_dropped_stutter_witness(bounds, &coi_opts, &mut *make_solver)?
2656                        .is_none()
2657                    {
2658                        return Ok(Err(
2659                            "dropped COI component could not confirm a 1-state witness; fell back to bounded traces"
2660                                .to_string(),
2661                        ));
2662                    }
2663                }
2664                let kind = if k == 1 {
2665                    "induction".to_string()
2666                } else {
2667                    format!("{k}-induction")
2668                };
2669                Ok(Ok(Outcome {
2670                    verdict: Verdict::Proved,
2671                    instance: None,
2672                    trace: None,
2673                    labels: Vec::new(),
2674                    note: Some(format!("proved for any number of steps by {kind}")),
2675                    stats: total_stats,
2676                }))
2677            }
2678            Next::Trace(t) => {
2679                let labels = self.model.labels_with(&t, &self.extra_step_labels);
2680                let step_desc = labels
2681                    .get(k - 1)
2682                    .and_then(|l| l.action.as_ref())
2683                    .map(|a| format!(" (action `{a}`)"))
2684                    .unwrap_or_default();
2685                Ok(Err(format!(
2686                    "inductive step failed{step_desc} from a possibly unreachable state; fell back to bounded traces"
2687                )))
2688            }
2689            Next::Instance(_) => Ok(Err(
2690                "inductive step failed from a possibly unreachable state; fell back to bounded traces"
2691                    .to_string(),
2692            )),
2693            Next::Unknown => Ok(Err(
2694                "inductive step ran out of budget; fell back to bounded traces".to_string(),
2695            )),
2696        }
2697    }
2698
2699    /// Explains why a `check` command holds (or is vacuous) within its scope
2700    /// by extracting a minimal unsatisfiable core of the model's named rules
2701    /// (REQUIREMENTS.md section 8). Returns `Ok(None)` if a counterexample
2702    /// exists, if this is a `run` command, or if the budget runs out.
2703    ///
2704    /// When the rules alone are unsatisfiable (`vacuous`), explains why the
2705    /// rules contradict each other without conjoining `!assertion`.
2706    pub fn explain_holds(&self) -> Result<Option<HoldsCore>, Vec<Error>> {
2707        if !self.is_check {
2708            return Ok(None);
2709        }
2710        let mut remaining = self
2711            .options
2712            .budget
2713            .conflicts
2714            .unwrap_or(crate::solve::DEFAULT_CONFLICTS);
2715        let bounds = self.bounds()?;
2716        let mut rules = self.model.named_facts();
2717        rules.extend(self.scope_facts(Some(&bounds)));
2718        rules.extend(self.extra_facts.iter().cloned());
2719        let facts = self.facts_for(Some(&bounds));
2720        let opts = self.effective_options(&facts);
2721        let mut make_solver = crate::sat::Cdcl::new;
2722
2723        // W25: when COI drops unrelated tables and the dropped component has a
2724        // 1-state stuttering witness, both vacuity and assertion core extraction
2725        // run strictly on the smaller COI slice.
2726        if let Some(part) = crate::coi::partition_coi(&bounds, &facts, &self.formula, &opts)
2727            && part
2728                .find_dropped_stutter_witness(&bounds, &opts, &mut make_solver)?
2729                .is_some()
2730        {
2731            let coi_rules = part.project_named_rules(&rules);
2732            if let crate::solve::CoreResult::Complete(core) = crate::solve::explain_core_budgeted(
2733                &part.coi_bounds,
2734                &coi_rules,
2735                &Formula::falsity(),
2736                &opts,
2737                &mut remaining,
2738            )? {
2739                return Ok(Some(core));
2740            }
2741            let res = crate::solve::explain_core_budgeted(
2742                &part.coi_bounds,
2743                &coi_rules,
2744                &self.formula,
2745                &opts,
2746                &mut remaining,
2747            )?;
2748            if let crate::solve::CoreResult::Complete(mut core) = res {
2749                if self
2750                    .refine_guard_core(
2751                        &part.coi_bounds,
2752                        &coi_rules,
2753                        &opts,
2754                        &mut core,
2755                        &mut remaining,
2756                        Some(&part),
2757                    )
2758                    .is_some()
2759                {
2760                    return Ok(None);
2761                }
2762                return Ok(Some(core));
2763            }
2764            return Ok(None);
2765        }
2766
2767        if let crate::solve::CoreResult::Complete(core) =
2768            self.explain_vacuous_budgeted(&mut remaining)?
2769        {
2770            return Ok(Some(core));
2771        }
2772        match self.explain_assertion_budgeted(&mut remaining)? {
2773            crate::solve::CoreResult::Complete(core) => Ok(Some(core)),
2774            _ => Ok(None),
2775        }
2776    }
2777
2778    pub(crate) fn explain_vacuous_budgeted(
2779        &self,
2780        remaining: &mut u64,
2781    ) -> Result<crate::solve::CoreResult, Vec<Error>> {
2782        if !self.is_check {
2783            return Ok(crate::solve::CoreResult::NotUnsat);
2784        }
2785        let bounds = self.bounds()?;
2786        let mut rules = self.model.named_facts();
2787        rules.extend(self.scope_facts(Some(&bounds)));
2788        rules.extend(self.extra_facts.iter().cloned());
2789        let facts = self.facts_for(Some(&bounds));
2790        let opts = self.effective_options(&facts);
2791        crate::solve::explain_core_budgeted(&bounds, &rules, &Formula::falsity(), &opts, remaining)
2792    }
2793
2794    /// Why a `run` has no instance within its scope (REQUIREMENTS.md
2795    /// section 8): a minimal core of the named rules that, with the run's
2796    /// own constraint, admits none, or, when the rules alone admit none,
2797    /// a minimal core of the rules alone, with `true` beside it.
2798    pub(crate) fn explain_no_instance_budgeted(
2799        &self,
2800        remaining: &mut u64,
2801    ) -> Result<(crate::solve::CoreResult, bool), Vec<Error>> {
2802        if self.is_check {
2803            return Ok((crate::solve::CoreResult::NotUnsat, false));
2804        }
2805        let bounds = self.bounds()?;
2806        let mut rules = self.model.named_facts();
2807        rules.extend(self.scope_facts(Some(&bounds)));
2808        rules.extend(self.extra_facts.iter().cloned());
2809        let facts = self.facts_for(Some(&bounds));
2810        let opts = self.effective_options(&facts);
2811        let alone = crate::solve::explain_core_budgeted(
2812            &bounds,
2813            &rules,
2814            &Formula::falsity(),
2815            &opts,
2816            remaining,
2817        )?;
2818        if !matches!(alone, crate::solve::CoreResult::NotUnsat) {
2819            return Ok((alone, true));
2820        }
2821        // No instance of F is a check of `not F`.
2822        let with_run = crate::solve::explain_core_budgeted(
2823            &bounds,
2824            &rules,
2825            &self.formula.not(),
2826            &opts,
2827            remaining,
2828        )?;
2829        Ok((with_run, false))
2830    }
2831
2832    pub(crate) fn explain_assertion_budgeted(
2833        &self,
2834        remaining: &mut u64,
2835    ) -> Result<crate::solve::CoreResult, Vec<Error>> {
2836        if !self.is_check {
2837            return Ok(crate::solve::CoreResult::NotUnsat);
2838        }
2839        let bounds = self.bounds()?;
2840        let mut rules = self.model.named_facts();
2841        rules.extend(self.scope_facts(Some(&bounds)));
2842        rules.extend(self.extra_facts.iter().cloned());
2843        let facts = self.facts_for(Some(&bounds));
2844        let opts = self.effective_options(&facts);
2845        let coi_part = crate::coi::partition_coi(&bounds, &facts, &self.formula, &opts);
2846        let (eff_bounds, eff_rules, eff_part) = if let Some(part) = &coi_part {
2847            (
2848                &part.coi_bounds,
2849                part.project_named_rules(&rules),
2850                Some(part),
2851            )
2852        } else {
2853            (&bounds, rules, None)
2854        };
2855        let res = crate::solve::explain_core_budgeted(
2856            eff_bounds,
2857            &eff_rules,
2858            &self.formula,
2859            &opts,
2860            remaining,
2861        )?;
2862        match res {
2863            crate::solve::CoreResult::Complete(mut core) => {
2864                // N14 & B13: refine any transition fact in `core.used` down to individual
2865                // step guards under the same shared conflict budget.
2866                if let Some(note) = self.refine_guard_core(
2867                    eff_bounds, &eff_rules, &opts, &mut core, remaining, eff_part,
2868                ) {
2869                    Ok(crate::solve::CoreResult::Incomplete {
2870                        core: Some(core),
2871                        note,
2872                    })
2873                } else {
2874                    Ok(crate::solve::CoreResult::Complete(core))
2875                }
2876            }
2877            other => Ok(other),
2878        }
2879    }
2880
2881    fn refine_guard_core(
2882        &self,
2883        bounds: &Bounds,
2884        rules: &[(String, Formula)],
2885        opts: &Options,
2886        core: &mut HoldsCore,
2887        remaining: &mut u64,
2888        coi_part: Option<&crate::coi::CoiPartition>,
2889    ) -> Option<String> {
2890        if self.model.step_specs.is_empty() {
2891            return None;
2892        }
2893        fn extract_init_conjuncts(f: &Formula, out: &mut Vec<Formula>) {
2894            match f.kind() {
2895                elinvar_logic::FormulaKind::And(fs) => {
2896                    for g in fs {
2897                        extract_init_conjuncts(g, out);
2898                    }
2899                }
2900                elinvar_logic::FormulaKind::Temporal(elinvar_logic::TemporalOp::Always, _) => {}
2901                _ => out.push(f.clone()),
2902            }
2903        }
2904        // Group step specs by their transition fact name.
2905        let mut by_fact: BTreeMap<String, Vec<&StepSpec>> = BTreeMap::new();
2906        for s in &self.model.step_specs {
2907            by_fact.entry(s.fact_name.clone()).or_default().push(s);
2908        }
2909        for (fact_name, specs) in by_fact {
2910            if !core.used.contains(&fact_name) {
2911                continue;
2912            }
2913            if specs.iter().all(|s| s.guards.is_empty()) {
2914                continue;
2915            }
2916            let other_used: Vec<Formula> = rules
2917                .iter()
2918                .filter(|(n, _)| n != &fact_name && core.used.contains(n))
2919                .map(|(_, f)| f.clone())
2920                .collect();
2921            let mut init_conjuncts = Vec::new();
2922            for (n, f) in rules {
2923                if n == &fact_name {
2924                    extract_init_conjuncts(f, &mut init_conjuncts);
2925                }
2926            }
2927            let extras: Vec<Formula> = self
2928                .model
2929                .transition_extras
2930                .get(&fact_name)
2931                .cloned()
2932                .unwrap_or_default()
2933                .into_iter()
2934                .filter_map(|arm| match coi_part {
2935                    Some(part) => part.strip_arm_to_coi(&arm),
2936                    None => Some(arm),
2937                })
2938                .collect();
2939            let specs: Vec<&StepSpec> = if let Some(part) = coi_part {
2940                specs
2941                    .into_iter()
2942                    .filter(|s| part.strip_arm_to_coi(&s.full_arm()).is_some())
2943                    .collect()
2944            } else {
2945                specs
2946            };
2947
2948            let rebuild = |active: &[Vec<bool>], include_init: bool| -> Formula {
2949                let mut arms = extras.clone();
2950                for (spec, flags) in specs.iter().zip(active) {
2951                    let arm = spec.with_active_guards(flags);
2952                    if let Some(part) = coi_part {
2953                        if let Some(stripped) = part.strip_arm_to_coi(&arm) {
2954                            arms.push(stripped);
2955                        }
2956                    } else {
2957                        arms.push(arm);
2958                    }
2959                }
2960                let trans = Formula::or_all(arms).always();
2961                if include_init && !init_conjuncts.is_empty() {
2962                    let mut parts = init_conjuncts.clone();
2963                    parts.push(trans);
2964                    Formula::and_all(parts)
2965                } else {
2966                    trans
2967                }
2968            };
2969
2970            let mut active: Vec<Vec<bool>> =
2971                specs.iter().map(|s| vec![true; s.guards.len()]).collect();
2972
2973            let probe =
2974                |parts: Vec<Formula>, remaining: &mut u64| -> Option<crate::solve::Verdict> {
2975                    if *remaining == 0 {
2976                        return Some(crate::solve::Verdict::Unknown);
2977                    }
2978                    let mut check_opts = *opts;
2979                    check_opts.budget = crate::sat::Budget {
2980                        conflicts: Some(*remaining),
2981                        time: opts.budget.time,
2982                    };
2983                    let out = run_with_solver(
2984                        bounds,
2985                        &Formula::and_all(parts),
2986                        &check_opts,
2987                        crate::sat::Cdcl::new,
2988                    )
2989                    .ok()?;
2990                    *remaining = remaining.saturating_sub(out.stats.conflicts);
2991                    Some(out.verdict)
2992                };
2993
2994            // Verify our reconstructed transition fact (with init conjuncts!)
2995            // matches the UNSAT core before testing guards.
2996            let mut base_parts = other_used.clone();
2997            base_parts.push(rebuild(&active, true));
2998            base_parts.push(self.formula.not());
2999            match probe(base_parts, remaining) {
3000                Some(crate::solve::Verdict::None) => {}
3001                Some(crate::solve::Verdict::Unknown) => {
3002                    return Some("guard core refinement did not finish within budget".to_string());
3003                }
3004                _ => continue,
3005            }
3006
3007            let mut needed_guards = Vec::new();
3008            let mut unused_guards = Vec::new();
3009            for (si, spec) in specs.iter().enumerate() {
3010                for (gi, guard) in spec.guards.iter().enumerate() {
3011                    active[si][gi] = false;
3012                    let mut trial_parts = other_used.clone();
3013                    trial_parts.push(rebuild(&active, true));
3014                    trial_parts.push(self.formula.not());
3015                    let label = format!("{}: `{}`", spec.name, guard.label);
3016                    match probe(trial_parts, remaining) {
3017                        Some(crate::solve::Verdict::None) => {
3018                            unused_guards.push(label);
3019                        }
3020                        Some(crate::solve::Verdict::Unknown) => {
3021                            active[si][gi] = true;
3022                            return Some(
3023                                "guard core refinement did not finish within budget".to_string(),
3024                            );
3025                        }
3026                        _ => {
3027                            active[si][gi] = true;
3028                            needed_guards.push(label);
3029                        }
3030                    }
3031                }
3032            }
3033            let init_needed = if !init_conjuncts.is_empty() && !needed_guards.is_empty() {
3034                let mut trial_parts = other_used.clone();
3035                trial_parts.push(rebuild(&active, false));
3036                trial_parts.push(self.formula.not());
3037                !matches!(
3038                    probe(trial_parts, remaining),
3039                    Some(crate::solve::Verdict::None)
3040                )
3041            } else {
3042                false
3043            };
3044            if !needed_guards.is_empty()
3045                && let Some(pos) = core.used.iter().position(|n| n == &fact_name)
3046            {
3047                core.used.remove(pos);
3048                let mut replacements = Vec::new();
3049                if init_needed {
3050                    replacements.push(format!("{fact_name} (init)"));
3051                }
3052                replacements.extend(needed_guards);
3053                for (offset, g) in replacements.into_iter().enumerate() {
3054                    core.used.insert(pos + offset, g);
3055                }
3056            }
3057            for g in unused_guards {
3058                if !core.unused.contains(&g) {
3059                    core.unused.push(g);
3060                }
3061            }
3062        }
3063        None
3064    }
3065
3066    /// N13: checks whether a `holds` or `proved` check held without using any
3067    /// rule of the model (`model.trivial_holds`) or because its implication
3068    /// premise can never be satisfied (`model.vacuous_premise`).
3069    pub(crate) fn holds_warnings<S, F>(&self, make_solver: &mut F) -> Vec<Error>
3070    where
3071        S: crate::sat::Solver + 'static,
3072        F: FnMut() -> S,
3073    {
3074        if !self.is_check {
3075            return Vec::new();
3076        }
3077        let Ok(bounds) = self.bounds() else {
3078            return Vec::new();
3079        };
3080        let facts = self.facts_for(Some(&bounds));
3081        let mut out = Vec::new();
3082        let cap = |b: crate::sat::Budget| -> crate::sat::Budget {
3083            let max_c = 50_000u64;
3084            let c = b.conflicts.map_or(max_c, |v| v.min(max_c));
3085            crate::sat::Budget {
3086                conflicts: Some(c),
3087                time: b.time,
3088            }
3089        };
3090
3091        // 1. Rule-free holds: `!assertion` is UNSAT under bounds alone (no facts).
3092        // W27/W29: with no facts, only relations mentioned in each decomposed
3093        // obligation matter, and `!(always P)` for non-temporal `P` is SAT iff
3094        // `!P` is SAT in 1 step.
3095        let (triv_assert, triv_single_step) = match self.formula.kind() {
3096            elinvar_logic::FormulaKind::Temporal(elinvar_logic::TemporalOp::Always, inner)
3097                if !inner.is_temporal() =>
3098            {
3099                (inner.clone(), true)
3100            }
3101            _ => (self.formula.clone(), !self.formula.is_temporal()),
3102        };
3103        let mut triv_opts = self.effective_options(&Formula::truth());
3104        if triv_single_step {
3105            triv_opts.steps = 1;
3106        }
3107        triv_opts.budget = cap(triv_opts.budget);
3108        let triv_obligations = if triv_single_step {
3109            crate::coi::decompose_check_obligations(&triv_assert)
3110        } else {
3111            vec![triv_assert]
3112        };
3113        let mut all_triv_unsat = !triv_obligations.is_empty();
3114        for ob in &triv_obligations {
3115            let neg_ob = ob.not();
3116            let triv_proj = crate::coi::project_bounds_for_formula(&bounds, &neg_ob);
3117            let triv_bounds = triv_proj.as_ref().unwrap_or(&bounds);
3118            match run_with_solver(triv_bounds, &neg_ob, &triv_opts, &mut *make_solver) {
3119                Ok(res) if res.verdict == crate::solve::Verdict::None => {}
3120                _ => {
3121                    all_triv_unsat = false;
3122                    break;
3123                }
3124            }
3125        }
3126        if all_triv_unsat {
3127            out.push(
3128                model_error(
3129                    "model.trivial_holds",
3130                    format!(
3131                        "assertion `{}` holds from bounds alone without using any rule of the model",
3132                        self.name
3133                    ),
3134                )
3135                .at(self.formula.place().clone()),
3136            );
3137        }
3138
3139        // 2. Vacuous premise: for `A implies B` (under optional `always` / `all`),
3140        //    check whether `A` can ever hold in any allowed case.
3141        //    W27: `facts and eventually P` is UNSAT iff `facts => always (not P)`
3142        //    holds, so reuse `try_check_coi` to drop unread tables and collapse
3143        //    stutter-admitting transitions before falling back to full solving.
3144        if let Some(witness) = premise_witness(&self.formula) {
3145            let mut prem_opts = self.effective_options(&facts);
3146            prem_opts.budget = cap(prem_opts.budget);
3147            let neg_witness = match witness.kind() {
3148                elinvar_logic::FormulaKind::Temporal(
3149                    elinvar_logic::TemporalOp::Eventually,
3150                    inner,
3151                ) if !inner.is_temporal() => inner.not().always(),
3152                _ => witness.not(),
3153            };
3154            use crate::solve::Verdict as V;
3155            // `Some(true)` the premise never holds, `Some(false)` it can,
3156            // `None` the capped budget ran out before either was known.
3157            let vacuous = match crate::coi::try_check_coi(
3158                &bounds,
3159                &facts,
3160                &neg_witness,
3161                &prem_opts,
3162                &mut *make_solver,
3163            ) {
3164                Ok(Some(res)) if res.verdict == V::Unknown => None,
3165                Ok(Some(res)) => Some(res.verdict == V::Holds),
3166                _ => {
3167                    let prem_part =
3168                        crate::coi::partition_coi(&bounds, &facts, &witness, &prem_opts);
3169                    let (p_bounds, p_facts) = prem_part
3170                        .as_ref()
3171                        .map_or((&bounds, &facts), |p| (&p.coi_bounds, &p.coi_facts));
3172                    match run_with_solver(
3173                        p_bounds,
3174                        &p_facts.and(&witness),
3175                        &prem_opts,
3176                        &mut *make_solver,
3177                    ) {
3178                        Ok(res) if res.verdict == V::Unknown => None,
3179                        Ok(res) => Some(res.verdict == V::None),
3180                        // The check's own solve reports the error.
3181                        Err(_) => Some(false),
3182                    }
3183                }
3184            };
3185            if vacuous.is_none() {
3186                // AGENTS.md laws 14 and 20: a `holds` over a premise that may
3187                // never happen is not left to look like a plain `holds`.
3188                out.push(
3189                    model_error(
3190                        "model.premise_unknown",
3191                        format!(
3192                            "whether the premise of `{}` can ever be satisfied was not found \
3193                             within {} conflicts, so this `holds` may be vacuous",
3194                            self.name,
3195                            prem_opts.budget.conflicts.unwrap_or(0)
3196                        ),
3197                    )
3198                    .at(self.formula.place().clone()),
3199                );
3200            }
3201            if vacuous == Some(true) {
3202                out.push(
3203                    model_error(
3204                        "model.vacuous_premise",
3205                        format!(
3206                            "the premise of `{}` is never satisfied in any allowed case within the scope",
3207                            self.name
3208                        ),
3209                    )
3210                    .at(self.formula.place().clone()),
3211                );
3212            }
3213        }
3214        out
3215    }
3216}
3217
3218/// Extracts a formula that witnesses the premise of an implication promise
3219/// being satisfied at least once (N13).
3220fn premise_witness(f: &Formula) -> Option<Formula> {
3221    use elinvar_logic::{FormulaKind, Quantifier, TemporalOp};
3222    match f.kind() {
3223        FormulaKind::Implies(a, b) => {
3224            if let Some(inner) = premise_witness(b) {
3225                Some(a.and(&inner))
3226            } else {
3227                Some(a.clone())
3228            }
3229        }
3230        FormulaKind::Quantified(Quantifier::All, decls, body) => {
3231            let inner = premise_witness(body)?;
3232            Some(Formula::some(decls.clone(), &inner))
3233        }
3234        FormulaKind::Temporal(TemporalOp::Always, inner) => {
3235            let w = premise_witness(inner)?;
3236            Some(w.eventually())
3237        }
3238        FormulaKind::And(fs) if fs.len() == 1 => premise_witness(&fs[0]),
3239        _ => None,
3240    }
3241}
3242
3243impl Model {
3244    /// LOGIC.md 13.5: each step of the trace, labelled with the first
3245    /// action or registered step predicate and arguments that happen at it,
3246    /// trying command-scoped `extra` step predicates before model-wide
3247    /// `step_labels`, and leaving no-change steps unlabelled (`nothing changes`)
3248    /// for Alloy-text models (B12).
3249    pub(crate) fn labels_with(&self, trace: &Trace, extra: &[Action]) -> Vec<StepLabel> {
3250        let candidates: Vec<&Action> = self
3251            .actions
3252            .iter()
3253            .chain(extra)
3254            .chain(&self.step_labels)
3255            .collect();
3256        if candidates.is_empty() {
3257            return (0..trace.states().len())
3258                .map(|_| StepLabel {
3259                    action: None,
3260                    args: Vec::new(),
3261                })
3262                .collect();
3263        }
3264        let states = trace.states();
3265        (0..states.len())
3266            .map(|k| {
3267                // B12: when using Alloy-text step labels (`self.actions.is_empty()`),
3268                // a step where no changing relation actually changes is always
3269                // `nothing changes`, never an idempotent write predicate.
3270                if self.actions.is_empty() {
3271                    let to = if k + 1 < states.len() {
3272                        k + 1
3273                    } else {
3274                        trace.loop_to()
3275                    };
3276                    let any_changed = states[k]
3277                        .entries()
3278                        .any(|(r, now)| states[to].get(r).is_some_and(|next| next != now));
3279                    if !any_changed {
3280                        return StepLabel {
3281                            action: None,
3282                            args: Vec::new(),
3283                        };
3284                    }
3285                }
3286                for a in &candidates {
3287                    let mut domains: Vec<Vec<usize>> = Vec::with_capacity(a.vars.len());
3288                    let mut empty = false;
3289                    for r in &a.ranges {
3290                        let atoms: Vec<usize> = match evaluate_trace_expr_at(trace, r, k) {
3291                            Ok(ts) => ts.indices().map(|i| i as usize).collect(),
3292                            Err(_) => Vec::new(),
3293                        };
3294                        if atoms.is_empty() {
3295                            empty = true;
3296                            break;
3297                        }
3298                        domains.push(atoms);
3299                    }
3300                    if empty {
3301                        continue;
3302                    }
3303                    let total: usize = domains
3304                        .iter()
3305                        .try_fold(1usize, |acc, d| acc.checked_mul(d.len()))
3306                        .unwrap_or(0);
3307                    // Cap combinatorial enumeration per step so large scopes stay fast.
3308                    if total == 0 || total > 1024 {
3309                        continue;
3310                    }
3311                    for code in 0..total {
3312                        let mut atoms = vec![0usize; domains.len()];
3313                        let mut c = code;
3314                        for (slot, dom) in atoms.iter_mut().zip(&domains).rev() {
3315                            *slot = dom[c % dom.len()];
3316                            c /= dom.len();
3317                        }
3318                        let bindings: Vec<(Variable, usize)> =
3319                            a.vars.iter().cloned().zip(atoms.iter().copied()).collect();
3320                        if evaluate_trace_at(trace, &a.formula, k, &bindings) == Ok(true) {
3321                            return StepLabel {
3322                                action: Some(a.name.clone()),
3323                                args: atoms
3324                                    .iter()
3325                                    .map(|&x| {
3326                                        trace
3327                                            .universe()
3328                                            .atom(x)
3329                                            .expect("an atom of the universe")
3330                                            .to_string()
3331                                    })
3332                                    .collect(),
3333                            };
3334                        }
3335                    }
3336                }
3337                StepLabel {
3338                    action: None,
3339                    args: Vec::new(),
3340                }
3341            })
3342            .collect()
3343    }
3344}
3345
3346/// `s` has at most `k` atoms, or exactly `k`: `no s or some v1, ..., vk: s |
3347/// s = v1 + ... + vk`, the `vi` disjoint when exact, as Alloy's
3348/// `BoundsComputer.size` states it (LOGIC.md 12.9).
3349fn size_fact(s: &Expr, k: usize, exact: bool) -> Formula {
3350    match k {
3351        0 => return s.no(),
3352        1 => return if exact { s.one() } else { s.lone() },
3353        _ => {}
3354    }
3355    let vars: Vec<Variable> = (1..=k).map(|j| Variable::new(format!("v{j}"))).collect();
3356    let es: Vec<Expr> = vars.iter().map(Expr::variable).collect();
3357    let mut sum = es[0].clone();
3358    let mut disjoint = Vec::new();
3359    for e in &es[1..] {
3360        disjoint.push(e.intersection(&sum).no());
3361        sum = e.union(&sum);
3362    }
3363    let decls: Vec<Decl> = vars.iter().map(|v| Decl::new(v, s)).collect();
3364    if exact {
3365        Formula::some(decls, &sum.equals(s).and(&Formula::and_all(disjoint)))
3366    } else {
3367        s.no().or(&Formula::some(decls, &sum.equals(s)))
3368    }
3369}
3370
3371fn extract_always_inductive(f: &Formula) -> Option<(Option<Formula>, Formula, bool)> {
3372    use elinvar_logic::{FormulaKind, TemporalOp};
3373    match f.kind() {
3374        FormulaKind::Temporal(TemporalOp::Always, inner) if !inner.is_temporal() => {
3375            Some((None, inner.clone(), false))
3376        }
3377        FormulaKind::Temporal(TemporalOp::Always, inner) if is_one_step_formula(inner) => {
3378            Some((None, inner.clone(), true))
3379        }
3380        FormulaKind::And(fs) if fs.len() == 1 => extract_always_inductive(&fs[0]),
3381        FormulaKind::Implies(a, b) if !a.is_temporal() => {
3382            let (extra, p, is_trans) = extract_always_inductive(b)?;
3383            let init = match extra {
3384                Some(e) => a.and(&e),
3385                None => a.clone(),
3386            };
3387            Some((Some(init), p, is_trans))
3388        }
3389        _ => None,
3390    }
3391}
3392
3393fn flatten_and_conjuncts(f: &Formula, out: &mut Vec<Formula>) {
3394    match f.kind() {
3395        elinvar_logic::FormulaKind::And(fs) => {
3396            for sub in fs {
3397                flatten_and_conjuncts(sub, out);
3398            }
3399        }
3400        _ => out.push(f.clone()),
3401    }
3402}
3403
3404fn formula_mentions_changing(f: &Formula) -> bool {
3405    use elinvar_logic::{ExprKind, FormulaKind, IntExprKind};
3406    fn expr_ch(e: &Expr) -> bool {
3407        match e.kind() {
3408            ExprKind::Relation(r) => r.is_changing(),
3409            ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
3410            ExprKind::Unary(_, a) | ExprKind::Prime(a) => expr_ch(a),
3411            ExprKind::Binary(_, a, b) => expr_ch(a) || expr_ch(b),
3412            ExprKind::Comprehension(decls, body) => {
3413                decls.iter().any(|d| expr_ch(&d.expr)) || formula_mentions_changing(body)
3414            }
3415            ExprKind::IfThenElse(c, a, b) => {
3416                formula_mentions_changing(c) || expr_ch(a) || expr_ch(b)
3417            }
3418            ExprKind::IntToSet(i) => int_ch(i),
3419        }
3420    }
3421    fn int_ch(i: &elinvar_logic::IntExpr) -> bool {
3422        match i.kind() {
3423            IntExprKind::Constant(_) => false,
3424            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_ch(e),
3425            IntExprKind::Binary(_, a, b) => int_ch(a) || int_ch(b),
3426            IntExprKind::Negate(a) => int_ch(a),
3427            IntExprKind::IfThenElse(c, a, b) => {
3428                formula_mentions_changing(c) || int_ch(a) || int_ch(b)
3429            }
3430            IntExprKind::SumOver(decls, body) => {
3431                decls.iter().any(|d| expr_ch(&d.expr)) || int_ch(body)
3432            }
3433        }
3434    }
3435    match f.kind() {
3436        FormulaKind::Constant(_) => false,
3437        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => expr_ch(a) || expr_ch(b),
3438        FormulaKind::Multiplicity(_, e) => expr_ch(e),
3439        FormulaKind::Not(a) | FormulaKind::Temporal(_, a) => formula_mentions_changing(a),
3440        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(formula_mentions_changing),
3441        FormulaKind::Implies(a, b)
3442        | FormulaKind::Iff(a, b)
3443        | FormulaKind::TemporalBinary(_, a, b) => {
3444            formula_mentions_changing(a) || formula_mentions_changing(b)
3445        }
3446        FormulaKind::Quantified(_, decls, body) => {
3447            decls.iter().any(|d| expr_ch(&d.expr)) || formula_mentions_changing(body)
3448        }
3449        FormulaKind::IntCompare(_, a, b) => int_ch(a) || int_ch(b),
3450    }
3451}
3452
3453/// Whether `f` reads only the current and next state (primes or depth-1
3454/// `after`, with no `always`/`eventually`/`until`/past operators).
3455fn is_one_step_formula(f: &Formula) -> bool {
3456    use elinvar_logic::{ExprKind, FormulaKind, IntExprKind, TemporalOp};
3457    fn expr_non_temporal(e: &Expr) -> bool {
3458        match e.kind() {
3459            ExprKind::Relation(_)
3460            | ExprKind::Variable(_)
3461            | ExprKind::None
3462            | ExprKind::Univ
3463            | ExprKind::Iden => true,
3464            ExprKind::Prime(_) => false,
3465            ExprKind::Unary(_, a) => expr_non_temporal(a),
3466            ExprKind::Binary(_, a, b) => expr_non_temporal(a) && expr_non_temporal(b),
3467            ExprKind::Comprehension(decls, body) => {
3468                decls.iter().all(|d| expr_non_temporal(&d.expr)) && !body.is_temporal()
3469            }
3470            ExprKind::IfThenElse(c, a, b) => {
3471                !c.is_temporal() && expr_non_temporal(a) && expr_non_temporal(b)
3472            }
3473            ExprKind::IntToSet(i) => int_non_temporal(i),
3474        }
3475    }
3476    fn int_non_temporal(i: &elinvar_logic::IntExpr) -> bool {
3477        match i.kind() {
3478            IntExprKind::Constant(_) => true,
3479            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_non_temporal(e),
3480            IntExprKind::Binary(_, a, b) => int_non_temporal(a) && int_non_temporal(b),
3481            IntExprKind::Negate(a) => int_non_temporal(a),
3482            IntExprKind::IfThenElse(c, a, b) => {
3483                !c.is_temporal() && int_non_temporal(a) && int_non_temporal(b)
3484            }
3485            IntExprKind::SumOver(decls, body) => {
3486                decls.iter().all(|d| expr_non_temporal(&d.expr)) && int_non_temporal(body)
3487            }
3488        }
3489    }
3490    fn expr_ok(e: &Expr) -> bool {
3491        match e.kind() {
3492            ExprKind::Relation(_)
3493            | ExprKind::Variable(_)
3494            | ExprKind::None
3495            | ExprKind::Univ
3496            | ExprKind::Iden => true,
3497            ExprKind::Prime(inner) => expr_non_temporal(inner),
3498            ExprKind::Unary(_, a) => expr_ok(a),
3499            ExprKind::Binary(_, a, b) => expr_ok(a) && expr_ok(b),
3500            ExprKind::Comprehension(decls, body) => {
3501                decls.iter().all(|d| expr_ok(&d.expr)) && is_one_step_formula(body)
3502            }
3503            ExprKind::IfThenElse(c, a, b) => is_one_step_formula(c) && expr_ok(a) && expr_ok(b),
3504            ExprKind::IntToSet(i) => int_ok(i),
3505        }
3506    }
3507    fn int_ok(i: &elinvar_logic::IntExpr) -> bool {
3508        match i.kind() {
3509            IntExprKind::Constant(_) => true,
3510            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_ok(e),
3511            IntExprKind::Binary(_, a, b) => int_ok(a) && int_ok(b),
3512            IntExprKind::Negate(a) => int_ok(a),
3513            IntExprKind::IfThenElse(c, a, b) => is_one_step_formula(c) && int_ok(a) && int_ok(b),
3514            IntExprKind::SumOver(decls, body) => {
3515                decls.iter().all(|d| expr_ok(&d.expr)) && int_ok(body)
3516            }
3517        }
3518    }
3519    match f.kind() {
3520        FormulaKind::Constant(_) => true,
3521        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => expr_ok(a) && expr_ok(b),
3522        FormulaKind::Multiplicity(_, e) => expr_ok(e),
3523        FormulaKind::Not(a) => is_one_step_formula(a),
3524        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(is_one_step_formula),
3525        FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
3526            is_one_step_formula(a) && is_one_step_formula(b)
3527        }
3528        FormulaKind::Quantified(_, decls, body) => {
3529            decls.iter().all(|d| expr_ok(&d.expr)) && is_one_step_formula(body)
3530        }
3531        FormulaKind::Temporal(TemporalOp::After, inner) => !inner.is_temporal(),
3532        FormulaKind::Temporal(_, _) | FormulaKind::TemporalBinary(_, _, _) => false,
3533        FormulaKind::IntCompare(_, a, b) => int_ok(a) && int_ok(b),
3534    }
3535}