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
use super::{Executable, Interpreter, InterpreterState};
use crate::{
    builtins::value::{ResultValue, Value},
    syntax::ast::node::Switch,
};

#[cfg(test)]
mod tests;

impl Executable for Switch {
    fn run(&self, interpreter: &mut Interpreter) -> ResultValue {
        let default = self.default();
        let val = self.val().run(interpreter)?;
        let mut result = Value::null();
        let mut matched = false;
        interpreter.set_current_state(InterpreterState::Executing);

        // If a case block does not end with a break statement then subsequent cases will be run without
        // checking their conditions until a break is encountered.
        let mut fall_through: bool = false;

        for case in self.cases().iter() {
            let cond = case.condition();
            let block = case.body();
            if fall_through || val.strict_equals(&cond.run(interpreter)?) {
                matched = true;
                let result = block.run(interpreter)?;
                match interpreter.get_current_state() {
                    InterpreterState::Return => {
                        // Early return.
                        return Ok(result);
                    }
                    InterpreterState::Break(_label) => {
                        // Break statement encountered so therefore end switch statement.
                        interpreter.set_current_state(InterpreterState::Executing);
                        break;
                    }
                    _ => {
                        // Continuing execution / falling through to next case statement(s).
                        fall_through = true;
                    }
                }
            }
        }
        if !matched {
            if let Some(default) = default {
                result = default.run(interpreter)?;
            }
        }
        Ok(result)
    }
}