dust/src/abstract_tree/for.rs

74 lines
2.3 KiB
Rust
Raw Normal View History

2023-10-28 14:28:43 +00:00
use rayon::prelude::*;
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-28 14:28:43 +00:00
use crate::{AbstractTree, Error, 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 {
2023-10-28 14:28:43 +00:00
is_async: bool,
2023-10-17 18:06:02 +00:00
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-28 14:28:43 +00:00
let for_node = node.child(0).unwrap();
let is_async = match for_node.kind() {
"for" => false,
"async for" => true,
_ => {
return Err(Error::UnexpectedSyntaxNode {
expected: "\"for\" or \"async for\"",
actual: for_node.kind(),
location: for_node.start_position(),
relevant_source: source[for_node.byte_range()].to_string(),
})
}
};
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 {
2023-10-28 14:28:43 +00:00
is_async,
2023-10-17 18:06:02 +00:00
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
2023-10-28 14:28:43 +00:00
if self.is_async {
values.par_iter().try_for_each(|value| {
2023-10-29 23:31:06 +00:00
let mut iter_context = Map::new();
2023-10-17 18:06:02 +00:00
2023-10-29 23:31:06 +00:00
iter_context
.variables_mut()
.insert(key.clone(), value.clone());
2023-10-23 19:25:22 +00:00
2023-10-28 14:28:43 +00:00
self.item.run(source, &mut iter_context).map(|_value| ())
})?;
2023-10-23 19:25:22 +00:00
} else {
2023-10-28 14:28:43 +00:00
for value in values.iter() {
2023-10-29 23:31:06 +00:00
context.variables_mut().insert(key.clone(), value.clone());
2023-10-28 14:28:43 +00:00
self.item.run(source, context)?;
}
2023-10-17 18:06:02 +00:00
}
Ok(Value::Empty)
}
}