1
0
dust/src/abstract_tree/transform.rs

60 lines
1.8 KiB
Rust
Raw Normal View History

2023-10-26 22:03:59 +00:00
use rayon::prelude::*;
2023-10-17 20:40:07 +00:00
use serde::{Deserialize, Serialize};
2023-10-22 19:24:10 +00:00
use tree_sitter::Node;
2023-10-17 20:40:07 +00:00
2023-10-26 22:03:59 +00:00
use crate::{AbstractTree, Expression, Identifier, Item, List, Map, Result, Value};
2023-10-17 20:40:07 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct Transform {
identifier: Identifier,
expression: Expression,
item: Item,
}
impl AbstractTree for Transform {
2023-10-22 19:24:10 +00:00
fn from_syntax_node(source: &str, node: Node) -> Result<Self> {
2023-10-17 20:40:07 +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(Transform {
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 20:40:07 +00:00
let key = self.identifier.inner();
2023-10-26 22:03:59 +00:00
let context = context.clone();
let new_list = List::with_capacity(values.len());
values.par_iter().try_for_each_with(
(context, new_list.clone()),
|(context, new_list), value| {
context.set_value(key.clone(), value.clone()).unwrap();
let item_run = self.item.run(source, context);
match item_run {
Ok(value) => {
new_list.items_mut().push(value);
Ok(())
}
Err(error) => Err(error),
}
},
)?;
2023-10-17 20:40:07 +00:00
Ok(Value::List(new_list))
}
}