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-12 18:20:41 +00:00
|
|
|
use crate::{AbstractTree, Map, Result, Statement, 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> {
|
|
|
|
debug_assert_eq!("block", node.kind());
|
|
|
|
|
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);
|
|
|
|
|
2023-11-12 18:20:41 +00:00
|
|
|
for index in 1..statement_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-12 18:20:41 +00:00
|
|
|
fn run(&self, source: &str, context: &mut Map) -> Result<Value> {
|
2023-11-11 01:44:03 +00:00
|
|
|
if self.is_async {
|
|
|
|
let statements = &self.statements;
|
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)| {
|
|
|
|
let mut context = context.clone();
|
|
|
|
let result = statement.run(source, &mut context);
|
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 {
|
|
|
|
Some(result)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.unwrap_or(Ok(Value::Empty))
|
|
|
|
} 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 {
|
|
|
|
prev_result = Some(statement.run(source, context)?);
|
|
|
|
}
|
2023-11-11 01:44:03 +00:00
|
|
|
|
2023-11-12 18:20:41 +00:00
|
|
|
Ok(prev_result.unwrap_or(Value::Empty))
|
2023-11-11 01:44:03 +00:00
|
|
|
}
|
2023-10-31 17:04:22 +00:00
|
|
|
}
|
|
|
|
}
|