1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use super::Expression;
use crate::{Error, Result};
use serde::Deserialize;
use std::fmt;
use std::str::FromStr;

/// Operations apply a particular operator to either one or two expression terms.
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum Operation {
    /// Represents an operation that applies an operator to a single expression.
    Unary(UnaryOp),
    /// Represents an operation that applies an operator to two expressions.
    Binary(BinaryOp),
}

impl From<UnaryOp> for Operation {
    fn from(op: UnaryOp) -> Self {
        Operation::Unary(op)
    }
}

impl From<BinaryOp> for Operation {
    fn from(op: BinaryOp) -> Self {
        Operation::Binary(op)
    }
}

/// An operation that applies an operator to one expression.
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct UnaryOp {
    /// The unary operator to use on the expression.
    pub operator: UnaryOperator,
    /// An expression that supports evaluation with the unary operator.
    pub expr: Expression,
}

impl UnaryOp {
    /// Creates a new `UnaryOp` from an operator and an expression.
    pub fn new<T>(operator: UnaryOperator, expr: T) -> UnaryOp
    where
        T: Into<Expression>,
    {
        UnaryOp {
            operator,
            expr: expr.into(),
        }
    }
}

/// An operator that can be applied to an expression.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum UnaryOperator {
    /// Negate operator (`-`).
    Neg,
    /// Not operator (`!`).
    Not,
}

impl UnaryOperator {
    /// Returns the `UnaryOperator` as a static `&str`.
    pub fn as_str(&self) -> &'static str {
        match self {
            UnaryOperator::Neg => "-",
            UnaryOperator::Not => "!",
        }
    }
}

impl fmt::Display for UnaryOperator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl FromStr for UnaryOperator {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "-" => Ok(UnaryOperator::Neg),
            "!" => Ok(UnaryOperator::Not),
            _ => Err(Error::new(format!("invalid unary operator: `{s}`"))),
        }
    }
}

/// An operation that applies an operator to two expressions.
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct BinaryOp {
    /// The expression on the left-hand-side of the operation.
    pub lhs_expr: Expression,
    /// The binary operator to use on the expressions.
    pub operator: BinaryOperator,
    /// The expression on the right-hand-side of the operation.
    pub rhs_expr: Expression,
}

impl BinaryOp {
    /// Creates a new `BinaryOp` from two expressions and an operator.
    pub fn new<L, R>(lhs_expr: L, operator: BinaryOperator, rhs_expr: R) -> BinaryOp
    where
        L: Into<Expression>,
        R: Into<Expression>,
    {
        BinaryOp {
            lhs_expr: lhs_expr.into(),
            operator,
            rhs_expr: rhs_expr.into(),
        }
    }

    // Normalize binary operation following operator precedence rules.
    //
    // The result can be evaluated from left to right without checking operator precendence.
    pub(crate) fn normalize(self) -> BinaryOp {
        use Operand::{BinOp, Expr};

        // We only care whether the operand is another binary operation or not. Any other
        // expression (including unary oparations) is treated the same way and does not require
        // special precedence rules.
        enum Operand {
            BinOp(BinaryOp),
            Expr(Expression),
        }

        impl From<Expression> for Operand {
            fn from(expr: Expression) -> Self {
                match expr {
                    Expression::Operation(operation) => match *operation {
                        Operation::Binary(binary) => Operand::BinOp(binary),
                        unary => Operand::Expr(Expression::from(unary)),
                    },
                    expr => Operand::Expr(expr),
                }
            }
        }

        let lhs = Operand::from(self.lhs_expr);
        let operator = self.operator;
        let rhs = Operand::from(self.rhs_expr);

        match (lhs, rhs) {
            (BinOp(lhs), BinOp(rhs)) => normalize_both(lhs.normalize(), operator, rhs.normalize()),
            (BinOp(lhs), Expr(rhs)) => normalize_lhs(lhs.normalize(), operator, rhs),
            (Expr(lhs), BinOp(rhs)) => normalize_rhs(lhs, operator, rhs.normalize()),
            (Expr(lhs), Expr(rhs)) => BinaryOp::new(lhs, operator, rhs),
        }
    }
}

fn normalize_both(lhs: BinaryOp, operator: BinaryOperator, rhs: BinaryOp) -> BinaryOp {
    if lhs.operator.precedence() < operator.precedence() {
        // BinaryOp(BinaryOp(lhs.lhs_expr + lhs.rhs_expr) * BinaryOp(rhs.lhs_expr - rhs.rhs_expr))
        //
        // => BinaryOp(lhs.lhs_expr + BinaryOp(BinaryOp(lhs.rhs_expr * rhs.lhs_expr) - rhs.rhs_expr))
        BinaryOp::new(
            lhs.lhs_expr,
            lhs.operator,
            Operation::Binary(normalize_rhs(lhs.rhs_expr, operator, rhs)),
        )
    } else if rhs.operator.precedence() < operator.precedence() {
        // BinaryOp(BinaryOp(lhs.lhs_expr / lhs.rhs_expr) * BinaryOp(rhs.lhs_expr - rhs.rhs_expr))
        //
        // => BinaryOp(BinaryOp(BinaryOp(lhs.lhs_expr / lhs.rhs_expr) * rhs.lhs_expr) - rhs.rhs_expr)
        BinaryOp::new(
            Operation::Binary(normalize_lhs(lhs, operator, rhs.lhs_expr)),
            rhs.operator,
            rhs.rhs_expr,
        )
    } else {
        // Nothing to normalize.
        BinaryOp::new(Operation::Binary(lhs), operator, Operation::Binary(rhs))
    }
}

fn normalize_lhs(lhs: BinaryOp, operator: BinaryOperator, rhs_expr: Expression) -> BinaryOp {
    if lhs.operator.precedence() < operator.precedence() {
        // BinaryOp(BinaryOp(lhs.lhs_expr + lhs.rhs_expr) / rhs_expr)
        //
        // => BinaryOp(lhs.lhs_expr + BinaryOp(lhs.rhs_expr / rhs_expr))
        BinaryOp::new(
            lhs.lhs_expr,
            lhs.operator,
            Operation::Binary(BinaryOp::new(lhs.rhs_expr, operator, rhs_expr)),
        )
    } else {
        // Nothing to normalize.
        BinaryOp::new(Operation::Binary(lhs), operator, rhs_expr)
    }
}

fn normalize_rhs(lhs_expr: Expression, operator: BinaryOperator, rhs: BinaryOp) -> BinaryOp {
    if rhs.operator.precedence() < operator.precedence() {
        // BinaryOp(lhs_expr / BinaryOp(rhs.lhs_expr + rhs.rhs_expr))
        //
        // => BinaryOp(BinaryOp(lhs_expr / rhs.lhs_expr) + rhs.rhs_expr)
        BinaryOp::new(
            Operation::Binary(BinaryOp::new(lhs_expr, operator, rhs.lhs_expr)),
            rhs.operator,
            rhs.rhs_expr,
        )
    } else {
        // Nothing to normalize.
        BinaryOp::new(lhs_expr, operator, Operation::Binary(rhs))
    }
}

/// An operator that can be applied to two expressions.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum BinaryOperator {
    /// Equal operator (`==`).
    Eq,
    /// Not-equal operator (`!=`).
    NotEq,
    /// Less-equal operator (`<=`).
    LessEq,
    /// Greater-equal operator (`>=`).
    GreaterEq,
    /// Less operator (`<`).
    Less,
    /// Greater operator (`>`).
    Greater,
    /// Plus operator (`+`).
    Plus,
    /// Minus operator (`-`).
    Minus,
    /// Multiply operator (`*`).
    Mul,
    /// Division operator (`/`).
    Div,
    /// Modulo operator (`%`).
    Mod,
    /// And operator (`&&`).
    And,
    /// Or operator (`||`).
    Or,
}

impl BinaryOperator {
    /// Returns the `BinaryOperator` as a static `&str`.
    pub fn as_str(&self) -> &'static str {
        match self {
            BinaryOperator::Eq => "==",
            BinaryOperator::NotEq => "!=",
            BinaryOperator::LessEq => "<=",
            BinaryOperator::GreaterEq => ">=",
            BinaryOperator::Less => "<",
            BinaryOperator::Greater => ">",
            BinaryOperator::Plus => "+",
            BinaryOperator::Minus => "-",
            BinaryOperator::Mul => "*",
            BinaryOperator::Div => "/",
            BinaryOperator::Mod => "%",
            BinaryOperator::And => "&&",
            BinaryOperator::Or => "||",
        }
    }

    // Returns the operator precedence level. Higher numbers mean higher precedence.
    pub(crate) fn precedence(self) -> u8 {
        match self {
            BinaryOperator::Mul | BinaryOperator::Div | BinaryOperator::Mod => 6,
            BinaryOperator::Plus | BinaryOperator::Minus => 5,
            BinaryOperator::LessEq
            | BinaryOperator::GreaterEq
            | BinaryOperator::Less
            | BinaryOperator::Greater => 4,
            BinaryOperator::Eq | BinaryOperator::NotEq => 3,
            BinaryOperator::And => 2,
            BinaryOperator::Or => 1,
        }
    }
}

impl fmt::Display for BinaryOperator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl FromStr for BinaryOperator {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "==" => Ok(BinaryOperator::Eq),
            "!=" => Ok(BinaryOperator::NotEq),
            "<=" => Ok(BinaryOperator::LessEq),
            ">=" => Ok(BinaryOperator::GreaterEq),
            "<" => Ok(BinaryOperator::Less),
            ">" => Ok(BinaryOperator::Greater),
            "+" => Ok(BinaryOperator::Plus),
            "-" => Ok(BinaryOperator::Minus),
            "*" => Ok(BinaryOperator::Mul),
            "/" => Ok(BinaryOperator::Div),
            "%" => Ok(BinaryOperator::Mod),
            "&&" => Ok(BinaryOperator::And),
            "||" => Ok(BinaryOperator::Or),
            _ => Err(Error::new(format!("invalid binary operator: `{s}`"))),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    macro_rules! binop {
        ($l:expr, $op:expr, $r:expr $(,)?) => {
            BinaryOp::new($l, $op, $r)
        };
    }

    macro_rules! assert_normalizes_to {
        ($op:expr, $expected:expr $(,)?) => {
            assert_eq!($op.normalize(), $expected);
        };
    }

    #[test]
    fn normalize_binary_op() {
        use BinaryOperator::{Div, Mod, Mul, Plus};

        assert_normalizes_to!(
            binop!(binop!(1, Plus, 2), Div, binop!(3, Mul, 4)),
            binop!(1, Plus, binop!(2, Div, binop!(3, Mul, 4))),
        );

        assert_normalizes_to!(
            binop!(binop!(1, Div, 2), Mul, binop!(3, Plus, binop!(4, Mod, 5))),
            binop!(binop!(binop!(1, Div, 2), Mul, 3), Plus, binop!(4, Mod, 5)),
        );

        assert_normalizes_to!(
            binop!(binop!(binop!(1, Plus, 2), Mul, 3), Div, 4),
            binop!(1, Plus, binop!(binop!(2, Mul, 3), Div, 4)),
        );

        assert_normalizes_to!(
            binop!(1, Div, binop!(binop!(2, Plus, 3), Mul, 4)),
            binop!(binop!(1, Div, 2), Plus, binop!(3, Mul, 4)),
        );
    }

    #[test]
    fn normalize_parenthesized() {
        use BinaryOperator::{Div, Mod, Mul, Plus};

        fn parens(op: BinaryOp) -> Expression {
            Expression::Parenthesis(Box::new(op.into()))
        }

        let op = binop!(
            parens(binop!(1, Div, 2)),
            Mul,
            parens(binop!(3, Mod, parens(binop!(4, Plus, 5)))),
        );

        assert_normalizes_to!(op.clone(), op);
    }

    #[test]
    fn already_normalized() {
        use BinaryOperator::Plus;

        let op = binop!(binop!(1, Plus, 2), Plus, binop!(3, Plus, 4));

        assert_normalizes_to!(op.clone(), op);
    }
}