hcl_edit/expr/
operation.rs

1use crate::expr::Expression;
2use crate::{Decor, Spanned};
3use std::ops::Range;
4
5// Re-exported for convenience.
6#[doc(inline)]
7pub use hcl_primitives::expr::{BinaryOperator, UnaryOperator};
8
9/// An operation that applies an operator to one expression.
10#[derive(Debug, Clone, Eq)]
11pub struct UnaryOp {
12    /// The unary operator to use on the expression.
13    pub operator: Spanned<UnaryOperator>,
14    /// An expression that supports evaluation with the unary operator.
15    pub expr: Expression,
16
17    decor: Decor,
18    span: Option<Range<usize>>,
19}
20
21impl UnaryOp {
22    /// Creates a new `UnaryOp` from an operator and an expression.
23    pub fn new(
24        operator: impl Into<Spanned<UnaryOperator>>,
25        expr: impl Into<Expression>,
26    ) -> UnaryOp {
27        UnaryOp {
28            operator: operator.into(),
29            expr: expr.into(),
30            decor: Decor::default(),
31            span: None,
32        }
33    }
34
35    pub(crate) fn despan(&mut self, input: &str) {
36        self.decor.despan(input);
37        self.expr.despan(input);
38    }
39}
40
41impl PartialEq for UnaryOp {
42    fn eq(&self, other: &Self) -> bool {
43        self.operator == other.operator && self.expr == other.expr
44    }
45}
46
47/// An operation that applies an operator to two expressions.
48#[derive(Debug, Clone, Eq)]
49pub struct BinaryOp {
50    /// The expression on the left-hand-side of the operation.
51    pub lhs_expr: Expression,
52    /// The binary operator to use on the expressions.
53    pub operator: Spanned<BinaryOperator>,
54    /// The expression on the right-hand-side of the operation.
55    pub rhs_expr: Expression,
56
57    decor: Decor,
58    span: Option<Range<usize>>,
59}
60
61impl BinaryOp {
62    /// Creates a new `BinaryOp` from two expressions and an operator.
63    pub fn new(
64        lhs_expr: impl Into<Expression>,
65        operator: impl Into<Spanned<BinaryOperator>>,
66        rhs_expr: impl Into<Expression>,
67    ) -> BinaryOp {
68        BinaryOp {
69            lhs_expr: lhs_expr.into(),
70            operator: operator.into(),
71            rhs_expr: rhs_expr.into(),
72            decor: Decor::default(),
73            span: None,
74        }
75    }
76
77    pub(crate) fn despan(&mut self, input: &str) {
78        self.decor.despan(input);
79        self.lhs_expr.despan(input);
80        self.rhs_expr.despan(input);
81    }
82}
83
84impl PartialEq for BinaryOp {
85    fn eq(&self, other: &Self) -> bool {
86        self.lhs_expr == other.lhs_expr
87            && self.operator == other.operator
88            && self.rhs_expr == other.rhs_expr
89    }
90}
91
92decorate_impl!(UnaryOp, BinaryOp);
93span_impl!(UnaryOp, BinaryOp);