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
use std::{collections::VecDeque, fmt};
use CalcType::{Add, Divide, Multiply, Power, Print, Subtract, Val};
#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
/// enum CalcType is a type containing operations used in the calculator.
pub enum CalcType {
    Add,
    Subtract,
    Multiply,
    Divide,
    Power,
    Print,
    Val(f64),
}
#[derive(Debug, Clone)]
pub struct EvaluationError {
    pub message: String,
}

impl fmt::Display for EvaluationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Failed evaluation with reason: {}", self.message)
    }
}

/// str_to_calc_type converts a string to an optional `CalcType`.
pub fn str_to_calc_type(string: &str) -> Option<CalcType> {
    let as_int = string.parse::<f64>();
    let result = match as_int {
        Ok(x) => Some(Val(x)),
        Err(_) => None,
    };

    if result.is_some() {
        return result;
    }

    match string {
        "+" => Some(Add),
        "-" => Some(Subtract),
        "*" => Some(Multiply),
        "/" => Some(Divide),
        "^" => Some(Power),
        "p" => Some(Print),

        _ => None,
    }
}

/// `eval` takes a `&str` and a `&mut VecDeque<f64>`, evaluates the expression,
/// and prints the result, pushing the results onto the stack of type
/// VecDeque<f64> provided as a parameter.
///
/// It does not return an error, but will instead silently fail if the expression is invalid.
/// Additionally, it mutates the stack parameter, rather than returning a new one.
/// Even if the stack is empty, it will still evaluate the expression.
/// For this reason, eval is unsafe, and safe_eval or safe_eval_with_stack should be used.
///
pub fn eval(input: &str, stack: &mut VecDeque<f64>) {
    //// Create a mutable copy of the inputted stack
    //// let mut stack = stack_in.clone();

    // Split the input into tokens.
    let toks = input.split(' ').collect::<Vec<&str>>();
    let mut ops: VecDeque<CalcType> = VecDeque::new();

    for tok in &toks {
        let x: CalcType = str_to_calc_type(tok).unwrap();

        match x {
            Add | Divide | Multiply | Power | Subtract | Print => ops.push_back(x),

            Val(x_) => stack.push_back(x_),
        }
    }

    for op in &ops {
        match op {
            Add => {
                let y = &stack.pop_back().unwrap_or(0.0);
                let x = &stack.pop_back().unwrap_or(0.0);
                &stack.push_back(x + y)
            }
            Subtract => {
                let y = &stack.pop_back().unwrap_or(0.0);
                let x = &stack.pop_back().unwrap_or(0.0);
                &stack.push_back(x - y)
            }
            Multiply => {
                let y = &stack.pop_back().unwrap_or(0.0);
                let x = &stack.pop_back().unwrap_or(0.0);
                &stack.push_back(x * y)
            }
            Divide => {
                let y = &stack.pop_back().unwrap_or(0.0);
                let x = &stack.pop_back().unwrap_or(0.0);
                &stack.push_back(x / y)
            }
            Power => {
                let y = &stack.pop_back().unwrap_or(0.0);
                let x = &stack.pop_back().unwrap_or(0.0);

                let result = x.powf(*y);
                &stack.push_back(result)
            }
            Print => &{ println!("{:#?}", stack.iter().last()) },
            Val(_) => panic!("Unexpected value in the operator stack!"),
        };
    }

    println!("{}", stack.iter().last().unwrap_or(&0.0));
}

/// `safe_eval` takes a `&str` evaluates the expression, returning the
/// resulting stack as a Result if the expression is valid, or an Err if the
/// expression is invalid or otherwise cannot be evaluated.
///
/// safe_eval is useful for testing the validity of an expression, and is safer
/// than eval, as it does not mutate any inputted values.
///
/// # Examples  
///
/// ```
/// use dc-ock::safe_eval;
///
/// fn main() {
///     let expr = "1 2 +";
///     match safe_eval(expr) {
///         Ok(x) => println!("{:?}", x), // prints [3.0]
///         Err(e) => println!("{}", e),  // prints an error message
///     }
/// }  
/// ```
pub fn safe_eval(input: &str) -> Result<VecDeque<f64>, EvaluationError> {
    // Initialise the stack
    let mut stack: VecDeque<f64> = VecDeque::new();

    // Split the input into tokens.
    let toks = input.split(' ').collect::<Vec<&str>>();
    let mut ops: VecDeque<CalcType> = VecDeque::new();

    for tok in &toks {
        let x: CalcType = match str_to_calc_type(tok) {
            Some(x) => x,
            None => {
                return Err(EvaluationError {
                    message: format!("Invalid token: {}", tok),
                })
            }
        };

        match x {
            Add | Divide | Multiply | Power | Subtract | Print => ops.push_back(x),

            Val(x_) => stack.push_back(x_),
        }
    }

    for op in &ops {
        match op {
            Add => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x + y)
            }
            Subtract => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x - y)
            }
            Multiply => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x * y)
            }
            Divide => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x / y)
            }
            Power => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;

                let result = x.powf(*y);
                &stack.push_back(result)
            }
            Print => &{ println!("{:#?}", stack.iter().last()) },
            Val(_) => panic!("Unexpected value in the operator stack!"),
        };
    }

    Ok(stack)
}

/// `safe_eval_with_stack` takes an `&str` expression, and a stack `VecDeque<f64>`,
/// and evaluates the expression, returning the resulting stack as a Result if the
/// if the expression is valid, or an Err if the expression is invalid or
/// otherwise cannot be evaluated.
///
/// safe_eval_with_stack is useful for testing the validity of an expression,
/// and is safer than eval, as it does not mutate any inputted values.
///
/// It also allows you to specify a stack to use for the expression, rather than
/// automatically creating a new stack internally. This is useful for persisting
/// a stack between calls to safe_eval_with_stack.
/// # Examples  
///
/// ```
/// use dc-ock::safe_eval_with_stack;
///
/// fn main() {
///     let mut stack: VecDeque<f64> = VecDeque::new();
///     stack.push_back(2.);
///     stack.push_back(7.5);
///     stack.push_back(3.5);
///
///     stack = safe_eval_with_stack("+ +", stack).unwrap();
///     println!("{:?}", stack); // prints [13.0]
/// }
/// ```
pub fn safe_eval_with_stack(
    input: &str,
    initial_stack: VecDeque<f64>,
) -> Result<VecDeque<f64>, EvaluationError> {
    let mut stack = initial_stack;
    // Split the input into tokens.
    let toks = input.split(' ').collect::<Vec<&str>>();
    let mut ops: VecDeque<CalcType> = VecDeque::new();

    for tok in &toks {
        let x: CalcType = match str_to_calc_type(tok) {
            Some(x) => x,
            None => {
                return Err(EvaluationError {
                    message: format!("Invalid token: {}", tok),
                })
            }
        };

        match x {
            Add | Divide | Multiply | Power | Subtract | Print => ops.push_back(x),

            Val(x_) => stack.push_back(x_),
        }
    }

    for op in &ops {
        match op {
            Add => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x + y)
            }
            Subtract => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x - y)
            }
            Multiply => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x * y)
            }
            Divide => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                &stack.push_back(x / y)
            }
            Power => {
                let y = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;
                let x = &stack.pop_back().ok_or(EvaluationError {
                    message: "Stack is empty!".to_string(),
                })?;

                let result = x.powf(*y);
                &stack.push_back(result)
            }
            Print => &{ println!("{:#?}", stack.iter().last()) },
            Val(_) => panic!("Unexpected value in the operator stack!"),
        };
    }

    Ok(stack)
}