1use crate::error::{Error, Place};
13use crate::relation::{Relation, Variable};
14use std::fmt;
15use std::sync::Arc;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum BinaryOp {
20 Union,
22 Intersection,
24 Difference,
26 Join,
28 Product,
30 Override,
32 DomainRestriction,
34 RangeRestriction,
36}
37
38impl BinaryOp {
39 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
56pub enum UnaryOp {
57 Transpose,
59 Closure,
61 ReflexiveClosure,
63}
64
65impl UnaryOp {
66 pub fn symbol(self) -> &'static str {
68 match self {
69 UnaryOp::Transpose => "~",
70 UnaryOp::Closure => "^",
71 UnaryOp::ReflexiveClosure => "*",
72 }
73 }
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
78pub enum Multiplicity {
79 Some,
81 No,
83 One,
85 Lone,
87}
88
89impl Multiplicity {
90 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
103pub enum Quantifier {
104 All,
106 Some,
108 No,
110 One,
112 Lone,
114}
115
116impl Quantifier {
117 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
131pub enum TemporalOp {
132 After,
134 Always,
136 Eventually,
138 Before,
140 Historically,
142 Once,
144}
145
146impl TemporalOp {
147 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 pub fn is_past(self) -> bool {
161 matches!(
162 self,
163 TemporalOp::Before | TemporalOp::Historically | TemporalOp::Once
164 )
165 }
166}
167
168#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub enum TemporalBinaryOp {
171 Until,
173 Releases,
175 Since,
177 Triggered,
179}
180
181impl TemporalBinaryOp {
182 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 pub fn is_past(self) -> bool {
194 matches!(self, TemporalBinaryOp::Since | TemporalBinaryOp::Triggered)
195 }
196}
197
198#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
200pub enum DeclMult {
201 One,
203 Lone,
205 Some,
207 Set,
209}
210
211impl DeclMult {
212 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 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#[derive(Clone, Debug)]
236pub struct Decl {
237 pub var: Variable,
239 pub expr: Expr,
241 pub mult: DeclMult,
243}
244
245impl Decl {
246 pub fn new(var: &Variable, expr: &Expr) -> Decl {
248 Decl::with(var, DeclMult::One, expr)
249 }
250
251 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 pub fn is_first_order(&self) -> bool {
262 self.mult == DeclMult::One && self.var.arity() == 1
263 }
264}
265
266#[derive(Clone, Debug)]
268pub enum ExprKind {
269 Relation(Relation),
271 Variable(Variable),
273 None,
275 Univ,
277 Iden,
279 Binary(BinaryOp, Expr, Expr),
281 Unary(UnaryOp, Expr),
283 Comprehension(Vec<Decl>, Formula),
285 IfThenElse(Formula, Expr, Expr),
287 Prime(Expr),
289 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#[derive(Clone)]
302pub struct Expr(pub(crate) Arc<ExprNode>);
303
304#[derive(Clone, Debug)]
306pub enum FormulaKind {
307 Constant(bool),
309 Subset(Expr, Expr),
311 Equal(Expr, Expr),
313 Multiplicity(Multiplicity, Expr),
315 Not(Formula),
317 And(Vec<Formula>),
319 Or(Vec<Formula>),
321 Implies(Formula, Formula),
323 Iff(Formula, Formula),
325 Quantified(Quantifier, Vec<Decl>, Formula),
327 Temporal(TemporalOp, Formula),
329 TemporalBinary(TemporalBinaryOp, Formula, Formula),
331 IntCompare(IntComparison, IntExpr, IntExpr),
333}
334
335#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
337#[non_exhaustive]
338pub enum IntOp {
339 Plus,
341 Minus,
343 Times,
345 Divide,
347 Remainder,
349 ShiftLeft,
351 ShiftRight,
353 UnsignedShiftRight,
355}
356
357impl IntOp {
358 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
375pub enum IntComparison {
376 Equal,
378 Less,
380 LessOrEqual,
382 Greater,
384 GreaterOrEqual,
386}
387
388impl IntComparison {
389 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 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#[derive(Clone, Debug)]
414pub enum IntExprKind {
415 Constant(i64),
417 Count(Expr),
419 Sum(Expr),
421 Binary(IntOp, IntExpr, IntExpr),
423 Negate(IntExpr),
425 IfThenElse(Formula, IntExpr, IntExpr),
427 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#[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 #[track_caller]
454 pub fn constant(k: i64) -> IntExpr {
455 int_node(IntExprKind::Constant(k), true, Vec::new(), Place::caller())
456 }
457
458 pub fn is_well_formed(&self) -> bool {
460 self.0.well_formed
461 }
462
463 pub fn kind(&self) -> &IntExprKind {
465 &self.0.kind
466 }
467
468 pub fn place(&self) -> &Place {
470 &self.0.place
471 }
472
473 pub fn own_errors(&self) -> &[Error] {
475 &self.0.errors
476 }
477
478 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 #[track_caller]
505 pub fn apply(&self, op: IntOp, other: &IntExpr) -> IntExpr {
506 self.binary(op, other)
507 }
508
509 #[track_caller]
511 pub fn plus(&self, other: &IntExpr) -> IntExpr {
512 self.binary(IntOp::Plus, other)
513 }
514
515 #[track_caller]
517 pub fn minus(&self, other: &IntExpr) -> IntExpr {
518 self.binary(IntOp::Minus, other)
519 }
520
521 #[track_caller]
523 pub fn times(&self, other: &IntExpr) -> IntExpr {
524 self.binary(IntOp::Times, other)
525 }
526
527 #[track_caller]
529 pub fn divide(&self, other: &IntExpr) -> IntExpr {
530 self.binary(IntOp::Divide, other)
531 }
532
533 #[track_caller]
535 pub fn remainder(&self, other: &IntExpr) -> IntExpr {
536 self.binary(IntOp::Remainder, other)
537 }
538
539 #[track_caller]
541 pub fn shift_left(&self, other: &IntExpr) -> IntExpr {
542 self.binary(IntOp::ShiftLeft, other)
543 }
544
545 #[track_caller]
547 pub fn shift_right(&self, other: &IntExpr) -> IntExpr {
548 self.binary(IntOp::ShiftRight, other)
549 }
550
551 #[track_caller]
553 pub fn unsigned_shift_right(&self, other: &IntExpr) -> IntExpr {
554 self.binary(IntOp::UnsignedShiftRight, other)
555 }
556
557 #[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 #[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 #[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 #[track_caller]
604 pub fn compare_with(&self, op: IntComparison, other: &IntExpr) -> Formula {
605 self.compare(op, other)
606 }
607
608 #[track_caller]
610 pub fn equals(&self, other: &IntExpr) -> Formula {
611 self.compare(IntComparison::Equal, other)
612 }
613
614 #[track_caller]
616 pub fn lt(&self, other: &IntExpr) -> Formula {
617 self.compare(IntComparison::Less, other)
618 }
619
620 #[track_caller]
622 pub fn lte(&self, other: &IntExpr) -> Formula {
623 self.compare(IntComparison::LessOrEqual, other)
624 }
625
626 #[track_caller]
628 pub fn gt(&self, other: &IntExpr) -> Formula {
629 self.compare(IntComparison::Greater, other)
630 }
631
632 #[track_caller]
634 pub fn gte(&self, other: &IntExpr) -> Formula {
635 self.compare(IntComparison::GreaterOrEqual, other)
636 }
637
638 #[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#[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
680fn 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 #[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 #[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 #[track_caller]
771 pub fn none() -> Expr {
772 expr_node(ExprKind::None, Some(1), Vec::new(), Place::caller())
773 }
774
775 #[track_caller]
777 pub fn univ() -> Expr {
778 expr_node(ExprKind::Univ, Some(1), Vec::new(), Place::caller())
779 }
780
781 #[track_caller]
783 pub fn iden() -> Expr {
784 expr_node(ExprKind::Iden, Some(2), Vec::new(), Place::caller())
785 }
786
787 pub fn arity(&self) -> Option<usize> {
789 self.0.arity
790 }
791
792 pub fn kind(&self) -> &ExprKind {
794 &self.0.kind
795 }
796
797 pub fn place(&self) -> &Place {
799 &self.0.place
800 }
801
802 pub fn own_errors(&self) -> &[Error] {
804 &self.0.errors
805 }
806
807 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 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 #[track_caller]
907 pub fn apply_binary(&self, op: BinaryOp, other: &Expr) -> Expr {
908 self.binary(op, other)
909 }
910
911 #[track_caller]
913 pub fn apply_unary(&self, op: UnaryOp) -> Expr {
914 self.unary(op)
915 }
916
917 #[track_caller]
919 pub fn apply_multiplicity(&self, m: Multiplicity) -> Formula {
920 self.multiplicity(m)
921 }
922
923 #[track_caller]
925 pub fn union(&self, other: &Expr) -> Expr {
926 self.binary(BinaryOp::Union, other)
927 }
928
929 #[track_caller]
931 pub fn intersection(&self, other: &Expr) -> Expr {
932 self.binary(BinaryOp::Intersection, other)
933 }
934
935 #[track_caller]
937 pub fn difference(&self, other: &Expr) -> Expr {
938 self.binary(BinaryOp::Difference, other)
939 }
940
941 #[track_caller]
943 pub fn join(&self, other: &Expr) -> Expr {
944 self.binary(BinaryOp::Join, other)
945 }
946
947 #[track_caller]
949 pub fn product(&self, other: &Expr) -> Expr {
950 self.binary(BinaryOp::Product, other)
951 }
952
953 #[track_caller]
955 pub fn override_with(&self, other: &Expr) -> Expr {
956 self.binary(BinaryOp::Override, other)
957 }
958
959 #[track_caller]
961 pub fn domain_restriction(&self, other: &Expr) -> Expr {
962 self.binary(BinaryOp::DomainRestriction, other)
963 }
964
965 #[track_caller]
967 pub fn range_restriction(&self, other: &Expr) -> Expr {
968 self.binary(BinaryOp::RangeRestriction, other)
969 }
970
971 #[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 #[track_caller]
984 pub fn transpose(&self) -> Expr {
985 self.unary(UnaryOp::Transpose)
986 }
987
988 #[track_caller]
990 pub fn closure(&self) -> Expr {
991 self.unary(UnaryOp::Closure)
992 }
993
994 #[track_caller]
996 pub fn reflexive_closure(&self) -> Expr {
997 self.unary(UnaryOp::ReflexiveClosure)
998 }
999
1000 #[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 #[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 #[track_caller]
1056 pub fn is_in(&self, other: &Expr) -> Formula {
1057 self.compare(other, false)
1058 }
1059
1060 #[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 #[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 #[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 #[track_caller]
1109 pub fn some(&self) -> Formula {
1110 self.multiplicity(Multiplicity::Some)
1111 }
1112
1113 #[track_caller]
1115 pub fn no(&self) -> Formula {
1116 self.multiplicity(Multiplicity::No)
1117 }
1118
1119 #[track_caller]
1121 pub fn one(&self) -> Formula {
1122 self.multiplicity(Multiplicity::One)
1123 }
1124
1125 #[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 #[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 #[track_caller]
1160 pub fn truth() -> Formula {
1161 Formula::constant(true)
1162 }
1163
1164 #[track_caller]
1166 pub fn falsity() -> Formula {
1167 Formula::constant(false)
1168 }
1169
1170 pub fn is_well_formed(&self) -> bool {
1172 self.0.well_formed
1173 }
1174
1175 pub fn kind(&self) -> &FormulaKind {
1177 &self.0.kind
1178 }
1179
1180 pub fn place(&self) -> &Place {
1182 &self.0.place
1183 }
1184
1185 pub fn own_errors(&self) -> &[Error] {
1187 &self.0.errors
1188 }
1189
1190 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 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 #[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 #[track_caller]
1223 pub fn and(&self, other: &Formula) -> Formula {
1224 Formula::and_all([self.clone(), other.clone()])
1225 }
1226
1227 #[track_caller]
1229 pub fn or(&self, other: &Formula) -> Formula {
1230 Formula::or_all([self.clone(), other.clone()])
1231 }
1232
1233 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[track_caller]
1308 pub fn after(&self) -> Formula {
1309 self.temporal(TemporalOp::After)
1310 }
1311
1312 #[track_caller]
1314 pub fn always(&self) -> Formula {
1315 self.temporal(TemporalOp::Always)
1316 }
1317
1318 #[track_caller]
1320 pub fn eventually(&self) -> Formula {
1321 self.temporal(TemporalOp::Eventually)
1322 }
1323
1324 #[track_caller]
1326 pub fn before(&self) -> Formula {
1327 self.temporal(TemporalOp::Before)
1328 }
1329
1330 #[track_caller]
1332 pub fn historically(&self) -> Formula {
1333 self.temporal(TemporalOp::Historically)
1334 }
1335
1336 #[track_caller]
1338 pub fn once(&self) -> Formula {
1339 self.temporal(TemporalOp::Once)
1340 }
1341
1342 #[track_caller]
1344 pub fn until(&self, other: &Formula) -> Formula {
1345 self.temporal_binary(TemporalBinaryOp::Until, other)
1346 }
1347
1348 #[track_caller]
1350 pub fn releases(&self, other: &Formula) -> Formula {
1351 self.temporal_binary(TemporalBinaryOp::Releases, other)
1352 }
1353
1354 #[track_caller]
1356 pub fn since(&self, other: &Formula) -> Formula {
1357 self.temporal_binary(TemporalBinaryOp::Since, other)
1358 }
1359
1360 #[track_caller]
1362 pub fn triggered(&self, other: &Formula) -> Formula {
1363 self.temporal_binary(TemporalBinaryOp::Triggered, other)
1364 }
1365
1366 pub fn past_depth(&self) -> usize {
1369 past_depth_formula(self)
1370 }
1371
1372 pub fn is_temporal(&self) -> bool {
1374 temporal_formula(self)
1375 }
1376
1377 #[track_caller]
1379 pub fn all(decls: Vec<Decl>, body: &Formula) -> Formula {
1380 Formula::quantified(Quantifier::All, decls, body)
1381 }
1382
1383 #[track_caller]
1385 pub fn some(decls: Vec<Decl>, body: &Formula) -> Formula {
1386 Formula::quantified(Quantifier::Some, decls, body)
1387 }
1388
1389 #[track_caller]
1391 pub fn no(decls: Vec<Decl>, body: &Formula) -> Formula {
1392 Formula::quantified(Quantifier::No, decls, body)
1393 }
1394
1395 #[track_caller]
1397 pub fn one(decls: Vec<Decl>, body: &Formula) -> Formula {
1398 Formula::quantified(Quantifier::One, decls, body)
1399 }
1400
1401 #[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
1539impl 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}