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
use crate::BinaryOp;
use crate::Function;

use serde::Serialize;
use tusk_lexer::TokenType;

#[derive(Serialize, Debug, Clone, PartialEq)]
pub enum Expression {
    True,
    False,
    Null,
    String(String),
    Integer(i64),
    Float(f64),
    Variable(String),
    TypedVariable(String, String),
    Identifier(String),
    Binary(Box<Expression>, BinaryOp, Box<Expression>),
    Assign(Box<Expression>, Box<Expression>),
    Concat(Box<Expression>, Box<Expression>),
    Array(Vec<Expression>),
    ArrayAccess(Box<Expression>, Option<Box<Expression>>),
    ArrayItem { key: Box<Expression>, value: Box<Expression> },
    PropertyAccess(Box<Expression>, Box<Expression>),
    New {
        class: Box<Expression>,
        args: Vec<Expression>,
    },
    Call {
        target: Box<Expression>,
        args: Vec<Expression>,
    },
    MethodCall {
        target: Box<Expression>,
        method: Box<Expression>,
        args: Vec<Expression>
    },
    Closure(Function),
    Unary(Box<Expression>),
    Negate(Box<Expression>),
    BitwiseNot(Box<Expression>),
}

impl Expression {
    pub fn make_infix(lhs: Expression, operator: &TokenType, rhs: Expression) -> Self {
        use TokenType::*;

        let lhs = Box::new(lhs);
        let rhs = Box::new(rhs);

        match *operator {
            Plus | Minus | Asterisk | Slash | Percent |
            GreaterThan | GreaterThanEquals | LessThan | LessThanEquals |
            BitwiseAnd | BitwiseOr | BitwiseLeftShift | BitwiseRightShift | BitwiseXor |
            And | Or => Self::Binary(lhs, BinaryOp::from(*operator), rhs),
            Period => Self::Concat(lhs, rhs),
            DoubleArrow => Self::ArrayItem { key: lhs, value: rhs },
            Equals => Self::Assign(lhs, rhs),
            _ => unimplemented!(),
        }
    }
}

impl From<bool> for Expression {
    fn from(value: bool) -> Self {
        match value {
            true => Self::True,
            false => Self::False,
        }
    }
}