dust/src/abstract_tree/item.rs

77 lines
2.3 KiB
Rust
Raw Normal View History

2023-10-06 17:32:58 +00:00
//! Top-level unit of Dust code.
2023-10-16 20:48:02 +00:00
use rayon::prelude::*;
2023-10-07 16:37:35 +00:00
use serde::{Deserialize, Serialize};
2023-10-06 17:32:58 +00:00
use tree_sitter::Node;
2023-10-25 20:44:50 +00:00
use crate::{AbstractTree, Error, Map, Result, Statement, Value};
2023-10-06 17:32:58 +00:00
/// An abstractiton of an independent unit of source code, or a comment.
///
/// Items are either comments, which do nothing, or statements, which can be run
/// to produce a single value or interact with a context by creating or
/// referencing variables.
2023-10-07 16:37:35 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
2023-10-09 19:54:47 +00:00
pub struct Item {
statements: Vec<Statement>,
}
impl Item {
pub fn new(statements: Vec<Statement>) -> Self {
Self { statements }
}
2023-10-16 20:48:02 +00:00
2023-10-25 20:44:50 +00:00
pub fn run_parallel(&self, source: &str, context: &mut Map) -> Result<Value> {
2023-10-17 01:13:58 +00:00
let statements = &self.statements;
let run_result = statements.into_par_iter().try_for_each(|statement| {
2023-10-16 20:48:02 +00:00
let mut context = context.clone();
2023-10-17 01:13:58 +00:00
statement.run(source, &mut context).map(|_| ())
2023-10-16 20:48:02 +00:00
});
2023-10-17 01:13:58 +00:00
match run_result {
Ok(()) => Ok(Value::Empty),
Err(error) => Err(error),
}
2023-10-16 20:48:02 +00:00
}
2023-10-06 17:32:58 +00:00
}
impl AbstractTree for Item {
2023-10-10 17:29:11 +00:00
fn from_syntax_node(source: &str, node: Node) -> Result<Self> {
2023-10-07 16:37:35 +00:00
debug_assert_eq!("item", node.kind());
2023-10-09 19:54:47 +00:00
let child_count = node.child_count();
let mut statements = Vec::with_capacity(child_count);
for index in 0..child_count {
let child = node.child(index).unwrap();
let statement = match child.kind() {
2023-10-10 17:29:11 +00:00
"statement" => Statement::from_syntax_node(source, child)?,
2023-10-09 19:54:47 +00:00
_ => {
2023-10-10 17:29:11 +00:00
return Err(Error::UnexpectedSyntaxNode {
2023-10-09 19:54:47 +00:00
expected: "comment or statement",
actual: child.kind(),
location: child.start_position(),
2023-10-10 17:29:11 +00:00
relevant_source: source[child.byte_range()].to_string(),
2023-10-09 19:54:47 +00:00
})
}
};
statements.push(statement);
2023-10-06 17:32:58 +00:00
}
2023-10-09 19:54:47 +00:00
Ok(Item { statements })
2023-10-06 17:32:58 +00:00
}
2023-10-25 20:44:50 +00:00
fn run(&self, source: &str, context: &mut Map) -> Result<Value> {
2023-10-09 19:54:47 +00:00
let mut prev_result = Ok(Value::Empty);
for statement in &self.statements {
prev_result?;
2023-10-10 17:29:11 +00:00
prev_result = statement.run(source, context);
2023-10-06 17:32:58 +00:00
}
2023-10-09 19:54:47 +00:00
prev_result
2023-10-06 17:32:58 +00:00
}
}