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
use super::Expr;
use std::ops;
/// A logical "or" of multiple expressions.
///
/// Returns `true` if at least one operand evaluates to `true`. An `ExprOr`
/// always has at least two operands; use [`Expr::or_from_vec`] which returns
/// `Expr::Value(false)` for empty input and unwraps single-element input.
///
/// # Examples
///
/// ```text
/// or(a, b, c) // returns `true` if any of `a`, `b`, or `c` is `true`
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ExprOr {
/// The expressions to "or" together.
pub operands: Vec<Expr>,
}
impl Expr {
/// Creates an OR expression from two operands.
///
/// Flattens nested ORs: `or(or(a, b), c)` produces `or(a, b, c)`.
pub fn or(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
let mut lhs = lhs.into();
let rhs = rhs.into();
match (&mut lhs, rhs) {
(Self::Or(lhs_or), Self::Or(rhs_or)) => {
lhs_or.operands.extend(rhs_or.operands);
lhs
}
(Self::Or(lhs_or), rhs) => {
lhs_or.operands.push(rhs);
lhs
}
(_, Self::Or(mut lhs_or)) => {
lhs_or.operands.push(lhs);
lhs_or.into()
}
(_, rhs) => ExprOr {
operands: vec![lhs, rhs],
}
.into(),
}
}
/// Creates an OR expression from a vector of operands.
///
/// Returns `Expr::Value(false)` for an empty vector and unwraps
/// single-element vectors into the element itself.
pub fn or_from_vec(operands: Vec<Self>) -> Self {
if operands.is_empty() {
return false.into();
}
if operands.len() == 1 {
return operands.into_iter().next().unwrap();
}
ExprOr { operands }.into()
}
}
impl ops::Deref for ExprOr {
type Target = [Expr];
fn deref(&self) -> &Self::Target {
self.operands.deref()
}
}
impl<'a> IntoIterator for &'a ExprOr {
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 ExprOr {
type IntoIter = std::slice::IterMut<'a, Expr>;
type Item = &'a mut Expr;
fn into_iter(self) -> Self::IntoIter {
self.operands.iter_mut()
}
}
impl From<ExprOr> for Expr {
fn from(value: ExprOr) -> Self {
Self::Or(value)
}
}