1
0
dust/src/abstract_tree/loop.rs

75 lines
1.6 KiB
Rust
Raw Normal View History

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 {
fn expected_type(&self, _context: &Context) -> Result<Type, ValidationError> {
2024-03-08 17:24:11 +00:00
Ok(Type::None)
}
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-03-08 17:24:11 +00:00
}
#[cfg(test)]
mod tests {
use crate::{
abstract_tree::{Expression, ValueNode},
Value,
};
use super::*;
#[test]
fn basic_loop() {
let result = Loop {
2024-03-11 19:17:01 +00:00
statements: vec![Statement::Break(Some(Expression::Value(
ValueNode::Integer(42),
)))],
2024-03-08 17:24:11 +00:00
}
.run(&Context::new());
2024-03-11 19:17:01 +00:00
assert_eq!(result, Ok(Action::Break(Some(Value::integer(42)))))
2024-02-25 18:49:26 +00:00
}
}