dust/src/abstract_tree/for.rs

53 lines
1.5 KiB
Rust
Raw Normal View History

2023-10-17 18:06:02 +00:00
use serde::{Deserialize, Serialize};
2023-10-22 19:24:10 +00:00
use tree_sitter::Node;
2023-10-17 18:06:02 +00:00
2023-10-25 20:44:50 +00:00
use crate::{AbstractTree, Expression, Identifier, Item, Map, Result, Value};
2023-10-17 18:06:02 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct For {
identifier: Identifier,
expression: Expression,
item: Item,
}
impl AbstractTree for For {
2023-10-22 19:24:10 +00:00
fn from_syntax_node(source: &str, node: Node) -> Result<Self> {
2023-10-17 18:06:02 +00:00
let identifier_node = node.child(1).unwrap();
let identifier = Identifier::from_syntax_node(source, identifier_node)?;
let expression_node = node.child(3).unwrap();
let expression = Expression::from_syntax_node(source, expression_node)?;
let item_node = node.child(5).unwrap();
let item = Item::from_syntax_node(source, item_node)?;
Ok(For {
identifier,
expression,
item,
})
}
2023-10-25 20:44:50 +00:00
fn run(&self, source: &str, context: &mut Map) -> Result<Value> {
2023-10-26 22:03:59 +00:00
let expression_run = self.expression.run(source, context)?;
let values = expression_run.as_list()?.items();
2023-10-17 18:06:02 +00:00
let key = self.identifier.inner();
2023-10-23 19:25:22 +00:00
let original_value = context.get_value(key)?;
2023-10-17 18:06:02 +00:00
2023-10-26 22:03:59 +00:00
for value in values.iter() {
2023-10-17 18:06:02 +00:00
context.set_value(key.clone(), value.clone())?;
2023-10-23 19:25:22 +00:00
self.item.run(source, context)?;
}
if let Some(original_value) = original_value {
context.set_value(key.clone(), original_value)?;
} else {
context.set_value(key.clone(), Value::Empty)?;
2023-10-17 18:06:02 +00:00
}
Ok(Value::Empty)
}
}