1
0
dust/src/abstract_tree/block.rs

89 lines
2.7 KiB
Rust
Raw Normal View History

use std::sync::RwLock;
2023-11-11 01:44:03 +00:00
use rayon::prelude::*;
2023-10-31 17:04:22 +00:00
use serde::{Deserialize, Serialize};
use tree_sitter::Node;
2023-11-30 00:23:42 +00:00
use crate::{AbstractTree, Error, Map, Result, Statement, TypeDefinition, Value};
2023-10-31 17:04:22 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct Block {
2023-11-11 01:44:03 +00:00
is_async: bool,
statements: Vec<Statement>,
2023-11-04 03:42:10 +00:00
}
2023-10-31 17:04:22 +00:00
impl AbstractTree for Block {
fn from_syntax_node(source: &str, node: Node) -> Result<Self> {
2023-11-27 22:53:12 +00:00
Error::expect_syntax_node(source, "block", node)?;
2023-10-31 17:04:22 +00:00
2023-11-11 01:44:03 +00:00
let first_child = node.child(0).unwrap();
let is_async = first_child.kind() == "async";
2023-11-12 18:20:41 +00:00
let statement_count = if is_async {
node.child_count() - 3
} else {
node.child_count() - 2
};
2023-10-31 17:04:22 +00:00
let mut statements = Vec::with_capacity(statement_count);
for index in 1..node.child_count() - 1 {
2023-10-31 17:04:22 +00:00
let child_node = node.child(index).unwrap();
2023-11-12 18:20:41 +00:00
if child_node.is_named() {
2023-10-31 17:04:22 +00:00
let statement = Statement::from_syntax_node(source, child_node)?;
statements.push(statement);
}
}
2023-11-11 01:44:03 +00:00
Ok(Block {
is_async,
statements,
})
2023-10-31 17:04:22 +00:00
}
2023-11-30 00:23:42 +00:00
fn run(&self, source: &str, context: &Map) -> Result<Value> {
2023-11-11 01:44:03 +00:00
if self.is_async {
let statements = &self.statements;
let final_result = RwLock::new(Ok(Value::Empty));
2023-10-31 17:04:22 +00:00
2023-11-11 01:44:03 +00:00
statements
.into_par_iter()
.enumerate()
.find_map_first(|(index, statement)| {
if let Statement::Return(expression) = statement {
return Some(expression.run(source, &mut context.clone()));
}
let result = statement.run(source, &mut context.clone());
2023-10-31 17:04:22 +00:00
2023-11-11 01:44:03 +00:00
if result.is_err() {
Some(result)
} else if index == statements.len() - 1 {
let _ = final_result.write().unwrap().as_mut().map(|_| result);
None
2023-11-11 01:44:03 +00:00
} else {
None
}
})
.unwrap_or(final_result.into_inner().unwrap())
2023-11-11 01:44:03 +00:00
} else {
2023-11-12 18:20:41 +00:00
let mut prev_result = None;
2023-11-11 01:44:03 +00:00
2023-11-12 18:20:41 +00:00
for statement in &self.statements {
if let Statement::Return(expression) = statement {
return expression.run(source, context);
}
prev_result = Some(statement.run(source, context));
2023-11-12 18:20:41 +00:00
}
2023-11-11 01:44:03 +00:00
prev_result.unwrap_or(Ok(Value::Empty))
2023-11-11 01:44:03 +00:00
}
2023-10-31 17:04:22 +00:00
}
2023-11-30 00:23:42 +00:00
fn expected_type(&self, context: &Map) -> Result<TypeDefinition> {
self.statements.last().unwrap().expected_type(context)
}
2023-10-31 17:04:22 +00:00
}