1
0
dust/src/abstract_tree/loop.rs

68 lines
1.5 KiB
Rust
Raw Normal View History

use crate::{
context::Context,
error::{RuntimeError, ValidationError},
};
2024-02-25 18:49:26 +00:00
2024-03-17 11:31:45 +00:00
use super::{AbstractTree, Action, Statement, Type, WithPosition};
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 {
2024-03-17 11:31:45 +00:00
statements: Vec<WithPosition<Statement>>,
2024-03-02 01:17:55 +00:00
}
2024-03-08 21:14:47 +00:00
impl Loop {
2024-03-17 11:31:45 +00:00
pub fn new(statements: Vec<WithPosition<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 {
2024-03-17 10:26:12 +00:00
statement.node.validate(_context)?;
2024-03-08 17:24:11 +00:00
}
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-17 10:26:12 +00:00
let action = statement.node.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 super::*;
#[test]
fn basic_loop() {
let result = Loop {
2024-03-17 11:48:06 +00:00
statements: vec![Statement::Break.with_position((0, 0))],
2024-03-08 17:24:11 +00:00
}
.run(&Context::new());
assert_eq!(result, Ok(Action::Break))
2024-02-25 18:49:26 +00:00
}
}