1
0
dust/src/abstract_tree/transform.rs

56 lines
1.7 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-31 17:04:22 +00:00
use crate::{AbstractTree, Block, Expression, Identifier, 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,
2023-10-31 17:04:22 +00:00
item: Block,
2023-10-17 20:40:07 +00:00
}
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)?;
2023-11-03 22:04:45 +00:00
let item_node = node.child(4).unwrap();
2023-10-31 17:04:22 +00:00
let item = Block::from_syntax_node(source, item_node)?;
2023-10-17 20:40:07 +00:00
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-28 14:28:43 +00:00
let new_values = values
2023-10-27 02:35:59 +00:00
.par_iter()
.map(|value| {
2023-11-10 21:24:19 +00:00
let iter_context = Map::clone_from(context).unwrap();
2023-10-26 22:03:59 +00:00
2023-11-10 21:24:19 +00:00
iter_context
.variables_mut()
.unwrap()
.insert(key.clone(), value.clone());
2023-10-26 22:03:59 +00:00
2023-11-10 21:24:19 +00:00
self.item
.run(source, &mut iter_context.clone())
.unwrap_or_default()
2023-10-27 02:35:59 +00:00
})
2023-10-28 14:28:43 +00:00
.filter(|value| !value.is_empty())
2023-10-27 02:35:59 +00:00
.collect();
2023-10-17 20:40:07 +00:00
2023-10-28 14:28:43 +00:00
Ok(Value::List(List::with_items(new_values)))
2023-10-17 20:40:07 +00:00
}
}