tazor 1.0.2

Tazor is Rust library implementing a calculator based on mathematical expression
Documentation
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use std::collections::HashMap;

/// Kind of expression that we can parse
///
/// Raw expression is an expression that we want directly evaluate as `1 + 1`
///
/// Variable is an expression defining a variable that we want store.
/// It follows the template `variable_name = variable_definition`
///
/// ex: `x = 1 + 1`
///
/// Function is an expression defining a fucntion that we want store.
/// It follows the template `function_name: function_variable_1, function_variable_2, ... = function definition`
///
/// ex: `f: x, y = x * x + y * y`
///
pub enum Expression {
    Raw(String),
    Variable(String, String),
    Function(String, Vec<String>, String),
}

impl Expression {
    /// Construct an Expression from string
    pub fn new(expression: &str) -> Self {
        return match expression.split_once('=') {
            // Here the expression define a variable or function
            Some((name, definition)) => match name.split_once(':') {
                // Here we have a function
                Some((fun_name, fun_variables_compact)) => {
                    let fun_variables: Vec<String> = fun_variables_compact
                        .split(',')
                        .map(|fun_variable_name: &str| {
                            String::from(fun_variable_name.trim_start().trim_end())
                        })
                        .collect();

                    return Self::Function(
                        String::from(fun_name.trim_start().trim_end()),
                        fun_variables,
                        String::from(definition.trim_start().trim_end()),
                    );
                }
                // Here we have a variable
                None => Self::Variable(
                    String::from(name.trim_start().trim_end()),
                    String::from(definition.trim_start().trim_end()),
                ),
            },
            // Here we have a raw expression
            None => Self::Raw(String::from(expression)),
        };
    }

    /// Replace all variable contained in expression by their value
    ///
    /// The variables are given in argument through HashMap where
    /// pair (key, value) correspond respectively to name and value of variable
    pub fn replace_variables(&mut self, variables: &HashMap<String, f64>) {
        match self {
            Self::Raw(definition) | Self::Variable(_, definition) => {
                variables
                    .iter()
                    .for_each(|(variable_name, variable_value)| {
                        let mut replaced_definition: String = definition
                            .replace(variable_name, format!("{}", variable_value).as_str());

                        core::mem::swap(definition, &mut replaced_definition);
                    });
            }
            Self::Function(_, function_variables, definition) => {
                variables
                    .iter()
                    .filter(|(variable_name, _)| {
                        return !function_variables.contains(variable_name);
                    })
                    .for_each(|(variable_name, variable_value)| {
                        let mut replaced_definition: String = definition
                            .replace(variable_name, format!("{}", variable_value).as_str());

                        core::mem::swap(definition, &mut replaced_definition);
                    });
            }
        };
    }

    /// Recovery positions of function and its parenthesis in expression definition
    /// Expression definition and function name are given in argument
    fn get_function_positions(
        expression_definition: &String,
        fun_name: &String,
    ) -> Result<Option<(usize, usize, usize)>, String> {
        // Get position of function
        let potential_start_position: Option<usize> = expression_definition.find(fun_name.as_str());

        if potential_start_position.is_none() {
            return Ok(None);
        }

        let start_position: usize = potential_start_position.unwrap();

        // Get position of opening parenthesis
        let start_search_parenthesis_position: usize = start_position + fun_name.len();

        let potential_opening_parenthesis_position: Option<usize> = expression_definition
            .chars()
            .skip(start_search_parenthesis_position)
            .position(|c| c == '(');

        if potential_opening_parenthesis_position.is_none() {
            return Ok(None);
        }

        let opening_parenthesis_position: usize =
            start_search_parenthesis_position + potential_opening_parenthesis_position.unwrap();

        // To get closing parenthesis, we initialize a counter to 1, then we increment it when we encounter
        // an opening parenthesis or we decrement it when we encounter a closing parenthesis.
        // When the counter reach 0, we have on closing parenthesis corresponding to function.
        let mut parenthesis_counter: u8 = 1;

        let closing_parenthesis_position: usize = opening_parenthesis_position
            + 1
            + expression_definition
                .chars()
                .skip(opening_parenthesis_position + 1)
                .take_while(|c| -> bool {
                    match c {
                        '(' => parenthesis_counter += 1,
                        ')' => parenthesis_counter -= 1,
                        _ => {}
                    }

                    return parenthesis_counter > 0;
                })
                .count();

        // Check if we handle a function, else we go to next function name
        let has_char_between_fun_name_and_first_parenthesis: bool = expression_definition
            [start_search_parenthesis_position..opening_parenthesis_position]
            .chars()
            .any(|c| !c.is_whitespace());

        if has_char_between_fun_name_and_first_parenthesis {
            return Ok(None);
        }

        return Ok(Some((
            start_position,
            opening_parenthesis_position,
            closing_parenthesis_position,
        )));
    }

    /// Replace all function contained in expression by their definition
    ///
    /// The function are given in argument through HashMap where
    /// key correspond to name of function and value is a pair containing
    /// name of variables and definition of function
    pub fn replace_functions(
        &mut self,
        functions: &HashMap<String, (Vec<String>, String)>,
    ) -> Result<(), String> {
        let definition: &mut String = match self {
            Self::Raw(raw_expression) => raw_expression,
            Self::Variable(_, definition) => definition,
            Self::Function(_, _, definition) => definition,
        };

        for fun_name in functions.keys() {
            // Get positions of function name and its parenthesis
            let potential_positions: Option<(usize, usize, usize)> =
                Expression::get_function_positions(&definition, fun_name)?;

            if potential_positions.is_none() {
                // here the functions is not in expression definition
                continue;
            }

            let (start_position, opening_parenthesis_position, closing_parenthesis_position) =
                potential_positions.unwrap();

            // Get value of function variables
            let variable_values: Vec<&str> = definition
                [(opening_parenthesis_position + 1)..closing_parenthesis_position]
                .split(", ")
                .collect();

            // Create string to replace function call by function body
            let variables: &Vec<String> = functions[fun_name].0.as_ref();
            let mut replaced_fun_definition: String = functions[fun_name].1.clone();

            if variables.len() != variable_values.len() {
                return Err(format!("The number of variables is not consistent"));
            }

            let mut id: usize = 0;

            for variable in variables {
                if variable_values[id]
                    .chars()
                    .any(|c| c == '+' || c == '*' || c == '-' || c == '/')
                {
                    replaced_fun_definition = replaced_fun_definition
                        .replace(variable, format!("({})", variable_values[id]).as_str());
                } else {
                    replaced_fun_definition =
                        replaced_fun_definition.replace(variable, variable_values[id]);
                }

                id += 1;
            }

            definition.replace_range(
                start_position..=closing_parenthesis_position,
                format!("({})", replaced_fun_definition).as_str(),
            );
        }

        return Ok(());
    }
}

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

    #[test]
    fn test_expression_new_with_raw_expression() {
        let expression: String = String::from("1 + 1");

        match Expression::new(expression.as_str()) {
            Expression::Raw(raw_expression) => assert_eq!(raw_expression, expression),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_expression_new_with_variable_definition() {
        let variable_name: String = String::from("x");
        let variable_definition: String = String::from("1 + 1");

        let expression: String = format!("{} = {}", variable_name, variable_definition);

        match Expression::new(expression.as_str()) {
            Expression::Variable(name, definition) => {
                assert_eq!(name, variable_name);
                assert_eq!(definition, variable_definition);
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_expression_new_with_function_definition() {
        let function_name: String = String::from("distance");
        let function_variables: Vec<String> =
            vec![String::from("x"), String::from("y"), String::from("z)")];
        let function_definition: String = String::from("x * x + y * y + z * z");

        let expression: String = format!(
            "{}: {}, {}, {} = {}",
            function_name,
            function_variables[0],
            function_variables[1],
            function_variables[2],
            function_definition
        );

        match Expression::new(&expression.as_str()) {
            Expression::Function(name, variables, definition) => {
                assert_eq!(name, function_name);
                assert_eq!(variables, function_variables);
                assert_eq!(definition, function_definition);
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_expression_replace_variables_in_raw_expression() {
        let mut variables: HashMap<String, f64> = HashMap::new();

        variables.insert(String::from("x"), 1.0);
        variables.insert(String::from("velocity"), 3.43);
        variables.insert(String::from("time"), 5.9954);

        let raw_expression: String = String::from("(x - 2.75) + velocity * time");

        let replaced_raw_expression: String = format!(
            "({} - 2.75) + {} * {}",
            variables["x"], variables["velocity"], variables["time"]
        );

        let mut expression: Expression = Expression::new(raw_expression.as_str());
        expression.replace_variables(&variables);

        match expression {
            Expression::Raw(replaced_expression) => {
                assert_eq!(replaced_raw_expression, replaced_expression)
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_expression_replace_variables_in_variable_expression() {
        let mut variables: HashMap<String, f64> = HashMap::new();

        variables.insert(String::from("x"), 1.0);
        variables.insert(String::from("velocity"), 3.43);
        variables.insert(String::from("time"), 5.9954);

        let var_expression: String = String::from("y = (x - 2.75) + velocity * time");

        let replaced_var_expression: String = format!(
            "({} - 2.75) + {} * {}",
            variables["x"], variables["velocity"], variables["time"]
        );

        let mut expression: Expression = Expression::new(var_expression.as_str());
        expression.replace_variables(&variables);

        match expression {
            Expression::Variable(_, replaced_expression) => {
                assert_eq!(replaced_var_expression, replaced_expression)
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_expression_replace_functions_in_raw_expression() {
        let mut functions: HashMap<String, (Vec<String>, String)> = HashMap::new();

        functions.insert(
            String::from("distance"),
            (
                vec![String::from("x"), String::from("y")],
                String::from("x * x + y * y"),
            ),
        );

        functions.insert(
            String::from("f"),
            (vec![String::from("a")], String::from("a + 1")),
        );

        let raw_expression: String = String::from("distance(2.0, 3.3) + f(5.2) * 3");
        let replaced_raw_expression: String =
            String::from("(2.0 * 2.0 + 3.3 * 3.3) + (5.2 + 1) * 3");

        let mut expression: Expression = Expression::new(raw_expression.as_str());
        expression.replace_functions(&functions).unwrap();

        match expression {
            Expression::Raw(replaced_expression) => {
                assert_eq!(replaced_raw_expression, replaced_expression)
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_expression_replace_functions_in_variable_expression() {
        let mut functions: HashMap<String, (Vec<String>, String)> = HashMap::new();

        functions.insert(
            String::from("distance"),
            (
                vec![String::from("x"), String::from("y")],
                String::from("x * x + y * y"),
            ),
        );

        functions.insert(
            String::from("f"),
            (vec![String::from("a")], String::from("a + 1")),
        );

        let var_expression: String = String::from("d = distance(2.0, 3.3) + f(5.2) * 3");
        let replaced_var_expression: String =
            String::from("(2.0 * 2.0 + 3.3 * 3.3) + (5.2 + 1) * 3");

        let mut expression: Expression = Expression::new(var_expression.as_str());
        expression.replace_functions(&functions).unwrap();

        match expression {
            Expression::Variable(_, replaced_expression) => {
                assert_eq!(replaced_var_expression, replaced_expression)
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_expression_replace_functions_in_expression_using_expression_with_parenthesis_as_argument(
    ) {
        let mut functions: HashMap<String, (Vec<String>, String)> = HashMap::new();

        functions.insert(
            String::from("f"),
            (
                vec![String::from("x"), String::from("y")],
                String::from("x + y"),
            ),
        );

        functions.insert(
            String::from("g"),
            (vec![String::from("x")], String::from("x + 1")),
        );

        let raw_expression: String = String::from("f(2 * (4 - 2) + 1, 3) + g(3 * (7 - 4))");
        let replaced_raw_expression: String =
            String::from("((2 * (4 - 2) + 1) + 3) + ((3 * (7 - 4)) + 1)");

        let mut expression: Expression = Expression::new(raw_expression.as_str());
        expression.replace_functions(&functions).unwrap();

        match expression {
            Expression::Raw(replaced_expression) => {
                assert_eq!(replaced_raw_expression, replaced_expression)
            }
            _ => assert!(false),
        }
    }
}