use crate::error::{Error, Place};
use crate::relation::{Relation, Variable};
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BinaryOp {
Union,
Intersection,
Difference,
Join,
Product,
Override,
DomainRestriction,
RangeRestriction,
}
impl BinaryOp {
pub fn symbol(self) -> &'static str {
match self {
BinaryOp::Union => "+",
BinaryOp::Intersection => "&",
BinaryOp::Difference => "-",
BinaryOp::Join => ".",
BinaryOp::Product => "->",
BinaryOp::Override => "++",
BinaryOp::DomainRestriction => "<:",
BinaryOp::RangeRestriction => ":>",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UnaryOp {
Transpose,
Closure,
ReflexiveClosure,
}
impl UnaryOp {
pub fn symbol(self) -> &'static str {
match self {
UnaryOp::Transpose => "~",
UnaryOp::Closure => "^",
UnaryOp::ReflexiveClosure => "*",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Multiplicity {
Some,
No,
One,
Lone,
}
impl Multiplicity {
pub fn keyword(self) -> &'static str {
match self {
Multiplicity::Some => "some",
Multiplicity::No => "no",
Multiplicity::One => "one",
Multiplicity::Lone => "lone",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Quantifier {
All,
Some,
No,
One,
Lone,
}
impl Quantifier {
pub fn keyword(self) -> &'static str {
match self {
Quantifier::All => "all",
Quantifier::Some => "some",
Quantifier::No => "no",
Quantifier::One => "one",
Quantifier::Lone => "lone",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TemporalOp {
After,
Always,
Eventually,
Before,
Historically,
Once,
}
impl TemporalOp {
pub fn keyword(self) -> &'static str {
match self {
TemporalOp::After => "after",
TemporalOp::Always => "always",
TemporalOp::Eventually => "eventually",
TemporalOp::Before => "before",
TemporalOp::Historically => "historically",
TemporalOp::Once => "once",
}
}
pub fn is_past(self) -> bool {
matches!(
self,
TemporalOp::Before | TemporalOp::Historically | TemporalOp::Once
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TemporalBinaryOp {
Until,
Releases,
Since,
Triggered,
}
impl TemporalBinaryOp {
pub fn keyword(self) -> &'static str {
match self {
TemporalBinaryOp::Until => "until",
TemporalBinaryOp::Releases => "releases",
TemporalBinaryOp::Since => "since",
TemporalBinaryOp::Triggered => "triggered",
}
}
pub fn is_past(self) -> bool {
matches!(self, TemporalBinaryOp::Since | TemporalBinaryOp::Triggered)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeclMult {
One,
Lone,
Some,
Set,
}
impl DeclMult {
pub fn keyword(self) -> &'static str {
match self {
DeclMult::One => "one",
DeclMult::Lone => "lone",
DeclMult::Some => "some",
DeclMult::Set => "set",
}
}
pub fn allows(self, n: usize) -> bool {
match self {
DeclMult::One => n == 1,
DeclMult::Lone => n <= 1,
DeclMult::Some => n >= 1,
DeclMult::Set => true,
}
}
}
#[derive(Clone, Debug)]
pub struct Decl {
pub var: Variable,
pub expr: Expr,
pub mult: DeclMult,
}
impl Decl {
pub fn new(var: &Variable, expr: &Expr) -> Decl {
Decl::with(var, DeclMult::One, expr)
}
pub fn with(var: &Variable, mult: DeclMult, expr: &Expr) -> Decl {
Decl {
var: var.clone(),
expr: expr.clone(),
mult,
}
}
pub fn is_first_order(&self) -> bool {
self.mult == DeclMult::One && self.var.arity() == 1
}
}
#[derive(Clone, Debug)]
pub enum ExprKind {
Relation(Relation),
Variable(Variable),
None,
Univ,
Iden,
Binary(BinaryOp, Expr, Expr),
Unary(UnaryOp, Expr),
Comprehension(Vec<Decl>, Formula),
IfThenElse(Formula, Expr, Expr),
Prime(Expr),
IntToSet(IntExpr),
}
pub(crate) struct ExprNode {
pub(crate) kind: ExprKind,
pub(crate) arity: Option<usize>,
pub(crate) errors: Vec<Error>,
pub(crate) place: Place,
}
#[derive(Clone)]
pub struct Expr(pub(crate) Arc<ExprNode>);
#[derive(Clone, Debug)]
pub enum FormulaKind {
Constant(bool),
Subset(Expr, Expr),
Equal(Expr, Expr),
Multiplicity(Multiplicity, Expr),
Not(Formula),
And(Vec<Formula>),
Or(Vec<Formula>),
Implies(Formula, Formula),
Iff(Formula, Formula),
Quantified(Quantifier, Vec<Decl>, Formula),
Temporal(TemporalOp, Formula),
TemporalBinary(TemporalBinaryOp, Formula, Formula),
IntCompare(IntComparison, IntExpr, IntExpr),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum IntOp {
Plus,
Minus,
Times,
Divide,
Remainder,
ShiftLeft,
ShiftRight,
UnsignedShiftRight,
}
impl IntOp {
pub fn symbol(self) -> &'static str {
match self {
IntOp::Plus => "+",
IntOp::Minus => "-",
IntOp::Times => "*",
IntOp::Divide => "/",
IntOp::Remainder => "%",
IntOp::ShiftLeft => "<<",
IntOp::ShiftRight => ">>",
IntOp::UnsignedShiftRight => ">>>",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IntComparison {
Equal,
Less,
LessOrEqual,
Greater,
GreaterOrEqual,
}
impl IntComparison {
pub fn symbol(self) -> &'static str {
match self {
IntComparison::Equal => "=",
IntComparison::Less => "<",
IntComparison::LessOrEqual => "=<",
IntComparison::Greater => ">",
IntComparison::GreaterOrEqual => ">=",
}
}
pub fn holds(self, a: i64, b: i64) -> bool {
match self {
IntComparison::Equal => a == b,
IntComparison::Less => a < b,
IntComparison::LessOrEqual => a <= b,
IntComparison::Greater => a > b,
IntComparison::GreaterOrEqual => a >= b,
}
}
}
#[derive(Clone, Debug)]
pub enum IntExprKind {
Constant(i64),
Count(Expr),
Sum(Expr),
Binary(IntOp, IntExpr, IntExpr),
Negate(IntExpr),
IfThenElse(Formula, IntExpr, IntExpr),
SumOver(Vec<Decl>, IntExpr),
}
pub(crate) struct IntNode {
pub(crate) kind: IntExprKind,
pub(crate) well_formed: bool,
pub(crate) errors: Vec<Error>,
pub(crate) place: Place,
}
#[derive(Clone)]
pub struct IntExpr(pub(crate) Arc<IntNode>);
fn int_node(kind: IntExprKind, well_formed: bool, errors: Vec<Error>, place: Place) -> IntExpr {
IntExpr(Arc::new(IntNode {
kind,
well_formed,
errors,
place,
}))
}
impl IntExpr {
#[track_caller]
pub fn constant(k: i64) -> IntExpr {
int_node(IntExprKind::Constant(k), true, Vec::new(), Place::caller())
}
pub fn is_well_formed(&self) -> bool {
self.0.well_formed
}
pub fn kind(&self) -> &IntExprKind {
&self.0.kind
}
pub fn place(&self) -> &Place {
&self.0.place
}
pub fn own_errors(&self) -> &[Error] {
&self.0.errors
}
pub fn placed(&self, place: Place) -> IntExpr {
let errors = self
.0
.errors
.iter()
.map(|e| e.clone().at(place.clone()))
.collect();
int_node(self.0.kind.clone(), self.0.well_formed, errors, place)
}
pub(crate) fn node_id(&self) -> usize {
Arc::as_ptr(&self.0) as usize
}
#[track_caller]
fn binary(&self, op: IntOp, other: &IntExpr) -> IntExpr {
int_node(
IntExprKind::Binary(op, self.clone(), other.clone()),
self.is_well_formed() && other.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn apply(&self, op: IntOp, other: &IntExpr) -> IntExpr {
self.binary(op, other)
}
#[track_caller]
pub fn plus(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::Plus, other)
}
#[track_caller]
pub fn minus(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::Minus, other)
}
#[track_caller]
pub fn times(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::Times, other)
}
#[track_caller]
pub fn divide(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::Divide, other)
}
#[track_caller]
pub fn remainder(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::Remainder, other)
}
#[track_caller]
pub fn shift_left(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::ShiftLeft, other)
}
#[track_caller]
pub fn shift_right(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::ShiftRight, other)
}
#[track_caller]
pub fn unsigned_shift_right(&self, other: &IntExpr) -> IntExpr {
self.binary(IntOp::UnsignedShiftRight, other)
}
#[track_caller]
pub fn negate(&self) -> IntExpr {
int_node(
IntExprKind::Negate(self.clone()),
self.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn if_then_else(condition: &Formula, then: &IntExpr, otherwise: &IntExpr) -> IntExpr {
int_node(
IntExprKind::IfThenElse(condition.clone(), then.clone(), otherwise.clone()),
condition.is_well_formed() && then.is_well_formed() && otherwise.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn sum_over(decls: Vec<Decl>, body: &IntExpr) -> IntExpr {
let place = Place::caller();
let (ok, errors) = check_decls(&decls, &place, Some("a sum"));
int_node(
IntExprKind::SumOver(decls, body.clone()),
ok && body.is_well_formed(),
errors,
place,
)
}
#[track_caller]
fn compare(&self, op: IntComparison, other: &IntExpr) -> Formula {
formula_node(
FormulaKind::IntCompare(op, self.clone(), other.clone()),
self.is_well_formed() && other.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn compare_with(&self, op: IntComparison, other: &IntExpr) -> Formula {
self.compare(op, other)
}
#[track_caller]
pub fn equals(&self, other: &IntExpr) -> Formula {
self.compare(IntComparison::Equal, other)
}
#[track_caller]
pub fn lt(&self, other: &IntExpr) -> Formula {
self.compare(IntComparison::Less, other)
}
#[track_caller]
pub fn lte(&self, other: &IntExpr) -> Formula {
self.compare(IntComparison::LessOrEqual, other)
}
#[track_caller]
pub fn gt(&self, other: &IntExpr) -> Formula {
self.compare(IntComparison::Greater, other)
}
#[track_caller]
pub fn gte(&self, other: &IntExpr) -> Formula {
self.compare(IntComparison::GreaterOrEqual, other)
}
#[track_caller]
pub fn to_set(&self) -> Expr {
let arity = self.is_well_formed().then_some(1);
expr_node(
ExprKind::IntToSet(self.clone()),
arity,
Vec::new(),
Place::caller(),
)
}
}
pub(crate) struct FormulaNode {
pub(crate) kind: FormulaKind,
pub(crate) well_formed: bool,
pub(crate) errors: Vec<Error>,
pub(crate) place: Place,
}
#[derive(Clone)]
pub struct Formula(pub(crate) Arc<FormulaNode>);
fn expr_node(kind: ExprKind, arity: Option<usize>, errors: Vec<Error>, place: Place) -> Expr {
Expr(Arc::new(ExprNode {
kind,
arity,
errors,
place,
}))
}
fn formula_node(kind: FormulaKind, well_formed: bool, errors: Vec<Error>, place: Place) -> Formula {
Formula(Arc::new(FormulaNode {
kind,
well_formed,
errors,
place,
}))
}
fn check_decls(decls: &[Decl], place: &Place, atoms_only: Option<&str>) -> (bool, Vec<Error>) {
let mut errors = Vec::new();
let mut parts_ok = true;
if decls.is_empty() {
errors.push(
Error::new("logic.no_declarations", "a quantifier with no declarations")
.at(place.clone()),
);
}
for d in decls {
let Some(k) = d.expr.arity() else {
parts_ok = false;
continue;
};
if d.is_first_order() {
if k != 1 {
errors.push(
Error::new(
"arity.not_a_set",
format!("`{}` is declared over an expression of arity {k}", d.var),
)
.at(place.clone()),
);
}
} else if let Some(within) = atoms_only {
errors.push(
Error::new(
"logic.higher_order",
format!("`{}` is declared over sets or relations in {within}", d.var),
)
.at(place.clone()),
);
} else if k != d.var.arity() {
errors.push(
Error::new(
"arity.mismatch",
format!(
"`{}` of arity {} is declared over an expression of arity {k}",
d.var,
d.var.arity()
),
)
.at(place.clone()),
);
}
}
(parts_ok && errors.is_empty(), errors)
}
impl Expr {
#[track_caller]
pub fn relation(r: &Relation) -> Expr {
let place = Place::caller();
if r.arity() == 0 {
let e = Error::new("arity.zero", format!("the relation `{r}` has arity 0"))
.at(r.place().clone());
return expr_node(ExprKind::Relation(r.clone()), None, vec![e], place);
}
expr_node(
ExprKind::Relation(r.clone()),
Some(r.arity()),
Vec::new(),
place,
)
}
#[track_caller]
pub fn variable(v: &Variable) -> Expr {
let place = Place::caller();
if v.arity() == 0 {
let e = Error::new("arity.zero", format!("the variable `{v}` has arity 0"))
.at(place.clone());
return expr_node(ExprKind::Variable(v.clone()), None, vec![e], place);
}
expr_node(
ExprKind::Variable(v.clone()),
Some(v.arity()),
Vec::new(),
place,
)
}
#[track_caller]
pub fn none() -> Expr {
expr_node(ExprKind::None, Some(1), Vec::new(), Place::caller())
}
#[track_caller]
pub fn univ() -> Expr {
expr_node(ExprKind::Univ, Some(1), Vec::new(), Place::caller())
}
#[track_caller]
pub fn iden() -> Expr {
expr_node(ExprKind::Iden, Some(2), Vec::new(), Place::caller())
}
pub fn arity(&self) -> Option<usize> {
self.0.arity
}
pub fn kind(&self) -> &ExprKind {
&self.0.kind
}
pub fn place(&self) -> &Place {
&self.0.place
}
pub fn own_errors(&self) -> &[Error] {
&self.0.errors
}
pub fn placed(&self, place: Place) -> Expr {
let errors = self
.0
.errors
.iter()
.map(|e| e.clone().at(place.clone()))
.collect();
expr_node(self.0.kind.clone(), self.0.arity, errors, place)
}
pub fn same_node(&self, other: &Expr) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
pub(crate) fn node_id(&self) -> usize {
Arc::as_ptr(&self.0) as usize
}
#[track_caller]
fn binary(&self, op: BinaryOp, other: &Expr) -> Expr {
let place = Place::caller();
let kind = ExprKind::Binary(op, self.clone(), other.clone());
let (Some(a), Some(b)) = (self.arity(), other.arity()) else {
return expr_node(kind, None, Vec::new(), place);
};
let arity = match op {
BinaryOp::Union
| BinaryOp::Intersection
| BinaryOp::Difference
| BinaryOp::Override => {
if a == b {
Ok(a)
} else {
Err(Error::new(
"arity.mismatch",
format!("`{}` of arities {a} and {b}", op.symbol()),
))
}
}
BinaryOp::Join => {
if a + b > 2 {
Ok(a + b - 2)
} else {
Err(Error::new("arity.join", "a join of two sets"))
}
}
BinaryOp::Product => Ok(a + b),
BinaryOp::DomainRestriction => {
if a == 1 {
Ok(b)
} else {
Err(Error::new(
"arity.not_a_set",
format!("the left side of `<:` has arity {a}"),
))
}
}
BinaryOp::RangeRestriction => {
if b == 1 {
Ok(a)
} else {
Err(Error::new(
"arity.not_a_set",
format!("the right side of `:>` has arity {b}"),
))
}
}
};
match arity {
Ok(k) => expr_node(kind, Some(k), Vec::new(), place),
Err(e) => {
let e = e.at(place.clone());
expr_node(kind, None, vec![e], place)
}
}
}
#[track_caller]
fn unary(&self, op: UnaryOp) -> Expr {
let place = Place::caller();
let kind = ExprKind::Unary(op, self.clone());
match self.arity() {
None => expr_node(kind, None, Vec::new(), place),
Some(2) => expr_node(kind, Some(2), Vec::new(), place),
Some(k) => {
let e = Error::new(
"arity.not_binary",
format!("`{}` on an expression of arity {k}", op.symbol()),
)
.at(place.clone());
expr_node(kind, None, vec![e], place)
}
}
}
#[track_caller]
pub fn apply_binary(&self, op: BinaryOp, other: &Expr) -> Expr {
self.binary(op, other)
}
#[track_caller]
pub fn apply_unary(&self, op: UnaryOp) -> Expr {
self.unary(op)
}
#[track_caller]
pub fn apply_multiplicity(&self, m: Multiplicity) -> Formula {
self.multiplicity(m)
}
#[track_caller]
pub fn union(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::Union, other)
}
#[track_caller]
pub fn intersection(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::Intersection, other)
}
#[track_caller]
pub fn difference(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::Difference, other)
}
#[track_caller]
pub fn join(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::Join, other)
}
#[track_caller]
pub fn product(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::Product, other)
}
#[track_caller]
pub fn override_with(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::Override, other)
}
#[track_caller]
pub fn domain_restriction(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::DomainRestriction, other)
}
#[track_caller]
pub fn range_restriction(&self, other: &Expr) -> Expr {
self.binary(BinaryOp::RangeRestriction, other)
}
#[track_caller]
pub fn prime(&self) -> Expr {
expr_node(
ExprKind::Prime(self.clone()),
self.arity(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn transpose(&self) -> Expr {
self.unary(UnaryOp::Transpose)
}
#[track_caller]
pub fn closure(&self) -> Expr {
self.unary(UnaryOp::Closure)
}
#[track_caller]
pub fn reflexive_closure(&self) -> Expr {
self.unary(UnaryOp::ReflexiveClosure)
}
#[track_caller]
pub fn comprehension(decls: Vec<Decl>, formula: &Formula) -> Expr {
let place = Place::caller();
let (ok, errors) = check_decls(&decls, &place, Some("a comprehension"));
let arity = (ok && formula.is_well_formed()).then_some(decls.len());
expr_node(
ExprKind::Comprehension(decls, formula.clone()),
arity,
errors,
place,
)
}
#[track_caller]
pub fn if_then_else(condition: &Formula, then: &Expr, otherwise: &Expr) -> Expr {
let place = Place::caller();
let kind = ExprKind::IfThenElse(condition.clone(), then.clone(), otherwise.clone());
let (Some(a), Some(b)) = (then.arity(), otherwise.arity()) else {
return expr_node(kind, None, Vec::new(), place);
};
if a != b {
let e = Error::new(
"arity.mismatch",
format!("`=> else` with branches of arities {a} and {b}"),
)
.at(place.clone());
return expr_node(kind, None, vec![e], place);
}
let arity = condition.is_well_formed().then_some(a);
expr_node(kind, arity, Vec::new(), place)
}
#[track_caller]
fn compare(&self, other: &Expr, equal: bool) -> Formula {
let place = Place::caller();
let kind = if equal {
FormulaKind::Equal(self.clone(), other.clone())
} else {
FormulaKind::Subset(self.clone(), other.clone())
};
let (Some(a), Some(b)) = (self.arity(), other.arity()) else {
return formula_node(kind, false, Vec::new(), place);
};
if a != b {
let op = if equal { "=" } else { "in" };
let e = Error::new("arity.mismatch", format!("`{op}` of arities {a} and {b}"))
.at(place.clone());
return formula_node(kind, false, vec![e], place);
}
formula_node(kind, true, Vec::new(), place)
}
#[track_caller]
pub fn is_in(&self, other: &Expr) -> Formula {
self.compare(other, false)
}
#[track_caller]
pub fn equals(&self, other: &Expr) -> Formula {
self.compare(other, true)
}
#[track_caller]
fn multiplicity(&self, m: Multiplicity) -> Formula {
formula_node(
FormulaKind::Multiplicity(m, self.clone()),
self.arity().is_some(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn count(&self) -> IntExpr {
int_node(
IntExprKind::Count(self.clone()),
self.arity().is_some(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn sum(&self) -> IntExpr {
let place = Place::caller();
let kind = IntExprKind::Sum(self.clone());
match self.arity() {
None => int_node(kind, false, Vec::new(), place),
Some(1) => int_node(kind, true, Vec::new(), place),
Some(k) => {
let e = Error::new(
"arity.not_a_set",
format!("`sum` of an expression of arity {k}"),
)
.at(place.clone());
int_node(kind, false, vec![e], place)
}
}
}
#[track_caller]
pub fn some(&self) -> Formula {
self.multiplicity(Multiplicity::Some)
}
#[track_caller]
pub fn no(&self) -> Formula {
self.multiplicity(Multiplicity::No)
}
#[track_caller]
pub fn one(&self) -> Formula {
self.multiplicity(Multiplicity::One)
}
#[track_caller]
pub fn lone(&self) -> Formula {
self.multiplicity(Multiplicity::Lone)
}
}
impl From<&Relation> for Expr {
#[track_caller]
fn from(r: &Relation) -> Expr {
Expr::relation(r)
}
}
impl From<&Variable> for Expr {
#[track_caller]
fn from(v: &Variable) -> Expr {
Expr::variable(v)
}
}
impl Formula {
#[track_caller]
pub fn constant(value: bool) -> Formula {
formula_node(
FormulaKind::Constant(value),
true,
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn truth() -> Formula {
Formula::constant(true)
}
#[track_caller]
pub fn falsity() -> Formula {
Formula::constant(false)
}
pub fn is_well_formed(&self) -> bool {
self.0.well_formed
}
pub fn kind(&self) -> &FormulaKind {
&self.0.kind
}
pub fn place(&self) -> &Place {
&self.0.place
}
pub fn own_errors(&self) -> &[Error] {
&self.0.errors
}
pub fn placed(&self, place: Place) -> Formula {
let errors = self
.0
.errors
.iter()
.map(|e| e.clone().at(place.clone()))
.collect();
formula_node(self.0.kind.clone(), self.0.well_formed, errors, place)
}
pub fn same_node(&self, other: &Formula) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
pub(crate) fn node_id(&self) -> usize {
Arc::as_ptr(&self.0) as usize
}
#[track_caller]
pub fn not(&self) -> Formula {
formula_node(
FormulaKind::Not(self.clone()),
self.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn and(&self, other: &Formula) -> Formula {
Formula::and_all([self.clone(), other.clone()])
}
#[track_caller]
pub fn or(&self, other: &Formula) -> Formula {
Formula::or_all([self.clone(), other.clone()])
}
#[track_caller]
pub fn and_all(formulas: impl IntoIterator<Item = Formula>) -> Formula {
let fs: Vec<Formula> = formulas.into_iter().collect();
let ok = fs.iter().all(Formula::is_well_formed);
formula_node(FormulaKind::And(fs), ok, Vec::new(), Place::caller())
}
#[track_caller]
pub fn or_all(formulas: impl IntoIterator<Item = Formula>) -> Formula {
let fs: Vec<Formula> = formulas.into_iter().collect();
let ok = fs.iter().all(Formula::is_well_formed);
formula_node(FormulaKind::Or(fs), ok, Vec::new(), Place::caller())
}
#[track_caller]
pub fn implies(&self, other: &Formula) -> Formula {
formula_node(
FormulaKind::Implies(self.clone(), other.clone()),
self.is_well_formed() && other.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn iff(&self, other: &Formula) -> Formula {
formula_node(
FormulaKind::Iff(self.clone(), other.clone()),
self.is_well_formed() && other.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn quantified(q: Quantifier, decls: Vec<Decl>, body: &Formula) -> Formula {
let place = Place::caller();
let (ok, errors) = check_decls(&decls, &place, None);
formula_node(
FormulaKind::Quantified(q, decls, body.clone()),
ok && body.is_well_formed(),
errors,
place,
)
}
#[track_caller]
pub fn temporal(&self, op: TemporalOp) -> Formula {
formula_node(
FormulaKind::Temporal(op, self.clone()),
self.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn temporal_binary(&self, op: TemporalBinaryOp, other: &Formula) -> Formula {
formula_node(
FormulaKind::TemporalBinary(op, self.clone(), other.clone()),
self.is_well_formed() && other.is_well_formed(),
Vec::new(),
Place::caller(),
)
}
#[track_caller]
pub fn after(&self) -> Formula {
self.temporal(TemporalOp::After)
}
#[track_caller]
pub fn always(&self) -> Formula {
self.temporal(TemporalOp::Always)
}
#[track_caller]
pub fn eventually(&self) -> Formula {
self.temporal(TemporalOp::Eventually)
}
#[track_caller]
pub fn before(&self) -> Formula {
self.temporal(TemporalOp::Before)
}
#[track_caller]
pub fn historically(&self) -> Formula {
self.temporal(TemporalOp::Historically)
}
#[track_caller]
pub fn once(&self) -> Formula {
self.temporal(TemporalOp::Once)
}
#[track_caller]
pub fn until(&self, other: &Formula) -> Formula {
self.temporal_binary(TemporalBinaryOp::Until, other)
}
#[track_caller]
pub fn releases(&self, other: &Formula) -> Formula {
self.temporal_binary(TemporalBinaryOp::Releases, other)
}
#[track_caller]
pub fn since(&self, other: &Formula) -> Formula {
self.temporal_binary(TemporalBinaryOp::Since, other)
}
#[track_caller]
pub fn triggered(&self, other: &Formula) -> Formula {
self.temporal_binary(TemporalBinaryOp::Triggered, other)
}
pub fn past_depth(&self) -> usize {
past_depth_formula(self)
}
pub fn is_temporal(&self) -> bool {
temporal_formula(self)
}
#[track_caller]
pub fn all(decls: Vec<Decl>, body: &Formula) -> Formula {
Formula::quantified(Quantifier::All, decls, body)
}
#[track_caller]
pub fn some(decls: Vec<Decl>, body: &Formula) -> Formula {
Formula::quantified(Quantifier::Some, decls, body)
}
#[track_caller]
pub fn no(decls: Vec<Decl>, body: &Formula) -> Formula {
Formula::quantified(Quantifier::No, decls, body)
}
#[track_caller]
pub fn one(decls: Vec<Decl>, body: &Formula) -> Formula {
Formula::quantified(Quantifier::One, decls, body)
}
#[track_caller]
pub fn lone(decls: Vec<Decl>, body: &Formula) -> Formula {
Formula::quantified(Quantifier::Lone, decls, body)
}
}
pub(crate) fn past_depth_expr(e: &Expr) -> usize {
match e.kind() {
ExprKind::Binary(_, a, b) => past_depth_expr(a).max(past_depth_expr(b)),
ExprKind::Unary(_, a) | ExprKind::Prime(a) => past_depth_expr(a),
ExprKind::Comprehension(decls, body) => decls
.iter()
.map(|d| past_depth_expr(&d.expr))
.fold(past_depth_formula(body), usize::max),
ExprKind::IfThenElse(c, a, b) => past_depth_formula(c)
.max(past_depth_expr(a))
.max(past_depth_expr(b)),
ExprKind::IntToSet(n) => past_depth_int(n),
ExprKind::Relation(_)
| ExprKind::Variable(_)
| ExprKind::None
| ExprKind::Univ
| ExprKind::Iden => 0,
}
}
fn past_depth_formula(f: &Formula) -> usize {
match f.kind() {
FormulaKind::Constant(_) => 0,
FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
past_depth_expr(a).max(past_depth_expr(b))
}
FormulaKind::Multiplicity(_, a) => past_depth_expr(a),
FormulaKind::Not(g) => past_depth_formula(g),
FormulaKind::And(fs) | FormulaKind::Or(fs) => {
fs.iter().map(past_depth_formula).max().unwrap_or(0)
}
FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
past_depth_formula(a).max(past_depth_formula(b))
}
FormulaKind::Quantified(_, decls, body) => decls
.iter()
.map(|d| past_depth_expr(&d.expr))
.fold(past_depth_formula(body), usize::max),
FormulaKind::Temporal(op, g) => past_depth_formula(g) + usize::from(op.is_past()),
FormulaKind::TemporalBinary(op, a, b) => {
past_depth_formula(a).max(past_depth_formula(b)) + usize::from(op.is_past())
}
FormulaKind::IntCompare(_, a, b) => past_depth_int(a).max(past_depth_int(b)),
}
}
pub(crate) fn past_depth_int(n: &IntExpr) -> usize {
match n.kind() {
IntExprKind::Constant(_) => 0,
IntExprKind::Count(e) | IntExprKind::Sum(e) => past_depth_expr(e),
IntExprKind::Binary(_, a, b) => past_depth_int(a).max(past_depth_int(b)),
IntExprKind::Negate(a) => past_depth_int(a),
IntExprKind::IfThenElse(c, a, b) => past_depth_formula(c)
.max(past_depth_int(a))
.max(past_depth_int(b)),
IntExprKind::SumOver(decls, body) => decls
.iter()
.map(|d| past_depth_expr(&d.expr))
.fold(past_depth_int(body), usize::max),
}
}
fn temporal_int(n: &IntExpr) -> bool {
match n.kind() {
IntExprKind::Constant(_) => false,
IntExprKind::Count(e) | IntExprKind::Sum(e) => temporal_expr(e),
IntExprKind::Binary(_, a, b) => temporal_int(a) || temporal_int(b),
IntExprKind::Negate(a) => temporal_int(a),
IntExprKind::IfThenElse(c, a, b) => {
temporal_formula(c) || temporal_int(a) || temporal_int(b)
}
IntExprKind::SumOver(decls, body) => {
decls.iter().any(|d| temporal_expr(&d.expr)) || temporal_int(body)
}
}
}
fn temporal_expr(e: &Expr) -> bool {
match e.kind() {
ExprKind::Prime(_) => true,
ExprKind::Binary(_, a, b) => temporal_expr(a) || temporal_expr(b),
ExprKind::Unary(_, a) => temporal_expr(a),
ExprKind::Comprehension(decls, body) => {
decls.iter().any(|d| temporal_expr(&d.expr)) || temporal_formula(body)
}
ExprKind::IfThenElse(c, a, b) => {
temporal_formula(c) || temporal_expr(a) || temporal_expr(b)
}
ExprKind::IntToSet(n) => temporal_int(n),
ExprKind::Relation(_)
| ExprKind::Variable(_)
| ExprKind::None
| ExprKind::Univ
| ExprKind::Iden => false,
}
}
fn temporal_formula(f: &Formula) -> bool {
match f.kind() {
FormulaKind::Constant(_) => false,
FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
temporal_expr(a) || temporal_expr(b)
}
FormulaKind::Multiplicity(_, a) => temporal_expr(a),
FormulaKind::Not(g) => temporal_formula(g),
FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(temporal_formula),
FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
temporal_formula(a) || temporal_formula(b)
}
FormulaKind::Quantified(_, decls, body) => {
decls.iter().any(|d| temporal_expr(&d.expr)) || temporal_formula(body)
}
FormulaKind::Temporal(..) | FormulaKind::TemporalBinary(..) => true,
FormulaKind::IntCompare(_, a, b) => temporal_int(a) || temporal_int(b),
}
}
fn write_decls(f: &mut fmt::Formatter<'_>, decls: &[Decl]) -> fmt::Result {
for (i, d) in decls.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
if d.is_first_order() {
write!(f, "{}: {}", d.var, d.expr)?;
} else {
write!(f, "{}: {} {}", d.var, d.mult.keyword(), d.expr)?;
}
}
Ok(())
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind() {
ExprKind::Relation(r) => write!(f, "{r}"),
ExprKind::Variable(v) => write!(f, "{v}"),
ExprKind::None => write!(f, "none"),
ExprKind::Univ => write!(f, "univ"),
ExprKind::Iden => write!(f, "iden"),
ExprKind::Binary(BinaryOp::Join, a, b) => write!(f, "({a}.{b})"),
ExprKind::Binary(op, a, b) => write!(f, "({a} {} {b})", op.symbol()),
ExprKind::Unary(op, a) => write!(f, "{}{a}", op.symbol()),
ExprKind::Comprehension(decls, body) => {
write!(f, "{{")?;
write_decls(f, decls)?;
write!(f, " | {body}}}")
}
ExprKind::IfThenElse(c, a, b) => write!(f, "({c} => {a} else {b})"),
ExprKind::Prime(a) => write!(f, "{a}'"),
ExprKind::IntToSet(n) => write!(f, "Int[{n}]"),
}
}
}
impl fmt::Debug for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for Formula {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind() {
FormulaKind::Constant(b) => write!(f, "{b}"),
FormulaKind::Subset(a, b) => write!(f, "{a} in {b}"),
FormulaKind::Equal(a, b) => write!(f, "{a} = {b}"),
FormulaKind::Multiplicity(m, a) => write!(f, "{} {a}", m.keyword()),
FormulaKind::Not(g) => write!(f, "not ({g})"),
FormulaKind::And(fs) | FormulaKind::Or(fs) if fs.is_empty() => {
write!(f, "{}", matches!(self.kind(), FormulaKind::And(_)))
}
FormulaKind::And(fs) | FormulaKind::Or(fs) => {
let op = if matches!(self.kind(), FormulaKind::And(_)) {
"and"
} else {
"or"
};
write!(f, "(")?;
for (i, g) in fs.iter().enumerate() {
if i > 0 {
write!(f, " {op} ")?;
}
write!(f, "{g}")?;
}
write!(f, ")")
}
FormulaKind::Implies(a, b) => write!(f, "({a} implies {b})"),
FormulaKind::Iff(a, b) => write!(f, "({a} iff {b})"),
FormulaKind::Quantified(q, decls, body) => {
write!(f, "({} ", q.keyword())?;
write_decls(f, decls)?;
write!(f, " | {body})")
}
FormulaKind::Temporal(op, g) => write!(f, "({} {g})", op.keyword()),
FormulaKind::TemporalBinary(op, a, b) => write!(f, "({a} {} {b})", op.keyword()),
FormulaKind::IntCompare(op, a, b) => write!(f, "{a} {} {b}", op.symbol()),
}
}
}
impl fmt::Display for IntExpr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind() {
IntExprKind::Constant(k) => write!(f, "{k}"),
IntExprKind::Count(e) => write!(f, "#{e}"),
IntExprKind::Sum(e) => write!(f, "(sum {e})"),
IntExprKind::Binary(op, a, b) => write!(f, "({a} {} {b})", op.symbol()),
IntExprKind::Negate(a) => write!(f, "-{a}"),
IntExprKind::IfThenElse(c, a, b) => write!(f, "({c} => {a} else {b})"),
IntExprKind::SumOver(decls, body) => {
write!(f, "(sum ")?;
write_decls(f, decls)?;
write!(f, " | {body})")
}
}
}
}
impl fmt::Debug for IntExpr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Debug for Formula {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}