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    pub fn binary_op(lhs: impl Into<Self>, op: BinaryOp, rhs: impl Into<Self>) -> Self {
30        ExprBinaryOp {
31            op,
32            lhs: Box::new(lhs.into()),
33            rhs: Box::new(rhs.into()),
34        }
35        .into()
36    }
37
38    pub fn eq(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
39        Expr::binary_op(lhs, BinaryOp::Eq, rhs)
40    }
41
42    /// Returns true if the expression is a binary expression with the equality operator
43    pub fn is_eq(&self) -> bool {
44        matches!(
45            self,
46            Self::BinaryOp(ExprBinaryOp {
47                op: BinaryOp::Eq,
48                ..
49            })
50        )
51    }
52
53    pub fn ge(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
54        Expr::binary_op(lhs, BinaryOp::Ge, rhs)
55    }
56
57    pub fn gt(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
58        Expr::binary_op(lhs, BinaryOp::Gt, rhs)
59    }
60
61    pub fn le(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
62        Expr::binary_op(lhs, BinaryOp::Le, rhs)
63    }
64
65    pub fn lt(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
66        Expr::binary_op(lhs, BinaryOp::Lt, rhs)
67    }
68
69    pub fn ne(lhs: impl Into<Self>, rhs: impl Into<Self>) -> Self {
70        Expr::binary_op(lhs, BinaryOp::Ne, rhs)
71    }
72}
73
74impl From<ExprBinaryOp> for Expr {
75    fn from(value: ExprBinaryOp) -> Self {
76        Self::BinaryOp(value)
77    }
78}