toasty_core/stmt/
expr_binary_op.rs

1use super::{BinaryOp, Expr};
2
3/// A binary operation between two expressions.
4///
5/// Applies an operator to a left-hand side and right-hand side expression.
6/// Supported operators include equality, comparison, and type checking.
7///
8/// # Examples
9///
10/// ```text
11/// eq(a, b)   // a == b
12/// ne(a, b)   // a != b
13/// lt(a, b)   // a < b
14/// gt(a, b)   // a > b
15/// ```
16#[derive(Debug, Clone, PartialEq)]
17pub struct ExprBinaryOp {
18    /// The left-hand side expression.
19    pub lhs: Box<Expr>,
20
21    /// The operator to apply.
22    pub op: BinaryOp,
23
24    /// The right-hand side expression.
25    pub rhs: Box<Expr>,
26}
27
28impl Expr {
29    /// Creates a binary operation expression with the given operator.
30    pub fn binary_op(lhs: impl Into<Self>, op: BinaryOp, rhs: impl Into<Self>) -> Self {
31        ExprBinaryOp {
32            op,
33            lhs: Box::new(lhs.into()),
34            rhs: Box::new(rhs.into()),
35        }
36        .into()
37    }
38
39    /// Creates an equality (`==`) expression.
40    pub fn eq(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
41        Expr::binary_op(lhs, BinaryOp::Eq, rhs)
42    }
43
44    /// Returns true if the expression is a binary expression with the equality operator
45    pub fn is_eq(&self) -> bool {
46        matches!(
47            self,
48            Self::BinaryOp(ExprBinaryOp {
49                op: BinaryOp::Eq,
50                ..
51            })
52        )
53    }
54
55    /// Creates a greater-than-or-equal (`>=`) expression.
56    pub fn ge(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
57        Expr::binary_op(lhs, BinaryOp::Ge, rhs)
58    }
59
60    /// Creates a greater-than (`>`) expression.
61    pub fn gt(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
62        Expr::binary_op(lhs, BinaryOp::Gt, rhs)
63    }
64
65    /// Creates a less-than-or-equal (`<=`) expression.
66    pub fn le(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
67        Expr::binary_op(lhs, BinaryOp::Le, rhs)
68    }
69
70    /// Creates a less-than (`<`) expression.
71    pub fn lt(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
72        Expr::binary_op(lhs, BinaryOp::Lt, rhs)
73    }
74
75    /// Creates a not-equal (`!=`) expression.
76    pub fn ne(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
77        Expr::binary_op(lhs, BinaryOp::Ne, rhs)
78    }
79}
80
81impl From<ExprBinaryOp> for Expr {
82    fn from(value: ExprBinaryOp) -> Self {
83        Self::BinaryOp(value)
84    }
85}