1
0
dust/src/abstract_tree/loop.rs

72 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();
if let Statement::Break(expression) = statement {
break expression.run(_context);
} else {
statement.run(_context)?;
}
}
}
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 17:24:11 +00:00
assert_eq!(result, Ok(Action::Return(Value::integer(42))))
2024-02-25 18:49:26 +00:00
}
}