Skip to main content

elinvar_logic/
ast.rs

1//! Expressions and formulas (LOGIC.md sections 3 to 5).
2//!
3//! Building never fails (DESIGN.md section 6.4). A method that would make
4//! an ill-formed node records the error, with the caller's place, and
5//! returns a node without an arity. A node built from an ill-formed part is
6//! ill-formed too and records nothing of its own (LOGIC.md section 6).
7//!
8//! The syntax enums are exhaustive on purpose, unlike other growing types
9//! (AGENTS.md law 26): a new operator must fail to compile in every
10//! translation and evaluation that does not handle it yet.
11
12use crate::error::{Error, Place};
13use crate::relation::{Relation, Variable};
14use std::fmt;
15use std::sync::Arc;
16
17/// An operator on two expressions.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum BinaryOp {
20    /// `a + b`
21    Union,
22    /// `a & b`
23    Intersection,
24    /// `a - b`
25    Difference,
26    /// `a . b`
27    Join,
28    /// `a -> b`
29    Product,
30    /// `a ++ b`
31    Override,
32    /// `s <: a`
33    DomainRestriction,
34    /// `a :> s`
35    RangeRestriction,
36}
37
38impl BinaryOp {
39    /// How the operator is written.
40    pub fn symbol(self) -> &'static str {
41        match self {
42            BinaryOp::Union => "+",
43            BinaryOp::Intersection => "&",
44            BinaryOp::Difference => "-",
45            BinaryOp::Join => ".",
46            BinaryOp::Product => "->",
47            BinaryOp::Override => "++",
48            BinaryOp::DomainRestriction => "<:",
49            BinaryOp::RangeRestriction => ":>",
50        }
51    }
52}
53
54/// An operator on one binary expression.
55#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
56pub enum UnaryOp {
57    /// `~a`
58    Transpose,
59    /// `^a`
60    Closure,
61    /// `*a`
62    ReflexiveClosure,
63}
64
65impl UnaryOp {
66    /// How the operator is written.
67    pub fn symbol(self) -> &'static str {
68        match self {
69            UnaryOp::Transpose => "~",
70            UnaryOp::Closure => "^",
71            UnaryOp::ReflexiveClosure => "*",
72        }
73    }
74}
75
76/// A multiplicity of an expression: `some a`, `no a`, `one a`, `lone a`.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
78pub enum Multiplicity {
79    /// At least one tuple.
80    Some,
81    /// No tuple.
82    No,
83    /// Exactly one tuple.
84    One,
85    /// At most one tuple.
86    Lone,
87}
88
89impl Multiplicity {
90    /// How it is written.
91    pub fn keyword(self) -> &'static str {
92        match self {
93            Multiplicity::Some => "some",
94            Multiplicity::No => "no",
95            Multiplicity::One => "one",
96            Multiplicity::Lone => "lone",
97        }
98    }
99}
100
101/// A quantifier (LOGIC.md section 4).
102#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
103pub enum Quantifier {
104    /// True under every binding.
105    All,
106    /// True under at least one binding.
107    Some,
108    /// True under no binding.
109    No,
110    /// True under exactly one binding.
111    One,
112    /// True under at most one binding.
113    Lone,
114}
115
116impl Quantifier {
117    /// How it is written.
118    pub fn keyword(self) -> &'static str {
119        match self {
120            Quantifier::All => "all",
121            Quantifier::Some => "some",
122            Quantifier::No => "no",
123            Quantifier::One => "one",
124            Quantifier::Lone => "lone",
125        }
126    }
127}
128
129/// A temporal operator on one formula (LOGIC.md section 13.2).
130#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
131pub enum TemporalOp {
132    /// `after F`: in the next state.
133    After,
134    /// `always F`: now and in every later state.
135    Always,
136    /// `eventually F`: now or in some later state.
137    Eventually,
138    /// `before F`: in the previous state, and there is one.
139    Before,
140    /// `historically F`: now and in every earlier state.
141    Historically,
142    /// `once F`: now or in some earlier state.
143    Once,
144}
145
146impl TemporalOp {
147    /// How it is written.
148    pub fn keyword(self) -> &'static str {
149        match self {
150            TemporalOp::After => "after",
151            TemporalOp::Always => "always",
152            TemporalOp::Eventually => "eventually",
153            TemporalOp::Before => "before",
154            TemporalOp::Historically => "historically",
155            TemporalOp::Once => "once",
156        }
157    }
158
159    /// Whether it looks back in time.
160    pub fn is_past(self) -> bool {
161        matches!(
162            self,
163            TemporalOp::Before | TemporalOp::Historically | TemporalOp::Once
164        )
165    }
166}
167
168/// A temporal operator on two formulas (LOGIC.md section 13.2).
169#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub enum TemporalBinaryOp {
171    /// `F until G`
172    Until,
173    /// `F releases G`
174    Releases,
175    /// `F since G`
176    Since,
177    /// `F triggered G`
178    Triggered,
179}
180
181impl TemporalBinaryOp {
182    /// How it is written.
183    pub fn keyword(self) -> &'static str {
184        match self {
185            TemporalBinaryOp::Until => "until",
186            TemporalBinaryOp::Releases => "releases",
187            TemporalBinaryOp::Since => "since",
188            TemporalBinaryOp::Triggered => "triggered",
189        }
190    }
191
192    /// Whether it looks back in time.
193    pub fn is_past(self) -> bool {
194        matches!(self, TemporalBinaryOp::Since | TemporalBinaryOp::Triggered)
195    }
196}
197
198/// How many tuples a declared variable holds (LOGIC.md section 5).
199#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
200pub enum DeclMult {
201    /// Exactly one: an atom, for a variable of arity 1.
202    One,
203    /// At most one tuple.
204    Lone,
205    /// At least one tuple.
206    Some,
207    /// Any number of tuples.
208    Set,
209}
210
211impl DeclMult {
212    /// How it is written.
213    pub fn keyword(self) -> &'static str {
214        match self {
215            DeclMult::One => "one",
216            DeclMult::Lone => "lone",
217            DeclMult::Some => "some",
218            DeclMult::Set => "set",
219        }
220    }
221
222    /// Whether a set of `n` tuples is allowed.
223    pub fn allows(self, n: usize) -> bool {
224        match self {
225            DeclMult::One => n == 1,
226            DeclMult::Lone => n <= 1,
227            DeclMult::Some => n >= 1,
228            DeclMult::Set => true,
229        }
230    }
231}
232
233/// A declaration `x: e` of one atom, or `x: m e` over sets or relations
234/// (LOGIC.md section 5).
235#[derive(Clone, Debug)]
236pub struct Decl {
237    /// The variable it introduces.
238    pub var: Variable,
239    /// What the variable ranges over.
240    pub expr: Expr,
241    /// How many tuples it holds.
242    pub mult: DeclMult,
243}
244
245impl Decl {
246    /// `var: expr`, for one atom.
247    pub fn new(var: &Variable, expr: &Expr) -> Decl {
248        Decl::with(var, DeclMult::One, expr)
249    }
250
251    /// `var: mult expr`.
252    pub fn with(var: &Variable, mult: DeclMult, expr: &Expr) -> Decl {
253        Decl {
254            var: var.clone(),
255            expr: expr.clone(),
256            mult,
257        }
258    }
259
260    /// Whether it declares one atom, not a set or a relation.
261    pub fn is_first_order(&self) -> bool {
262        self.mult == DeclMult::One && self.var.arity() == 1
263    }
264}
265
266/// What an expression is made of.
267#[derive(Clone, Debug)]
268pub enum ExprKind {
269    /// A relation.
270    Relation(Relation),
271    /// A variable.
272    Variable(Variable),
273    /// `none`
274    None,
275    /// `univ`
276    Univ,
277    /// `iden`
278    Iden,
279    /// A binary operator.
280    Binary(BinaryOp, Expr, Expr),
281    /// A unary operator.
282    Unary(UnaryOp, Expr),
283    /// `{x1: e1, ..., xm: em | F}`
284    Comprehension(Vec<Decl>, Formula),
285    /// `F => a else b`
286    IfThenElse(Formula, Expr, Expr),
287    /// `e'`: the value in the next state (LOGIC.md 13.2).
288    Prime(Expr),
289    /// `Int[n]`: the integer atom of `n`'s value (LOGIC.md 16.3).
290    IntToSet(IntExpr),
291}
292
293pub(crate) struct ExprNode {
294    pub(crate) kind: ExprKind,
295    pub(crate) arity: Option<usize>,
296    pub(crate) errors: Vec<Error>,
297    pub(crate) place: Place,
298}
299
300/// An expression: an immutable value, cheap to clone and share.
301#[derive(Clone)]
302pub struct Expr(pub(crate) Arc<ExprNode>);
303
304/// What a formula is made of.
305#[derive(Clone, Debug)]
306pub enum FormulaKind {
307    /// `true` or `false`
308    Constant(bool),
309    /// `a in b`
310    Subset(Expr, Expr),
311    /// `a = b`
312    Equal(Expr, Expr),
313    /// `some a`, `no a`, `one a`, `lone a`
314    Multiplicity(Multiplicity, Expr),
315    /// `not F`
316    Not(Formula),
317    /// `F and G and ...`; true when empty.
318    And(Vec<Formula>),
319    /// `F or G or ...`; false when empty.
320    Or(Vec<Formula>),
321    /// `F implies G`
322    Implies(Formula, Formula),
323    /// `F iff G`
324    Iff(Formula, Formula),
325    /// `q x1: e1, ..., xm: em | F`
326    Quantified(Quantifier, Vec<Decl>, Formula),
327    /// `after F`, `always F`, and the other unary temporal operators.
328    Temporal(TemporalOp, Formula),
329    /// `F until G`, and the other binary temporal operators.
330    TemporalBinary(TemporalBinaryOp, Formula, Formula),
331    /// `a < b`, and the other comparisons of integers (LOGIC.md 16.3).
332    IntCompare(IntComparison, IntExpr, IntExpr),
333}
334
335/// An operator on two integers (LOGIC.md 16.2).
336#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
337#[non_exhaustive]
338pub enum IntOp {
339    /// `a + b`
340    Plus,
341    /// `a - b`
342    Minus,
343    /// `a * b`
344    Times,
345    /// `a / b`, rounded toward zero
346    Divide,
347    /// `a % b`, with the sign of `a`
348    Remainder,
349    /// `a << b`
350    ShiftLeft,
351    /// `a >> b`, filling with the sign of `a`
352    ShiftRight,
353    /// `a >>> b`, filling with zeros
354    UnsignedShiftRight,
355}
356
357impl IntOp {
358    /// How it is written.
359    pub fn symbol(self) -> &'static str {
360        match self {
361            IntOp::Plus => "+",
362            IntOp::Minus => "-",
363            IntOp::Times => "*",
364            IntOp::Divide => "/",
365            IntOp::Remainder => "%",
366            IntOp::ShiftLeft => "<<",
367            IntOp::ShiftRight => ">>",
368            IntOp::UnsignedShiftRight => ">>>",
369        }
370    }
371}
372
373/// A comparison of two integers (LOGIC.md 16.3).
374#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
375pub enum IntComparison {
376    /// `a = b`
377    Equal,
378    /// `a < b`
379    Less,
380    /// `a =< b`
381    LessOrEqual,
382    /// `a > b`
383    Greater,
384    /// `a >= b`
385    GreaterOrEqual,
386}
387
388impl IntComparison {
389    /// How it is written.
390    pub fn symbol(self) -> &'static str {
391        match self {
392            IntComparison::Equal => "=",
393            IntComparison::Less => "<",
394            IntComparison::LessOrEqual => "=<",
395            IntComparison::Greater => ">",
396            IntComparison::GreaterOrEqual => ">=",
397        }
398    }
399
400    /// Whether it holds of two values.
401    pub fn holds(self, a: i64, b: i64) -> bool {
402        match self {
403            IntComparison::Equal => a == b,
404            IntComparison::Less => a < b,
405            IntComparison::LessOrEqual => a <= b,
406            IntComparison::Greater => a > b,
407            IntComparison::GreaterOrEqual => a >= b,
408        }
409    }
410}
411
412/// What an integer expression is made of (LOGIC.md 16.2).
413#[derive(Clone, Debug)]
414pub enum IntExprKind {
415    /// A number.
416    Constant(i64),
417    /// `#e`
418    Count(Expr),
419    /// `sum e`: the integers of a set's integer atoms, added.
420    Sum(Expr),
421    /// `a op b`
422    Binary(IntOp, IntExpr, IntExpr),
423    /// `-a`
424    Negate(IntExpr),
425    /// `F => a else b`
426    IfThenElse(Formula, IntExpr, IntExpr),
427    /// `sum x1: e1, ..., xm: em | n`
428    SumOver(Vec<Decl>, IntExpr),
429}
430
431pub(crate) struct IntNode {
432    pub(crate) kind: IntExprKind,
433    pub(crate) well_formed: bool,
434    pub(crate) errors: Vec<Error>,
435    pub(crate) place: Place,
436}
437
438/// An integer expression: an immutable value, cheap to clone and share.
439#[derive(Clone)]
440pub struct IntExpr(pub(crate) Arc<IntNode>);
441
442fn int_node(kind: IntExprKind, well_formed: bool, errors: Vec<Error>, place: Place) -> IntExpr {
443    IntExpr(Arc::new(IntNode {
444        kind,
445        well_formed,
446        errors,
447        place,
448    }))
449}
450
451impl IntExpr {
452    /// The number `k`.
453    #[track_caller]
454    pub fn constant(k: i64) -> IntExpr {
455        int_node(IntExprKind::Constant(k), true, Vec::new(), Place::caller())
456    }
457
458    /// Whether this integer expression and all its parts are well formed.
459    pub fn is_well_formed(&self) -> bool {
460        self.0.well_formed
461    }
462
463    /// What it is made of.
464    pub fn kind(&self) -> &IntExprKind {
465        &self.0.kind
466    }
467
468    /// Where it was built.
469    pub fn place(&self) -> &Place {
470        &self.0.place
471    }
472
473    /// The errors recorded when this node was built, not its parts'.
474    pub fn own_errors(&self) -> &[Error] {
475        &self.0.errors
476    }
477
478    /// The same node, at another place, as [`Expr::placed`].
479    pub fn placed(&self, place: Place) -> IntExpr {
480        let errors = self
481            .0
482            .errors
483            .iter()
484            .map(|e| e.clone().at(place.clone()))
485            .collect();
486        int_node(self.0.kind.clone(), self.0.well_formed, errors, place)
487    }
488
489    pub(crate) fn node_id(&self) -> usize {
490        Arc::as_ptr(&self.0) as usize
491    }
492
493    #[track_caller]
494    fn binary(&self, op: IntOp, other: &IntExpr) -> IntExpr {
495        int_node(
496            IntExprKind::Binary(op, self.clone(), other.clone()),
497            self.is_well_formed() && other.is_well_formed(),
498            Vec::new(),
499            Place::caller(),
500        )
501    }
502
503    /// `self op other`, for any operator.
504    #[track_caller]
505    pub fn apply(&self, op: IntOp, other: &IntExpr) -> IntExpr {
506        self.binary(op, other)
507    }
508
509    /// `self + other`
510    #[track_caller]
511    pub fn plus(&self, other: &IntExpr) -> IntExpr {
512        self.binary(IntOp::Plus, other)
513    }
514
515    /// `self - other`
516    #[track_caller]
517    pub fn minus(&self, other: &IntExpr) -> IntExpr {
518        self.binary(IntOp::Minus, other)
519    }
520
521    /// `self * other`
522    #[track_caller]
523    pub fn times(&self, other: &IntExpr) -> IntExpr {
524        self.binary(IntOp::Times, other)
525    }
526
527    /// `self / other`
528    #[track_caller]
529    pub fn divide(&self, other: &IntExpr) -> IntExpr {
530        self.binary(IntOp::Divide, other)
531    }
532
533    /// `self % other`
534    #[track_caller]
535    pub fn remainder(&self, other: &IntExpr) -> IntExpr {
536        self.binary(IntOp::Remainder, other)
537    }
538
539    /// `self << other`
540    #[track_caller]
541    pub fn shift_left(&self, other: &IntExpr) -> IntExpr {
542        self.binary(IntOp::ShiftLeft, other)
543    }
544
545    /// `self >> other`, filling with the sign of `self`
546    #[track_caller]
547    pub fn shift_right(&self, other: &IntExpr) -> IntExpr {
548        self.binary(IntOp::ShiftRight, other)
549    }
550
551    /// `self >>> other`, filling with zeros
552    #[track_caller]
553    pub fn unsigned_shift_right(&self, other: &IntExpr) -> IntExpr {
554        self.binary(IntOp::UnsignedShiftRight, other)
555    }
556
557    /// `-self`
558    #[track_caller]
559    pub fn negate(&self) -> IntExpr {
560        int_node(
561            IntExprKind::Negate(self.clone()),
562            self.is_well_formed(),
563            Vec::new(),
564            Place::caller(),
565        )
566    }
567
568    /// `condition => then else otherwise`
569    #[track_caller]
570    pub fn if_then_else(condition: &Formula, then: &IntExpr, otherwise: &IntExpr) -> IntExpr {
571        int_node(
572            IntExprKind::IfThenElse(condition.clone(), then.clone(), otherwise.clone()),
573            condition.is_well_formed() && then.is_well_formed() && otherwise.is_well_formed(),
574            Vec::new(),
575            Place::caller(),
576        )
577    }
578
579    /// `sum x1: e1, ..., xm: em | body`, over atoms.
580    #[track_caller]
581    pub fn sum_over(decls: Vec<Decl>, body: &IntExpr) -> IntExpr {
582        let place = Place::caller();
583        let (ok, errors) = check_decls(&decls, &place, Some("a sum"));
584        int_node(
585            IntExprKind::SumOver(decls, body.clone()),
586            ok && body.is_well_formed(),
587            errors,
588            place,
589        )
590    }
591
592    #[track_caller]
593    fn compare(&self, op: IntComparison, other: &IntExpr) -> Formula {
594        formula_node(
595            FormulaKind::IntCompare(op, self.clone(), other.clone()),
596            self.is_well_formed() && other.is_well_formed(),
597            Vec::new(),
598            Place::caller(),
599        )
600    }
601
602    /// `self op other`, for any comparison.
603    #[track_caller]
604    pub fn compare_with(&self, op: IntComparison, other: &IntExpr) -> Formula {
605        self.compare(op, other)
606    }
607
608    /// `self = other`
609    #[track_caller]
610    pub fn equals(&self, other: &IntExpr) -> Formula {
611        self.compare(IntComparison::Equal, other)
612    }
613
614    /// `self < other`
615    #[track_caller]
616    pub fn lt(&self, other: &IntExpr) -> Formula {
617        self.compare(IntComparison::Less, other)
618    }
619
620    /// `self =< other`
621    #[track_caller]
622    pub fn lte(&self, other: &IntExpr) -> Formula {
623        self.compare(IntComparison::LessOrEqual, other)
624    }
625
626    /// `self > other`
627    #[track_caller]
628    pub fn gt(&self, other: &IntExpr) -> Formula {
629        self.compare(IntComparison::Greater, other)
630    }
631
632    /// `self >= other`
633    #[track_caller]
634    pub fn gte(&self, other: &IntExpr) -> Formula {
635        self.compare(IntComparison::GreaterOrEqual, other)
636    }
637
638    /// `Int[self]`, the set of the integer atom of its value.
639    #[track_caller]
640    pub fn to_set(&self) -> Expr {
641        let arity = self.is_well_formed().then_some(1);
642        expr_node(
643            ExprKind::IntToSet(self.clone()),
644            arity,
645            Vec::new(),
646            Place::caller(),
647        )
648    }
649}
650
651pub(crate) struct FormulaNode {
652    pub(crate) kind: FormulaKind,
653    pub(crate) well_formed: bool,
654    pub(crate) errors: Vec<Error>,
655    pub(crate) place: Place,
656}
657
658/// A formula: an immutable value, cheap to clone and share.
659#[derive(Clone)]
660pub struct Formula(pub(crate) Arc<FormulaNode>);
661
662fn expr_node(kind: ExprKind, arity: Option<usize>, errors: Vec<Error>, place: Place) -> Expr {
663    Expr(Arc::new(ExprNode {
664        kind,
665        arity,
666        errors,
667        place,
668    }))
669}
670
671fn formula_node(kind: FormulaKind, well_formed: bool, errors: Vec<Error>, place: Place) -> Formula {
672    Formula(Arc::new(FormulaNode {
673        kind,
674        well_formed,
675        errors,
676        place,
677    }))
678}
679
680/// Checks a list of declarations: one or more, an atom's over a set, and a
681/// set's or relation's over an expression of its arity; in a comprehension
682/// or a sum, named by `atoms_only`, atoms only. Returns whether all parts
683/// are well formed, and the errors of this node.
684fn check_decls(decls: &[Decl], place: &Place, atoms_only: Option<&str>) -> (bool, Vec<Error>) {
685    let mut errors = Vec::new();
686    let mut parts_ok = true;
687    if decls.is_empty() {
688        errors.push(
689            Error::new("logic.no_declarations", "a quantifier with no declarations")
690                .at(place.clone()),
691        );
692    }
693    for d in decls {
694        let Some(k) = d.expr.arity() else {
695            parts_ok = false;
696            continue;
697        };
698        if d.is_first_order() {
699            if k != 1 {
700                errors.push(
701                    Error::new(
702                        "arity.not_a_set",
703                        format!("`{}` is declared over an expression of arity {k}", d.var),
704                    )
705                    .at(place.clone()),
706                );
707            }
708        } else if let Some(within) = atoms_only {
709            errors.push(
710                Error::new(
711                    "logic.higher_order",
712                    format!("`{}` is declared over sets or relations in {within}", d.var),
713                )
714                .at(place.clone()),
715            );
716        } else if k != d.var.arity() {
717            errors.push(
718                Error::new(
719                    "arity.mismatch",
720                    format!(
721                        "`{}` of arity {} is declared over an expression of arity {k}",
722                        d.var,
723                        d.var.arity()
724                    ),
725                )
726                .at(place.clone()),
727            );
728        }
729    }
730    (parts_ok && errors.is_empty(), errors)
731}
732
733impl Expr {
734    /// The relation as an expression. A relation of arity 0 gives an
735    /// ill-formed expression (`arity.zero`).
736    #[track_caller]
737    pub fn relation(r: &Relation) -> Expr {
738        let place = Place::caller();
739        if r.arity() == 0 {
740            let e = Error::new("arity.zero", format!("the relation `{r}` has arity 0"))
741                .at(r.place().clone());
742            return expr_node(ExprKind::Relation(r.clone()), None, vec![e], place);
743        }
744        expr_node(
745            ExprKind::Relation(r.clone()),
746            Some(r.arity()),
747            Vec::new(),
748            place,
749        )
750    }
751
752    /// The variable as an expression, of its arity.
753    #[track_caller]
754    pub fn variable(v: &Variable) -> Expr {
755        let place = Place::caller();
756        if v.arity() == 0 {
757            let e = Error::new("arity.zero", format!("the variable `{v}` has arity 0"))
758                .at(place.clone());
759            return expr_node(ExprKind::Variable(v.clone()), None, vec![e], place);
760        }
761        expr_node(
762            ExprKind::Variable(v.clone()),
763            Some(v.arity()),
764            Vec::new(),
765            place,
766        )
767    }
768
769    /// `none`, the empty set.
770    #[track_caller]
771    pub fn none() -> Expr {
772        expr_node(ExprKind::None, Some(1), Vec::new(), Place::caller())
773    }
774
775    /// `univ`, every atom.
776    #[track_caller]
777    pub fn univ() -> Expr {
778        expr_node(ExprKind::Univ, Some(1), Vec::new(), Place::caller())
779    }
780
781    /// `iden`, every pair of an atom with itself.
782    #[track_caller]
783    pub fn iden() -> Expr {
784        expr_node(ExprKind::Iden, Some(2), Vec::new(), Place::caller())
785    }
786
787    /// The arity, or `None` if the expression is ill-formed.
788    pub fn arity(&self) -> Option<usize> {
789        self.0.arity
790    }
791
792    /// What the expression is made of.
793    pub fn kind(&self) -> &ExprKind {
794        &self.0.kind
795    }
796
797    /// Where it was built.
798    pub fn place(&self) -> &Place {
799        &self.0.place
800    }
801
802    /// The errors recorded when this node was built, not its parts'.
803    pub fn own_errors(&self) -> &[Error] {
804        &self.0.errors
805    }
806
807    /// The same node, at another place: for a node built from model text,
808    /// the place in the text. Errors recorded at this node move with it.
809    pub fn placed(&self, place: Place) -> Expr {
810        let errors = self
811            .0
812            .errors
813            .iter()
814            .map(|e| e.clone().at(place.clone()))
815            .collect();
816        expr_node(self.0.kind.clone(), self.0.arity, errors, place)
817    }
818
819    /// Whether two handles are the same node.
820    pub fn same_node(&self, other: &Expr) -> bool {
821        Arc::ptr_eq(&self.0, &other.0)
822    }
823
824    pub(crate) fn node_id(&self) -> usize {
825        Arc::as_ptr(&self.0) as usize
826    }
827
828    #[track_caller]
829    fn binary(&self, op: BinaryOp, other: &Expr) -> Expr {
830        let place = Place::caller();
831        let kind = ExprKind::Binary(op, self.clone(), other.clone());
832        let (Some(a), Some(b)) = (self.arity(), other.arity()) else {
833            return expr_node(kind, None, Vec::new(), place);
834        };
835        let arity = match op {
836            BinaryOp::Union
837            | BinaryOp::Intersection
838            | BinaryOp::Difference
839            | BinaryOp::Override => {
840                if a == b {
841                    Ok(a)
842                } else {
843                    Err(Error::new(
844                        "arity.mismatch",
845                        format!("`{}` of arities {a} and {b}", op.symbol()),
846                    ))
847                }
848            }
849            BinaryOp::Join => {
850                if a + b > 2 {
851                    Ok(a + b - 2)
852                } else {
853                    Err(Error::new("arity.join", "a join of two sets"))
854                }
855            }
856            BinaryOp::Product => Ok(a + b),
857            BinaryOp::DomainRestriction => {
858                if a == 1 {
859                    Ok(b)
860                } else {
861                    Err(Error::new(
862                        "arity.not_a_set",
863                        format!("the left side of `<:` has arity {a}"),
864                    ))
865                }
866            }
867            BinaryOp::RangeRestriction => {
868                if b == 1 {
869                    Ok(a)
870                } else {
871                    Err(Error::new(
872                        "arity.not_a_set",
873                        format!("the right side of `:>` has arity {b}"),
874                    ))
875                }
876            }
877        };
878        match arity {
879            Ok(k) => expr_node(kind, Some(k), Vec::new(), place),
880            Err(e) => {
881                let e = e.at(place.clone());
882                expr_node(kind, None, vec![e], place)
883            }
884        }
885    }
886
887    #[track_caller]
888    fn unary(&self, op: UnaryOp) -> Expr {
889        let place = Place::caller();
890        let kind = ExprKind::Unary(op, self.clone());
891        match self.arity() {
892            None => expr_node(kind, None, Vec::new(), place),
893            Some(2) => expr_node(kind, Some(2), Vec::new(), place),
894            Some(k) => {
895                let e = Error::new(
896                    "arity.not_binary",
897                    format!("`{}` on an expression of arity {k}", op.symbol()),
898                )
899                .at(place.clone());
900                expr_node(kind, None, vec![e], place)
901            }
902        }
903    }
904
905    /// `self op other`, for any binary operator.
906    #[track_caller]
907    pub fn apply_binary(&self, op: BinaryOp, other: &Expr) -> Expr {
908        self.binary(op, other)
909    }
910
911    /// `op self`, for any unary operator.
912    #[track_caller]
913    pub fn apply_unary(&self, op: UnaryOp) -> Expr {
914        self.unary(op)
915    }
916
917    /// `m self`, for any multiplicity.
918    #[track_caller]
919    pub fn apply_multiplicity(&self, m: Multiplicity) -> Formula {
920        self.multiplicity(m)
921    }
922
923    /// `self + other`
924    #[track_caller]
925    pub fn union(&self, other: &Expr) -> Expr {
926        self.binary(BinaryOp::Union, other)
927    }
928
929    /// `self & other`
930    #[track_caller]
931    pub fn intersection(&self, other: &Expr) -> Expr {
932        self.binary(BinaryOp::Intersection, other)
933    }
934
935    /// `self - other`
936    #[track_caller]
937    pub fn difference(&self, other: &Expr) -> Expr {
938        self.binary(BinaryOp::Difference, other)
939    }
940
941    /// `self . other`
942    #[track_caller]
943    pub fn join(&self, other: &Expr) -> Expr {
944        self.binary(BinaryOp::Join, other)
945    }
946
947    /// `self -> other`
948    #[track_caller]
949    pub fn product(&self, other: &Expr) -> Expr {
950        self.binary(BinaryOp::Product, other)
951    }
952
953    /// `self ++ other`
954    #[track_caller]
955    pub fn override_with(&self, other: &Expr) -> Expr {
956        self.binary(BinaryOp::Override, other)
957    }
958
959    /// `self <: other`, with `self` the set.
960    #[track_caller]
961    pub fn domain_restriction(&self, other: &Expr) -> Expr {
962        self.binary(BinaryOp::DomainRestriction, other)
963    }
964
965    /// `self :> other`, with `other` the set.
966    #[track_caller]
967    pub fn range_restriction(&self, other: &Expr) -> Expr {
968        self.binary(BinaryOp::RangeRestriction, other)
969    }
970
971    /// `self'`, the value in the next state.
972    #[track_caller]
973    pub fn prime(&self) -> Expr {
974        expr_node(
975            ExprKind::Prime(self.clone()),
976            self.arity(),
977            Vec::new(),
978            Place::caller(),
979        )
980    }
981
982    /// `~self`
983    #[track_caller]
984    pub fn transpose(&self) -> Expr {
985        self.unary(UnaryOp::Transpose)
986    }
987
988    /// `^self`
989    #[track_caller]
990    pub fn closure(&self) -> Expr {
991        self.unary(UnaryOp::Closure)
992    }
993
994    /// `*self`
995    #[track_caller]
996    pub fn reflexive_closure(&self) -> Expr {
997        self.unary(UnaryOp::ReflexiveClosure)
998    }
999
1000    /// `{x1: e1, ..., xm: em | formula}`, of arity `m`.
1001    #[track_caller]
1002    pub fn comprehension(decls: Vec<Decl>, formula: &Formula) -> Expr {
1003        let place = Place::caller();
1004        let (ok, errors) = check_decls(&decls, &place, Some("a comprehension"));
1005        let arity = (ok && formula.is_well_formed()).then_some(decls.len());
1006        expr_node(
1007            ExprKind::Comprehension(decls, formula.clone()),
1008            arity,
1009            errors,
1010            place,
1011        )
1012    }
1013
1014    /// `condition => then else otherwise`
1015    #[track_caller]
1016    pub fn if_then_else(condition: &Formula, then: &Expr, otherwise: &Expr) -> Expr {
1017        let place = Place::caller();
1018        let kind = ExprKind::IfThenElse(condition.clone(), then.clone(), otherwise.clone());
1019        let (Some(a), Some(b)) = (then.arity(), otherwise.arity()) else {
1020            return expr_node(kind, None, Vec::new(), place);
1021        };
1022        if a != b {
1023            let e = Error::new(
1024                "arity.mismatch",
1025                format!("`=> else` with branches of arities {a} and {b}"),
1026            )
1027            .at(place.clone());
1028            return expr_node(kind, None, vec![e], place);
1029        }
1030        let arity = condition.is_well_formed().then_some(a);
1031        expr_node(kind, arity, Vec::new(), place)
1032    }
1033
1034    #[track_caller]
1035    fn compare(&self, other: &Expr, equal: bool) -> Formula {
1036        let place = Place::caller();
1037        let kind = if equal {
1038            FormulaKind::Equal(self.clone(), other.clone())
1039        } else {
1040            FormulaKind::Subset(self.clone(), other.clone())
1041        };
1042        let (Some(a), Some(b)) = (self.arity(), other.arity()) else {
1043            return formula_node(kind, false, Vec::new(), place);
1044        };
1045        if a != b {
1046            let op = if equal { "=" } else { "in" };
1047            let e = Error::new("arity.mismatch", format!("`{op}` of arities {a} and {b}"))
1048                .at(place.clone());
1049            return formula_node(kind, false, vec![e], place);
1050        }
1051        formula_node(kind, true, Vec::new(), place)
1052    }
1053
1054    /// `self in other`
1055    #[track_caller]
1056    pub fn is_in(&self, other: &Expr) -> Formula {
1057        self.compare(other, false)
1058    }
1059
1060    /// `self = other`
1061    #[track_caller]
1062    pub fn equals(&self, other: &Expr) -> Formula {
1063        self.compare(other, true)
1064    }
1065
1066    #[track_caller]
1067    fn multiplicity(&self, m: Multiplicity) -> Formula {
1068        formula_node(
1069            FormulaKind::Multiplicity(m, self.clone()),
1070            self.arity().is_some(),
1071            Vec::new(),
1072            Place::caller(),
1073        )
1074    }
1075
1076    /// `#self`, the number of its tuples (LOGIC.md 16.2).
1077    #[track_caller]
1078    pub fn count(&self) -> IntExpr {
1079        int_node(
1080            IntExprKind::Count(self.clone()),
1081            self.arity().is_some(),
1082            Vec::new(),
1083            Place::caller(),
1084        )
1085    }
1086
1087    /// `sum self`, the integers of a set's integer atoms, added
1088    /// (LOGIC.md 16.2).
1089    #[track_caller]
1090    pub fn sum(&self) -> IntExpr {
1091        let place = Place::caller();
1092        let kind = IntExprKind::Sum(self.clone());
1093        match self.arity() {
1094            None => int_node(kind, false, Vec::new(), place),
1095            Some(1) => int_node(kind, true, Vec::new(), place),
1096            Some(k) => {
1097                let e = Error::new(
1098                    "arity.not_a_set",
1099                    format!("`sum` of an expression of arity {k}"),
1100                )
1101                .at(place.clone());
1102                int_node(kind, false, vec![e], place)
1103            }
1104        }
1105    }
1106
1107    /// `some self`
1108    #[track_caller]
1109    pub fn some(&self) -> Formula {
1110        self.multiplicity(Multiplicity::Some)
1111    }
1112
1113    /// `no self`
1114    #[track_caller]
1115    pub fn no(&self) -> Formula {
1116        self.multiplicity(Multiplicity::No)
1117    }
1118
1119    /// `one self`
1120    #[track_caller]
1121    pub fn one(&self) -> Formula {
1122        self.multiplicity(Multiplicity::One)
1123    }
1124
1125    /// `lone self`
1126    #[track_caller]
1127    pub fn lone(&self) -> Formula {
1128        self.multiplicity(Multiplicity::Lone)
1129    }
1130}
1131
1132impl From<&Relation> for Expr {
1133    #[track_caller]
1134    fn from(r: &Relation) -> Expr {
1135        Expr::relation(r)
1136    }
1137}
1138
1139impl From<&Variable> for Expr {
1140    #[track_caller]
1141    fn from(v: &Variable) -> Expr {
1142        Expr::variable(v)
1143    }
1144}
1145
1146impl Formula {
1147    /// `true` or `false`.
1148    #[track_caller]
1149    pub fn constant(value: bool) -> Formula {
1150        formula_node(
1151            FormulaKind::Constant(value),
1152            true,
1153            Vec::new(),
1154            Place::caller(),
1155        )
1156    }
1157
1158    /// `true`
1159    #[track_caller]
1160    pub fn truth() -> Formula {
1161        Formula::constant(true)
1162    }
1163
1164    /// `false`
1165    #[track_caller]
1166    pub fn falsity() -> Formula {
1167        Formula::constant(false)
1168    }
1169
1170    /// Whether this formula and all its parts are well formed.
1171    pub fn is_well_formed(&self) -> bool {
1172        self.0.well_formed
1173    }
1174
1175    /// What the formula is made of.
1176    pub fn kind(&self) -> &FormulaKind {
1177        &self.0.kind
1178    }
1179
1180    /// Where it was built.
1181    pub fn place(&self) -> &Place {
1182        &self.0.place
1183    }
1184
1185    /// The errors recorded when this node was built, not its parts'.
1186    pub fn own_errors(&self) -> &[Error] {
1187        &self.0.errors
1188    }
1189
1190    /// The same node, at another place, as [`Expr::placed`].
1191    pub fn placed(&self, place: Place) -> Formula {
1192        let errors = self
1193            .0
1194            .errors
1195            .iter()
1196            .map(|e| e.clone().at(place.clone()))
1197            .collect();
1198        formula_node(self.0.kind.clone(), self.0.well_formed, errors, place)
1199    }
1200
1201    /// Whether two handles are the same node.
1202    pub fn same_node(&self, other: &Formula) -> bool {
1203        Arc::ptr_eq(&self.0, &other.0)
1204    }
1205
1206    pub(crate) fn node_id(&self) -> usize {
1207        Arc::as_ptr(&self.0) as usize
1208    }
1209
1210    /// `not self`
1211    #[track_caller]
1212    pub fn not(&self) -> Formula {
1213        formula_node(
1214            FormulaKind::Not(self.clone()),
1215            self.is_well_formed(),
1216            Vec::new(),
1217            Place::caller(),
1218        )
1219    }
1220
1221    /// `self and other`
1222    #[track_caller]
1223    pub fn and(&self, other: &Formula) -> Formula {
1224        Formula::and_all([self.clone(), other.clone()])
1225    }
1226
1227    /// `self or other`
1228    #[track_caller]
1229    pub fn or(&self, other: &Formula) -> Formula {
1230        Formula::or_all([self.clone(), other.clone()])
1231    }
1232
1233    /// The conjunction of any number of formulas; true when there are none.
1234    #[track_caller]
1235    pub fn and_all(formulas: impl IntoIterator<Item = Formula>) -> Formula {
1236        let fs: Vec<Formula> = formulas.into_iter().collect();
1237        let ok = fs.iter().all(Formula::is_well_formed);
1238        formula_node(FormulaKind::And(fs), ok, Vec::new(), Place::caller())
1239    }
1240
1241    /// The disjunction of any number of formulas; false when there are none.
1242    #[track_caller]
1243    pub fn or_all(formulas: impl IntoIterator<Item = Formula>) -> Formula {
1244        let fs: Vec<Formula> = formulas.into_iter().collect();
1245        let ok = fs.iter().all(Formula::is_well_formed);
1246        formula_node(FormulaKind::Or(fs), ok, Vec::new(), Place::caller())
1247    }
1248
1249    /// `self implies other`
1250    #[track_caller]
1251    pub fn implies(&self, other: &Formula) -> Formula {
1252        formula_node(
1253            FormulaKind::Implies(self.clone(), other.clone()),
1254            self.is_well_formed() && other.is_well_formed(),
1255            Vec::new(),
1256            Place::caller(),
1257        )
1258    }
1259
1260    /// `self iff other`
1261    #[track_caller]
1262    pub fn iff(&self, other: &Formula) -> Formula {
1263        formula_node(
1264            FormulaKind::Iff(self.clone(), other.clone()),
1265            self.is_well_formed() && other.is_well_formed(),
1266            Vec::new(),
1267            Place::caller(),
1268        )
1269    }
1270
1271    /// `q x1: e1, ..., xm: em | body`
1272    #[track_caller]
1273    pub fn quantified(q: Quantifier, decls: Vec<Decl>, body: &Formula) -> Formula {
1274        let place = Place::caller();
1275        let (ok, errors) = check_decls(&decls, &place, None);
1276        formula_node(
1277            FormulaKind::Quantified(q, decls, body.clone()),
1278            ok && body.is_well_formed(),
1279            errors,
1280            place,
1281        )
1282    }
1283
1284    /// `op self`, for a unary temporal operator.
1285    #[track_caller]
1286    pub fn temporal(&self, op: TemporalOp) -> Formula {
1287        formula_node(
1288            FormulaKind::Temporal(op, self.clone()),
1289            self.is_well_formed(),
1290            Vec::new(),
1291            Place::caller(),
1292        )
1293    }
1294
1295    /// `self op other`, for a binary temporal operator.
1296    #[track_caller]
1297    pub fn temporal_binary(&self, op: TemporalBinaryOp, other: &Formula) -> Formula {
1298        formula_node(
1299            FormulaKind::TemporalBinary(op, self.clone(), other.clone()),
1300            self.is_well_formed() && other.is_well_formed(),
1301            Vec::new(),
1302            Place::caller(),
1303        )
1304    }
1305
1306    /// `after self`
1307    #[track_caller]
1308    pub fn after(&self) -> Formula {
1309        self.temporal(TemporalOp::After)
1310    }
1311
1312    /// `always self`
1313    #[track_caller]
1314    pub fn always(&self) -> Formula {
1315        self.temporal(TemporalOp::Always)
1316    }
1317
1318    /// `eventually self`
1319    #[track_caller]
1320    pub fn eventually(&self) -> Formula {
1321        self.temporal(TemporalOp::Eventually)
1322    }
1323
1324    /// `before self`
1325    #[track_caller]
1326    pub fn before(&self) -> Formula {
1327        self.temporal(TemporalOp::Before)
1328    }
1329
1330    /// `historically self`
1331    #[track_caller]
1332    pub fn historically(&self) -> Formula {
1333        self.temporal(TemporalOp::Historically)
1334    }
1335
1336    /// `once self`
1337    #[track_caller]
1338    pub fn once(&self) -> Formula {
1339        self.temporal(TemporalOp::Once)
1340    }
1341
1342    /// `self until other`
1343    #[track_caller]
1344    pub fn until(&self, other: &Formula) -> Formula {
1345        self.temporal_binary(TemporalBinaryOp::Until, other)
1346    }
1347
1348    /// `self releases other`
1349    #[track_caller]
1350    pub fn releases(&self, other: &Formula) -> Formula {
1351        self.temporal_binary(TemporalBinaryOp::Releases, other)
1352    }
1353
1354    /// `self since other`
1355    #[track_caller]
1356    pub fn since(&self, other: &Formula) -> Formula {
1357        self.temporal_binary(TemporalBinaryOp::Since, other)
1358    }
1359
1360    /// `self triggered other`
1361    #[track_caller]
1362    pub fn triggered(&self, other: &Formula) -> Formula {
1363        self.temporal_binary(TemporalBinaryOp::Triggered, other)
1364    }
1365
1366    /// The greatest number of past operators nested in one another
1367    /// (LOGIC.md 13.3).
1368    pub fn past_depth(&self) -> usize {
1369        past_depth_formula(self)
1370    }
1371
1372    /// Whether the formula has a temporal operator or a prime.
1373    pub fn is_temporal(&self) -> bool {
1374        temporal_formula(self)
1375    }
1376
1377    /// `all x1: e1, ..., xm: em | body`
1378    #[track_caller]
1379    pub fn all(decls: Vec<Decl>, body: &Formula) -> Formula {
1380        Formula::quantified(Quantifier::All, decls, body)
1381    }
1382
1383    /// `some x1: e1, ..., xm: em | body`
1384    #[track_caller]
1385    pub fn some(decls: Vec<Decl>, body: &Formula) -> Formula {
1386        Formula::quantified(Quantifier::Some, decls, body)
1387    }
1388
1389    /// `no x1: e1, ..., xm: em | body`
1390    #[track_caller]
1391    pub fn no(decls: Vec<Decl>, body: &Formula) -> Formula {
1392        Formula::quantified(Quantifier::No, decls, body)
1393    }
1394
1395    /// `one x1: e1, ..., xm: em | body`
1396    #[track_caller]
1397    pub fn one(decls: Vec<Decl>, body: &Formula) -> Formula {
1398        Formula::quantified(Quantifier::One, decls, body)
1399    }
1400
1401    /// `lone x1: e1, ..., xm: em | body`
1402    #[track_caller]
1403    pub fn lone(decls: Vec<Decl>, body: &Formula) -> Formula {
1404        Formula::quantified(Quantifier::Lone, decls, body)
1405    }
1406}
1407
1408pub(crate) fn past_depth_expr(e: &Expr) -> usize {
1409    match e.kind() {
1410        ExprKind::Binary(_, a, b) => past_depth_expr(a).max(past_depth_expr(b)),
1411        ExprKind::Unary(_, a) | ExprKind::Prime(a) => past_depth_expr(a),
1412        ExprKind::Comprehension(decls, body) => decls
1413            .iter()
1414            .map(|d| past_depth_expr(&d.expr))
1415            .fold(past_depth_formula(body), usize::max),
1416        ExprKind::IfThenElse(c, a, b) => past_depth_formula(c)
1417            .max(past_depth_expr(a))
1418            .max(past_depth_expr(b)),
1419        ExprKind::IntToSet(n) => past_depth_int(n),
1420        ExprKind::Relation(_)
1421        | ExprKind::Variable(_)
1422        | ExprKind::None
1423        | ExprKind::Univ
1424        | ExprKind::Iden => 0,
1425    }
1426}
1427
1428fn past_depth_formula(f: &Formula) -> usize {
1429    match f.kind() {
1430        FormulaKind::Constant(_) => 0,
1431        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
1432            past_depth_expr(a).max(past_depth_expr(b))
1433        }
1434        FormulaKind::Multiplicity(_, a) => past_depth_expr(a),
1435        FormulaKind::Not(g) => past_depth_formula(g),
1436        FormulaKind::And(fs) | FormulaKind::Or(fs) => {
1437            fs.iter().map(past_depth_formula).max().unwrap_or(0)
1438        }
1439        FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
1440            past_depth_formula(a).max(past_depth_formula(b))
1441        }
1442        FormulaKind::Quantified(_, decls, body) => decls
1443            .iter()
1444            .map(|d| past_depth_expr(&d.expr))
1445            .fold(past_depth_formula(body), usize::max),
1446        FormulaKind::Temporal(op, g) => past_depth_formula(g) + usize::from(op.is_past()),
1447        FormulaKind::TemporalBinary(op, a, b) => {
1448            past_depth_formula(a).max(past_depth_formula(b)) + usize::from(op.is_past())
1449        }
1450        FormulaKind::IntCompare(_, a, b) => past_depth_int(a).max(past_depth_int(b)),
1451    }
1452}
1453
1454pub(crate) fn past_depth_int(n: &IntExpr) -> usize {
1455    match n.kind() {
1456        IntExprKind::Constant(_) => 0,
1457        IntExprKind::Count(e) | IntExprKind::Sum(e) => past_depth_expr(e),
1458        IntExprKind::Binary(_, a, b) => past_depth_int(a).max(past_depth_int(b)),
1459        IntExprKind::Negate(a) => past_depth_int(a),
1460        IntExprKind::IfThenElse(c, a, b) => past_depth_formula(c)
1461            .max(past_depth_int(a))
1462            .max(past_depth_int(b)),
1463        IntExprKind::SumOver(decls, body) => decls
1464            .iter()
1465            .map(|d| past_depth_expr(&d.expr))
1466            .fold(past_depth_int(body), usize::max),
1467    }
1468}
1469
1470fn temporal_int(n: &IntExpr) -> bool {
1471    match n.kind() {
1472        IntExprKind::Constant(_) => false,
1473        IntExprKind::Count(e) | IntExprKind::Sum(e) => temporal_expr(e),
1474        IntExprKind::Binary(_, a, b) => temporal_int(a) || temporal_int(b),
1475        IntExprKind::Negate(a) => temporal_int(a),
1476        IntExprKind::IfThenElse(c, a, b) => {
1477            temporal_formula(c) || temporal_int(a) || temporal_int(b)
1478        }
1479        IntExprKind::SumOver(decls, body) => {
1480            decls.iter().any(|d| temporal_expr(&d.expr)) || temporal_int(body)
1481        }
1482    }
1483}
1484
1485fn temporal_expr(e: &Expr) -> bool {
1486    match e.kind() {
1487        ExprKind::Prime(_) => true,
1488        ExprKind::Binary(_, a, b) => temporal_expr(a) || temporal_expr(b),
1489        ExprKind::Unary(_, a) => temporal_expr(a),
1490        ExprKind::Comprehension(decls, body) => {
1491            decls.iter().any(|d| temporal_expr(&d.expr)) || temporal_formula(body)
1492        }
1493        ExprKind::IfThenElse(c, a, b) => {
1494            temporal_formula(c) || temporal_expr(a) || temporal_expr(b)
1495        }
1496        ExprKind::IntToSet(n) => temporal_int(n),
1497        ExprKind::Relation(_)
1498        | ExprKind::Variable(_)
1499        | ExprKind::None
1500        | ExprKind::Univ
1501        | ExprKind::Iden => false,
1502    }
1503}
1504
1505fn temporal_formula(f: &Formula) -> bool {
1506    match f.kind() {
1507        FormulaKind::Constant(_) => false,
1508        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
1509            temporal_expr(a) || temporal_expr(b)
1510        }
1511        FormulaKind::Multiplicity(_, a) => temporal_expr(a),
1512        FormulaKind::Not(g) => temporal_formula(g),
1513        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(temporal_formula),
1514        FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
1515            temporal_formula(a) || temporal_formula(b)
1516        }
1517        FormulaKind::Quantified(_, decls, body) => {
1518            decls.iter().any(|d| temporal_expr(&d.expr)) || temporal_formula(body)
1519        }
1520        FormulaKind::Temporal(..) | FormulaKind::TemporalBinary(..) => true,
1521        FormulaKind::IntCompare(_, a, b) => temporal_int(a) || temporal_int(b),
1522    }
1523}
1524
1525fn write_decls(f: &mut fmt::Formatter<'_>, decls: &[Decl]) -> fmt::Result {
1526    for (i, d) in decls.iter().enumerate() {
1527        if i > 0 {
1528            write!(f, ", ")?;
1529        }
1530        if d.is_first_order() {
1531            write!(f, "{}: {}", d.var, d.expr)?;
1532        } else {
1533            write!(f, "{}: {} {}", d.var, d.mult.keyword(), d.expr)?;
1534        }
1535    }
1536    Ok(())
1537}
1538
1539/// Expressions are written fully parenthesized, so the text is unambiguous.
1540impl fmt::Display for Expr {
1541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1542        match self.kind() {
1543            ExprKind::Relation(r) => write!(f, "{r}"),
1544            ExprKind::Variable(v) => write!(f, "{v}"),
1545            ExprKind::None => write!(f, "none"),
1546            ExprKind::Univ => write!(f, "univ"),
1547            ExprKind::Iden => write!(f, "iden"),
1548            ExprKind::Binary(BinaryOp::Join, a, b) => write!(f, "({a}.{b})"),
1549            ExprKind::Binary(op, a, b) => write!(f, "({a} {} {b})", op.symbol()),
1550            ExprKind::Unary(op, a) => write!(f, "{}{a}", op.symbol()),
1551            ExprKind::Comprehension(decls, body) => {
1552                write!(f, "{{")?;
1553                write_decls(f, decls)?;
1554                write!(f, " | {body}}}")
1555            }
1556            ExprKind::IfThenElse(c, a, b) => write!(f, "({c} => {a} else {b})"),
1557            ExprKind::Prime(a) => write!(f, "{a}'"),
1558            ExprKind::IntToSet(n) => write!(f, "Int[{n}]"),
1559        }
1560    }
1561}
1562
1563impl fmt::Debug for Expr {
1564    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1565        write!(f, "{self}")
1566    }
1567}
1568
1569impl fmt::Display for Formula {
1570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1571        match self.kind() {
1572            FormulaKind::Constant(b) => write!(f, "{b}"),
1573            FormulaKind::Subset(a, b) => write!(f, "{a} in {b}"),
1574            FormulaKind::Equal(a, b) => write!(f, "{a} = {b}"),
1575            FormulaKind::Multiplicity(m, a) => write!(f, "{} {a}", m.keyword()),
1576            FormulaKind::Not(g) => write!(f, "not ({g})"),
1577            FormulaKind::And(fs) | FormulaKind::Or(fs) if fs.is_empty() => {
1578                write!(f, "{}", matches!(self.kind(), FormulaKind::And(_)))
1579            }
1580            FormulaKind::And(fs) | FormulaKind::Or(fs) => {
1581                let op = if matches!(self.kind(), FormulaKind::And(_)) {
1582                    "and"
1583                } else {
1584                    "or"
1585                };
1586                write!(f, "(")?;
1587                for (i, g) in fs.iter().enumerate() {
1588                    if i > 0 {
1589                        write!(f, " {op} ")?;
1590                    }
1591                    write!(f, "{g}")?;
1592                }
1593                write!(f, ")")
1594            }
1595            FormulaKind::Implies(a, b) => write!(f, "({a} implies {b})"),
1596            FormulaKind::Iff(a, b) => write!(f, "({a} iff {b})"),
1597            FormulaKind::Quantified(q, decls, body) => {
1598                write!(f, "({} ", q.keyword())?;
1599                write_decls(f, decls)?;
1600                write!(f, " | {body})")
1601            }
1602            FormulaKind::Temporal(op, g) => write!(f, "({} {g})", op.keyword()),
1603            FormulaKind::TemporalBinary(op, a, b) => write!(f, "({a} {} {b})", op.keyword()),
1604            FormulaKind::IntCompare(op, a, b) => write!(f, "{a} {} {b}", op.symbol()),
1605        }
1606    }
1607}
1608
1609impl fmt::Display for IntExpr {
1610    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1611        match self.kind() {
1612            IntExprKind::Constant(k) => write!(f, "{k}"),
1613            IntExprKind::Count(e) => write!(f, "#{e}"),
1614            IntExprKind::Sum(e) => write!(f, "(sum {e})"),
1615            IntExprKind::Binary(op, a, b) => write!(f, "({a} {} {b})", op.symbol()),
1616            IntExprKind::Negate(a) => write!(f, "-{a}"),
1617            IntExprKind::IfThenElse(c, a, b) => write!(f, "({c} => {a} else {b})"),
1618            IntExprKind::SumOver(decls, body) => {
1619                write!(f, "(sum ")?;
1620                write_decls(f, decls)?;
1621                write!(f, " | {body})")
1622            }
1623        }
1624    }
1625}
1626
1627impl fmt::Debug for IntExpr {
1628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629        write!(f, "{self}")
1630    }
1631}
1632
1633impl fmt::Debug for Formula {
1634    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1635        write!(f, "{self}")
1636    }
1637}