1
0
dust/src/abstract_tree/loop.rs

73 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-02-26 21:27:01 +00:00
pub struct Loop<'src> {
2024-03-02 01:17:55 +00:00
statements: Vec<Statement<'src>>,
}
impl<'src> Loop<'src> {
pub fn new(statements: Vec<Statement<'src>>) -> Self {
Self { statements }
}
2024-02-25 18:49:26 +00:00
}
2024-02-26 21:27:01 +00:00
impl<'src> AbstractTree for Loop<'src> {
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 {
statements: vec![Statement::Break(Expression::Value(ValueNode::Integer(42)))],
}
.run(&Context::new());
2024-03-08 19:29:53 +00:00
assert_eq!(result, Ok(Action::Break(Value::integer(42))))
2024-02-25 18:49:26 +00:00
}
}