1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use super::Expr;
use std::ops;
/// A logical "and" of multiple expressions.
///
/// Returns `true` only if all operands evaluate to `true`. An `ExprAnd` always
/// has at least two operands; use [`Expr::and_from_vec`] which returns
/// `Expr::Value(true)` for empty input and unwraps single-element input.
///
/// # Examples
///
/// ```text
/// and(a, b, c) // returns `true` if `a`, `b`, and `c` are all `true`
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ExprAnd {
/// The expressions to "and" together.
pub operands: Vec<Expr>,
}
impl Expr {
/// Creates an AND expression from two operands.
///
/// Flattens nested ANDs: `and(and(a, b), c)` produces `and(a, b, c)`.
/// Short-circuits on `true`: `and(true, x)` returns `x`.
pub fn and(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
let mut lhs = lhs.into();
let rhs = rhs.into();
match (&mut lhs, rhs) {
(expr, rhs) if expr.is_true() => rhs,
(_, expr) if expr.is_true() => lhs,
(Self::And(lhs_and), Self::And(rhs_and)) => {
lhs_and.operands.extend(rhs_and.operands);
lhs
}
(Self::And(lhs_and), rhs) => {
lhs_and.operands.push(rhs);
lhs
}
(_, Self::And(mut rhs_and)) => {
rhs_and.operands.push(lhs);
rhs_and.into()
}
(_, rhs) => ExprAnd {
operands: vec![lhs, rhs],
}
.into(),
}
}
/// Creates an AND expression from a vector of operands.
///
/// Returns `Expr::Value(true)` for an empty vector and unwraps
/// single-element vectors into the element itself.
pub fn and_from_vec(operands: Vec<Self>) -> Self {
if operands.is_empty() {
return true.into();
}
if operands.len() == 1 {
return operands.into_iter().next().unwrap();
}
ExprAnd { operands }.into()
}
}
impl ops::Deref for ExprAnd {
type Target = [Expr];
fn deref(&self) -> &Self::Target {
self.operands.deref()
}
}
impl<'a> IntoIterator for &'a ExprAnd {
type IntoIter = std::slice::Iter<'a, Expr>;
type Item = &'a Expr;
fn into_iter(self) -> Self::IntoIter {
self.operands.iter()
}
}
impl<'a> IntoIterator for &'a mut ExprAnd {
type IntoIter = std::slice::IterMut<'a, Expr>;
type Item = &'a mut Expr;
fn into_iter(self) -> Self::IntoIter {
self.operands.iter_mut()
}
}
impl From<ExprAnd> for Expr {
fn from(value: ExprAnd) -> Self {
Self::And(value)
}
}