1
0
dust/src/abstract_tree/while.rs

52 lines
1.4 KiB
Rust
Raw Normal View History

2023-10-07 02:45:36 +00:00
use serde::{Deserialize, Serialize};
2023-10-10 17:29:11 +00:00
use tree_sitter::Node;
2023-10-07 02:45:36 +00:00
2023-10-25 20:44:50 +00:00
use crate::{AbstractTree, Expression, Item, Map, Result, Value};
2023-10-07 02:45:36 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct While {
expression: Expression,
2023-10-09 19:54:47 +00:00
items: Vec<Item>,
2023-10-07 02:45:36 +00:00
}
impl AbstractTree for While {
2023-10-10 17:29:11 +00:00
fn from_syntax_node(source: &str, node: Node) -> crate::Result<Self> {
2023-10-07 02:45:36 +00:00
debug_assert_eq!("while", node.kind());
let expression_node = node.child(1).unwrap();
2023-10-10 17:29:11 +00:00
let expression = Expression::from_syntax_node(source, expression_node)?;
2023-10-07 02:45:36 +00:00
2023-10-09 19:54:47 +00:00
let child_count = node.child_count();
let mut items = Vec::with_capacity(child_count);
2023-10-07 02:45:36 +00:00
2023-10-09 19:54:47 +00:00
for index in 3..child_count - 1 {
let item_node = node.child(index).unwrap();
2023-10-10 17:29:11 +00:00
let item = Item::from_syntax_node(source, item_node)?;
2023-10-09 19:54:47 +00:00
items.push(item);
}
Ok(While { expression, items })
2023-10-07 02:45:36 +00:00
}
2023-10-25 20:44:50 +00:00
fn run(&self, source: &str, context: &mut Map) -> Result<Value> {
2023-10-10 17:29:11 +00:00
while self.expression.run(source, context)?.as_boolean()? {
2023-10-09 19:54:47 +00:00
for item in &self.items {
2023-10-10 17:29:11 +00:00
item.run(source, context)?;
2023-10-09 19:54:47 +00:00
}
2023-10-07 02:45:36 +00:00
}
Ok(crate::Value::Empty)
}
}
#[cfg(test)]
mod tests {
use crate::evaluate;
#[test]
fn evalualate_while_loop() {
2023-10-09 19:54:47 +00:00
assert_eq!(evaluate("while false { 'foo' }"), Ok(crate::Value::Empty))
2023-10-07 02:45:36 +00:00
}
}