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
pub type Number = f64;

#[derive(Debug, PartialEq, Clone)]
pub struct FunCall {
    pub name: String,
    pub params: Vec<Operand>,
}

#[derive(Debug, PartialEq, Clone)]
pub enum Operand {
    Number(Number),
    Symbol(String),
    Term(Box<Term>),
    FunCall(FunCall),
}

impl Operand {
    pub fn is_symbol(&self, sym: &str) -> bool {
        matches!(self, Operand::Symbol(s) if s == sym)
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Operation {
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    Pow,
}

#[derive(Debug, PartialEq, Clone)]
pub struct Term {
    pub op: Operation,
    pub lhs: Operand,
    pub rhs: Operand,
}

#[derive(Debug, PartialEq, Clone)]
pub struct CustomFunction {
    pub args: Vec<String>,
    pub body: Operand,
}

#[derive(Clone)]
pub struct BuildInFunction {
    pub name: String,
    pub arg: String,
    pub body: &'static dyn Fn(Number) -> Number,
}

impl PartialEq for BuildInFunction {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.arg == other.arg
    }
}

impl std::fmt::Debug for BuildInFunction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuildInFunction")
            .field("name", &self.name)
            .field("arg", &self.arg)
            .finish()
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum Function {
    Custom(CustomFunction),
    BuildIn(BuildInFunction),
}

impl Default for Function {
    fn default() -> Self {
        Function::Custom(CustomFunction {
            args: Vec::new(),
            body: Operand::Number(1.0),
        })
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum Statement {
    Expression {
        op: Operand,
    },
    Assignment {
        sym: String,
        op: Operand,
    },
    SolveFor {
        lhs: Operand,
        rhs: Operand,
        sym: String,
    },
    Function {
        name: String,
        fun: Function,
    },
    Plot {
        name: String,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    fn create_term() -> Term {
        let lhs = Operand::Number(1.0);
        let rhs = Operand::Number(1.0);
        let op = Operation::Add;
        Term { op, lhs, rhs }
    }

    #[test]
    fn operand_is_symbol() {
        assert!(Operand::Symbol("x".to_string()).is_symbol("x"));
    }

    #[test]
    fn operand_is_not_symbol() {
        assert!(!Operand::Symbol("y".to_string()).is_symbol("x"));
        assert!(!Operand::Number(1.0).is_symbol("x"));
        assert!(!Operand::Term(Box::new(create_term())).is_symbol("x"));
    }
}