1
0
dust/src/abstract_tree/block.rs

95 lines
2.5 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 Block {
statements: Vec<Statement>,
2024-02-25 18:49:26 +00:00
}
2024-03-08 21:14:47 +00:00
impl Block {
pub fn new(statements: Vec<Statement>) -> Self {
2024-02-25 18:49:26 +00:00
Self { statements }
}
}
2024-03-08 21:14:47 +00:00
impl AbstractTree for Block {
fn expected_type(&self, _context: &Context) -> Result<Type, ValidationError> {
2024-03-09 17:58:29 +00:00
if let Some(statement) = self.statements.last() {
statement.expected_type(_context)
} else {
Ok(Type::None)
}
}
fn validate(&self, _context: &Context) -> Result<(), ValidationError> {
2024-03-02 00:29:16 +00:00
for statement in &self.statements {
statement.validate(_context)?;
}
Ok(())
}
2024-03-08 17:24:11 +00:00
fn run(self, _context: &Context) -> Result<Action, RuntimeError> {
2024-03-09 17:58:29 +00:00
let mut previous = Action::None;
2024-03-02 00:29:16 +00:00
for statement in self.statements {
2024-03-08 17:24:11 +00:00
let action = statement.run(_context)?;
previous = match action {
2024-03-09 17:58:29 +00:00
Action::Return(value) => Action::Return(value),
2024-03-11 22:21:40 +00:00
Action::None => Action::None,
Action::Break => return Ok(action),
2024-03-08 17:24:11 +00:00
};
2024-03-02 00:29:16 +00:00
}
2024-03-09 17:58:29 +00:00
Ok(previous)
2024-03-02 00:29:16 +00:00
}
}
#[cfg(test)]
mod tests {
2024-03-09 17:58:29 +00:00
use crate::{
abstract_tree::{Expression, ValueNode},
Value,
};
2024-03-02 00:29:16 +00:00
use super::*;
#[test]
fn run_returns_value_of_final_statement() {
let block = Block::new(vec![
2024-03-17 06:51:33 +00:00
Statement::Expression(
Expression::Value(ValueNode::Integer(1)).positioned((0..1).into()),
),
Statement::Expression(
Expression::Value(ValueNode::Integer(2)).positioned((0..1).into()),
),
Statement::Expression(
Expression::Value(ValueNode::Integer(42)).positioned((0..1).into()),
),
2024-03-02 00:29:16 +00:00
]);
2024-03-08 17:24:11 +00:00
assert_eq!(
block.run(&Context::new()),
Ok(Action::Return(Value::integer(42)))
)
2024-03-02 00:29:16 +00:00
}
#[test]
fn expected_type_returns_type_of_final_statement() {
let block = Block::new(vec![
2024-03-17 06:51:33 +00:00
Statement::Expression(
Expression::Value(ValueNode::String("42".to_string())).positioned((0..0).into()),
),
Statement::Expression(
Expression::Value(ValueNode::Integer(42)).positioned((0..1).into()),
),
2024-03-02 00:29:16 +00:00
]);
assert_eq!(block.expected_type(&Context::new()), Ok(Type::Integer))
2024-02-25 18:49:26 +00:00
}
}