toasty_core/stmt/
op_binary.rs

1use std::fmt;
2
3/// A binary comparison operator.
4///
5/// Used by [`ExprBinaryOp`](super::ExprBinaryOp) to specify the comparison
6/// applied between two expressions.
7///
8/// # Examples
9///
10/// ```
11/// use toasty_core::stmt::BinaryOp;
12///
13/// let op = BinaryOp::Eq;
14/// assert!(op.is_eq());
15/// assert_eq!(op.to_string(), "=");
16///
17/// // Negation
18/// assert_eq!(op.negate(), Some(BinaryOp::Ne));
19///
20/// // Commutation (swapping operands)
21/// assert_eq!(BinaryOp::Lt.commute(), BinaryOp::Gt);
22/// ```
23#[derive(Copy, Clone, PartialEq, Eq, Hash)]
24pub enum BinaryOp {
25    /// Equality (`=`).
26    Eq,
27    /// Inequality (`!=`).
28    Ne,
29    /// Greater than or equal (`>=`).
30    Ge,
31    /// Greater than (`>`).
32    Gt,
33    /// Less than or equal (`<=`).
34    Le,
35    /// Less than (`<`).
36    Lt,
37}
38
39impl BinaryOp {
40    /// Returns `true` if this is the equality operator.
41    pub fn is_eq(self) -> bool {
42        matches!(self, Self::Eq)
43    }
44
45    /// Returns `true` if this is the inequality operator.
46    pub fn is_ne(self) -> bool {
47        matches!(self, Self::Ne)
48    }
49
50    /// Returns the logical negation of this operator, if one exists.
51    ///
52    /// - `=` → `!=`
53    /// - `!=` → `=`
54    /// - `<` → `>=`
55    /// - `>=` → `<`
56    /// - `>` → `<=`
57    /// - `<=` → `>`
58    pub fn negate(self) -> Option<Self> {
59        match self {
60            Self::Eq => Some(Self::Ne),
61            Self::Ne => Some(Self::Eq),
62            Self::Lt => Some(Self::Ge),
63            Self::Ge => Some(Self::Lt),
64            Self::Gt => Some(Self::Le),
65            Self::Le => Some(Self::Gt),
66        }
67    }
68
69    /// Returns the operator that represents an equivalent comparison when the
70    /// operands are commuted (swapped).
71    ///
72    /// For example, `5 < x` becomes `x > 5`, so `Lt.commute()` returns `Gt`.
73    /// Symmetric operators like `Eq` and `Ne` return themselves.
74    pub fn commute(self) -> Self {
75        match self {
76            Self::Eq => Self::Eq,
77            Self::Ne => Self::Ne,
78            Self::Ge => Self::Le,
79            Self::Gt => Self::Lt,
80            Self::Le => Self::Ge,
81            Self::Lt => Self::Gt,
82        }
83    }
84}
85
86impl fmt::Display for BinaryOp {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match self {
89            BinaryOp::Eq => "=".fmt(f),
90            BinaryOp::Ne => "!=".fmt(f),
91            BinaryOp::Ge => ">=".fmt(f),
92            BinaryOp::Gt => ">".fmt(f),
93            BinaryOp::Le => "<=".fmt(f),
94            BinaryOp::Lt => "<".fmt(f),
95        }
96    }
97}
98
99impl fmt::Debug for BinaryOp {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        fmt::Display::fmt(self, f)
102    }
103}