dd_statechart 0.7.0

A Data-Driven implementation of Harel Statecharts designed for high-reliability systems.
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
429
430
431
432
433
434
435
436
437
438
439
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
Filename : interpreter/evaluator.rs

Copyright (C) 2021 CJ McAllister
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

Purpose:
    This module defines the rules behind evaluating ECMAScript expressions.

    It leverages Rust's robust enums and trait system to represent ECMAScript
    values as Intermediate values, and the trait system allows for easy use
    of the values in the evaluation functions.

\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

use std::{error::Error, fmt};

use crate::{
    datamodel::SystemVariables,
    interpreter::{
        ArithmeticOperator, EcmaScriptEvalError, EcmaScriptValue, Expression, Literal,
        LogicalOperator, Operator, Unary,
    },
};


///////////////////////////////////////////////////////////////////////////////
//  Data Structures
///////////////////////////////////////////////////////////////////////////////

pub struct Evaluator<'e, 'sv> {
    expr: &'e Expression,
    sys_vars: &'sv SystemVariables,
}

#[derive(Debug, PartialEq)]
pub enum EvaluatorError {
    IdentifierNotFound(String /* Identifier name */),
    StringNegation(String /* String on which negation was attempted */),

    // Wrappers
    EcmaScriptEvalError(
        EcmaScriptEvalError, /* Wrapped error */
        Expression,          /* Subexpression containing the error */
    ),
}


///////////////////////////////////////////////////////////////////////////////
//  Object Implementations
///////////////////////////////////////////////////////////////////////////////

impl<'e, 'sv> Evaluator<'e, 'sv> {
    pub fn new(expr: &'e Expression, sys_vars: &'sv SystemVariables) -> Self {
        Self { expr, sys_vars }
    }


    /*  *  *  *  *  *  *  *\
     *  Utility Methods   *
    \*  *  *  *  *  *  *  */

    pub fn evaluate(&self) -> Result<EcmaScriptValue, EvaluatorError> {
        self.eval_subexpr(self.expr)
    }


    /*  *  *  *  *  *  *  *\
     *  Helper Functions  *
    \*  *  *  *  *  *  *  */

    fn eval_subexpr(&self, expr: &Expression) -> Result<EcmaScriptValue, EvaluatorError> {
        match expr {
            Expression::Literal(literal) => Ok(Self::eval_literal(literal)),
            Expression::Identifier(name) => self.eval_identifier(name),
            Expression::Unary(unary) => self.eval_unary(unary),
            Expression::Binary(left, op, right) => self.eval_binary(op, left, right),
            Expression::Grouping(inner_expr) => self.eval_subexpr(inner_expr),
        }
    }

    fn eval_identifier(&self, name: &str) -> Result<EcmaScriptValue, EvaluatorError> {
        // Look up the identifier in the data map
        if let Some(value) = self.sys_vars.get_data_member(name) {
            Ok(value.clone())
        } else {
            // Identifier was not found in the data map, return error
            Err(EvaluatorError::IdentifierNotFound(name.to_string()))
        }
    }

    fn eval_unary(&self, unary: &Unary) -> Result<EcmaScriptValue, EvaluatorError> {
        match unary {
            Unary::Negation(expr) => {
                match self.eval_subexpr(expr)? {
                    EcmaScriptValue::String(value) => {
                        // String negation is an error
                        Err(EvaluatorError::StringNegation(value))
                    }
                    EcmaScriptValue::Number(value) => {
                        // Negate value and return
                        Ok(EcmaScriptValue::Number(-value))
                    }
                    EcmaScriptValue::Boolean(value_is_true) => {
                        if value_is_true {
                            // Negation of 'true' evaluates to '-1.0'
                            Ok(EcmaScriptValue::Number(-1.0))
                        } else {
                            // Negation of 'false' evaluates to '-0.0'
                            Ok(EcmaScriptValue::Number(-0.0))
                        }
                    }
                    EcmaScriptValue::Null => {
                        // Negation of 'null' evaluates to '-0.0'
                        Ok(EcmaScriptValue::Number(-0.0))
                    }
                }
            }
            Unary::Not(expr) => {
                match self.eval_subexpr(expr)? {
                    EcmaScriptValue::String(_value) => {
                        // !String evaluates to 'false', because reasons
                        Ok(EcmaScriptValue::Boolean(false))
                    }
                    EcmaScriptValue::Number(value) => {
                        // !Number evaluates to 'true' for 0, 'false' for all other values
                        if (value - 0.0).abs() < f64::EPSILON {
                            Ok(EcmaScriptValue::Boolean(true))
                        } else {
                            Ok(EcmaScriptValue::Boolean(false))
                        }
                    }
                    EcmaScriptValue::Boolean(value_is_true) => {
                        // Invert value and return
                        Ok(EcmaScriptValue::Boolean(!value_is_true))
                    }
                    EcmaScriptValue::Null => {
                        // !'null' evaluates to 'true'
                        Ok(EcmaScriptValue::Boolean(true))
                    }
                }
            }
        }
    }

    fn eval_binary(
        &self,
        op: &Operator,
        left: &Expression,
        right: &Expression,
    ) -> Result<EcmaScriptValue, EvaluatorError> {
        let left_value = self.eval_subexpr(left)?;
        let right_value = self.eval_subexpr(right)?;

        match op {
            Operator::Arithmetic(math_op) => Self::eval_math_op(math_op, left_value, right_value)
                .map_err(|e| {
                    EvaluatorError::EcmaScriptEvalError(
                        e,
                        Expression::Binary(
                            Box::new(left.clone()),
                            Operator::Arithmetic(math_op.clone()),
                            Box::new(right.clone()),
                        ),
                    )
                }),
            Operator::Logical(logic_op) => Ok(EcmaScriptValue::Boolean(Self::eval_logic_op(
                logic_op,
                left_value,
                right_value,
            ))),
        }
    }


    /*  *  *  *  *  *  *  *\
     *   Helper Methods   *
    \*  *  *  *  *  *  *  */

    fn eval_literal(literal: &Literal) -> EcmaScriptValue {
        match literal {
            Literal::String(value) => EcmaScriptValue::String(value.clone()),
            Literal::Number(value) => EcmaScriptValue::Number(*value),
            Literal::True => EcmaScriptValue::Boolean(true),
            Literal::False => EcmaScriptValue::Boolean(false),
            Literal::Null => EcmaScriptValue::Null,
        }
    }

    // Perform arithmetic operation per the 'op' parameter, and return the result or error
    fn eval_math_op(
        op: &ArithmeticOperator,
        left: EcmaScriptValue,
        right: EcmaScriptValue,
    ) -> Result<EcmaScriptValue, EcmaScriptEvalError> {
        match op {
            ArithmeticOperator::Plus => Ok(left + right),
            ArithmeticOperator::Minus => left - right,
            ArithmeticOperator::Star => left * right,
            ArithmeticOperator::Slash => left / right,
        }
    }

    // Perform logical operation per the 'op' parameter, and return the result
    fn eval_logic_op(op: &LogicalOperator, left: EcmaScriptValue, right: EcmaScriptValue) -> bool {
        match op {
            LogicalOperator::EqualTo => left == right,
            LogicalOperator::NotEqualTo => left != right,
            LogicalOperator::GreaterThan => left > right,
            LogicalOperator::GreaterThanOrEqualTo => left >= right,
            LogicalOperator::LessThan => left < right,
            LogicalOperator::LessThanOrEqualTo => left <= right,
        }
    }
}


///////////////////////////////////////////////////////////////////////////////
//  Trait Implementations
///////////////////////////////////////////////////////////////////////////////


/*  *  *  *  *  *  *  *\
 *   EvaluatorError   *
\*  *  *  *  *  *  *  */

impl Error for EvaluatorError {}

impl fmt::Display for EvaluatorError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::IdentifierNotFound(name) => {
                write!(f, "Identifier '{}' not found in Data Model'", name)
            }
            Self::StringNegation(string) => {
                write!(
                    f,
                    "Attempted to negate String '{}', which is invalid",
                    string
                )
            }

            // Wrappers
            Self::EcmaScriptEvalError(ese_err, subexpr) => {
                write!(
                    f,
                    "EcmaScriptEvalError '{:?}' encountered while evaluating sub-expression '{}'",
                    ese_err, subexpr
                )
            }
        }
    }
}


///////////////////////////////////////////////////////////////////////////////
//  Unit Tests
///////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {

    use std::error::Error;

    use crate::{
        datamodel::SystemVariables,
        interpreter::{
            evaluator::{Evaluator, EvaluatorError},
            ArithmeticOperator, EcmaScriptValue, Expression, Literal, LogicalOperator, Operator,
            Unary,
        },
    };


    type TestResult = Result<(), Box<dyn Error>>;


    //FEAT: *TESTING* Develop a method to test large variety of value/type combos
    #[test]
    fn logical_evaluation() -> TestResult {
        let float_val = 2.0;
        let int_val = 2;

        // Create an Evaluator object loaded with a binary logical expression
        let expr = Expression::Binary(
            Box::new(Expression::Literal(Literal::Number(float_val))),
            Operator::Logical(LogicalOperator::EqualTo),
            Box::new(Expression::Literal(Literal::Number(int_val as f64))),
        );
        let sys_vars = SystemVariables::default();
        let evaluator = Evaluator::new(&expr, &sys_vars);

        eprintln!("Evaluating Expression '{}'...", expr);

        // Attempt to evaluate the expression
        let result_as_iv = evaluator.evaluate()?;
        eprintln!("Expression '{}' == {:?}", expr, result_as_iv);

        assert_eq!(
            result_as_iv,
            EcmaScriptValue::Boolean(float_val == int_val as f64)
        );

        Ok(())
    }

    #[test]
    fn arithmetic_evaluation() -> TestResult {
        let float_val = 4.0;
        let int_val = 0;

        // Create an Evaluator object loaded with a binary arithmetic expression
        let expr = Expression::Binary(
            Box::new(Expression::Literal(Literal::String(float_val.to_string()))),
            Operator::Arithmetic(ArithmeticOperator::Slash),
            Box::new(Expression::Literal(Literal::Number(int_val as f64))),
        );
        let sys_vars = SystemVariables::default();
        let evaluator = Evaluator::new(&expr, &sys_vars);

        eprintln!("Evaluating Expression '{}'...", expr);

        // Attempt to evaluate the expression
        let result_as_iv = evaluator.evaluate()?;
        eprintln!("Expression '{}' == {:?}", expr, result_as_iv);

        assert_eq!(result_as_iv, EcmaScriptValue::Number(f64::INFINITY));

        Ok(())
    }

    #[test]
    fn string_concatenation() -> TestResult {
        let float_val = 2.5;
        let int_val = 2;

        // Create an Evaluator object loaded with a binary arithmetic expression
        let expr = Expression::Binary(
            Box::new(Expression::Literal(Literal::String(float_val.to_string()))),
            Operator::Arithmetic(ArithmeticOperator::Plus),
            Box::new(Expression::Literal(Literal::String(int_val.to_string()))),
        );
        let sys_vars = SystemVariables::default();
        let evaluator = Evaluator::new(&expr, &sys_vars);

        eprintln!("Evaluating Expression '{}'...", expr);

        // Attempt to evaluate the expression
        let result_as_iv = evaluator.evaluate()?;
        eprintln!("Expression '{}' == {:?}", expr, result_as_iv);

        assert_eq!(
            result_as_iv,
            EcmaScriptValue::String(float_val.to_string() + &int_val.to_string())
        );

        Ok(())
    }

    #[test]
    fn null_comparison() -> TestResult {
        let int_val = 0;

        // Create an Evaluator object loaded with a binary arithmetic expression
        let expr = Expression::Binary(
            Box::new(Expression::Literal(Literal::String(int_val.to_string()))),
            Operator::Logical(LogicalOperator::EqualTo),
            Box::new(Expression::Literal(Literal::Null)),
        );
        let sys_vars = SystemVariables::default();
        let evaluator = Evaluator::new(&expr, &sys_vars);

        eprintln!("Evaluating Expression '{}'...", expr);

        // Attempt to evaluate the expression
        let result_as_iv = evaluator.evaluate()?;
        eprintln!("Expression '{}' == {:?}", expr, result_as_iv);

        assert_eq!(result_as_iv, EcmaScriptValue::Boolean(false));

        Ok(())
    }

    #[test]
    fn identifier_not_found() -> TestResult {
        // Create an expression with a nonexistent identifier
        let non_existent = "dne".to_string();
        let expr1 = Expression::Identifier(non_existent.clone());
        let sys_vars1 = SystemVariables::default();

        // Attempt to evaluate it
        let evaluator1 = Evaluator::new(&expr1, &sys_vars1);
        assert_eq!(
            evaluator1.evaluate(),
            Err(EvaluatorError::IdentifierNotFound(non_existent))
        );

        // Create an expression with an extant identifier
        let extant = "hello".to_string();
        let expected = EcmaScriptValue::String(extant.clone());
        let expr2 = Expression::Identifier(extant.clone());
        let mut sys_vars2 = SystemVariables::default();
        sys_vars2.set_data_member(&extant, expected.clone());

        // Attempt to evaluate it
        let evaluator2 = Evaluator::new(&expr2, &sys_vars2);
        assert_eq!(evaluator2.evaluate(), Ok(expected));

        Ok(())
    }

    #[test]
    fn string_negation() -> TestResult {
        // Create an expression with a negated string
        let test_str = "test".to_string();
        let expr = Expression::Unary(Unary::Negation(Box::new(Expression::Literal(
            Literal::String(test_str.clone()),
        ))));


        // Attempt to evaluate it
        assert_eq!(
            Evaluator::new(&expr, &SystemVariables::default(),).evaluate(),
            Err(EvaluatorError::StringNegation(test_str.clone()))
        );

        Ok(())
    }
}