1
0
dust/src/abstract_tree/while.rs

45 lines
1.1 KiB
Rust
Raw Normal View History

2023-10-07 02:45:36 +00:00
use serde::{Deserialize, Serialize};
2023-10-07 16:37:35 +00:00
use crate::{AbstractTree, Expression, Item};
2023-10-07 02:45:36 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct While {
expression: Expression,
2023-10-07 16:37:35 +00:00
item: Item,
2023-10-07 02:45:36 +00:00
}
impl AbstractTree for While {
fn from_syntax_node(node: tree_sitter::Node, source: &str) -> crate::Result<Self> {
debug_assert_eq!("while", node.kind());
let expression_node = node.child(1).unwrap();
let expression = Expression::from_syntax_node(expression_node, source)?;
2023-10-07 16:37:35 +00:00
let item_node = node.child(3).unwrap();
let item = Item::from_syntax_node(item_node, source)?;
2023-10-07 02:45:36 +00:00
2023-10-07 16:37:35 +00:00
Ok(While { expression, item })
2023-10-07 02:45:36 +00:00
}
fn run(&self, context: &mut crate::VariableMap) -> crate::Result<crate::Value> {
while self.expression.run(context)?.as_boolean()? {
2023-10-07 16:37:35 +00:00
self.item.run(context)?;
2023-10-07 02:45:36 +00:00
}
Ok(crate::Value::Empty)
}
}
#[cfg(test)]
mod tests {
use crate::evaluate;
#[test]
fn evalualate_while_loop() {
assert_eq!(
evaluate("while false { 'foo' }"),
vec![Ok(crate::Value::Empty)]
)
}
}