hcl/expr/
operation.rs

1use super::Expression;
2use serde::Deserialize;
3
4// Re-exported for convenience.
5#[doc(inline)]
6pub use hcl_primitives::expr::{BinaryOperator, UnaryOperator};
7
8/// Operations apply a particular operator to either one or two expression terms.
9#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
10pub enum Operation {
11    /// Represents an operation that applies an operator to a single expression.
12    Unary(UnaryOp),
13    /// Represents an operation that applies an operator to two expressions.
14    Binary(BinaryOp),
15}
16
17impl From<UnaryOp> for Operation {
18    fn from(op: UnaryOp) -> Self {
19        Operation::Unary(op)
20    }
21}
22
23impl From<BinaryOp> for Operation {
24    fn from(op: BinaryOp) -> Self {
25        Operation::Binary(op)
26    }
27}
28
29/// An operation that applies an operator to one expression.
30#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
31pub struct UnaryOp {
32    /// The unary operator to use on the expression.
33    pub operator: UnaryOperator,
34    /// An expression that supports evaluation with the unary operator.
35    pub expr: Expression,
36}
37
38impl UnaryOp {
39    /// Creates a new `UnaryOp` from an operator and an expression.
40    pub fn new<T>(operator: UnaryOperator, expr: T) -> UnaryOp
41    where
42        T: Into<Expression>,
43    {
44        UnaryOp {
45            operator,
46            expr: expr.into(),
47        }
48    }
49}
50
51/// An operation that applies an operator to two expressions.
52#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
53pub struct BinaryOp {
54    /// The expression on the left-hand-side of the operation.
55    pub lhs_expr: Expression,
56    /// The binary operator to use on the expressions.
57    pub operator: BinaryOperator,
58    /// The expression on the right-hand-side of the operation.
59    pub rhs_expr: Expression,
60}
61
62impl BinaryOp {
63    /// Creates a new `BinaryOp` from two expressions and an operator.
64    pub fn new<L, R>(lhs_expr: L, operator: BinaryOperator, rhs_expr: R) -> BinaryOp
65    where
66        L: Into<Expression>,
67        R: Into<Expression>,
68    {
69        BinaryOp {
70            lhs_expr: lhs_expr.into(),
71            operator,
72            rhs_expr: rhs_expr.into(),
73        }
74    }
75}