2024-02-29 02:04:38 +00:00
|
|
|
use crate::{
|
|
|
|
context::Context,
|
|
|
|
error::{RuntimeError, ValidationError},
|
|
|
|
};
|
2024-02-25 18:49:26 +00:00
|
|
|
|
2024-03-08 17:24:11 +00:00
|
|
|
use super::{AbstractTree, Action, Statement, Type};
|
2024-02-25 18:49:26 +00:00
|
|
|
|
2024-02-25 19:26:22 +00:00
|
|
|
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
|
2024-03-08 21:14:47 +00:00
|
|
|
pub struct Loop {
|
|
|
|
statements: Vec<Statement>,
|
2024-03-02 01:17:55 +00:00
|
|
|
}
|
|
|
|
|
2024-03-08 21:14:47 +00:00
|
|
|
impl Loop {
|
|
|
|
pub fn new(statements: Vec<Statement>) -> Self {
|
2024-03-02 01:17:55 +00:00
|
|
|
Self { statements }
|
|
|
|
}
|
2024-02-25 18:49:26 +00:00
|
|
|
}
|
|
|
|
|
2024-03-08 21:14:47 +00:00
|
|
|
impl AbstractTree for Loop {
|
2024-02-29 02:04:38 +00:00
|
|
|
fn expected_type(&self, _context: &Context) -> Result<Type, ValidationError> {
|
2024-03-08 17:24:11 +00:00
|
|
|
Ok(Type::None)
|
2024-02-29 02:04:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn validate(&self, _context: &Context) -> Result<(), ValidationError> {
|
2024-03-08 17:24:11 +00:00
|
|
|
for statement in &self.statements {
|
|
|
|
statement.validate(_context)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run(self, _context: &Context) -> Result<Action, RuntimeError> {
|
|
|
|
let mut index = 0;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
if index == self.statements.len() - 1 {
|
|
|
|
index = 0;
|
|
|
|
} else {
|
|
|
|
index += 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
let statement = self.statements[index].clone();
|
2024-03-08 19:29:53 +00:00
|
|
|
let action = statement.run(_context)?;
|
2024-03-08 17:24:11 +00:00
|
|
|
|
2024-03-08 19:29:53 +00:00
|
|
|
match action {
|
|
|
|
Action::Return(_) => {}
|
|
|
|
Action::None => {}
|
|
|
|
r#break => return Ok(r#break),
|
2024-03-08 17:24:11 +00:00
|
|
|
}
|
|
|
|
}
|
2024-02-29 02:04:38 +00:00
|
|
|
}
|
2024-03-08 17:24:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn basic_loop() {
|
|
|
|
let result = Loop {
|
2024-03-17 05:26:05 +00:00
|
|
|
statements: vec![Statement::Break],
|
2024-03-08 17:24:11 +00:00
|
|
|
}
|
|
|
|
.run(&Context::new());
|
2024-02-29 02:04:38 +00:00
|
|
|
|
2024-03-11 21:44:52 +00:00
|
|
|
assert_eq!(result, Ok(Action::Break))
|
2024-02-25 18:49:26 +00:00
|
|
|
}
|
|
|
|
}
|