2023-10-06 17:32:58 +00:00
|
|
|
//! Top-level unit of Dust code.
|
|
|
|
|
2023-10-07 16:37:35 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2023-10-06 17:32:58 +00:00
|
|
|
use tree_sitter::Node;
|
|
|
|
|
|
|
|
use crate::{AbstractTree, Error, Result, Statement, Value, VariableMap};
|
|
|
|
|
|
|
|
/// 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-06 17:32:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl AbstractTree for Item {
|
|
|
|
fn from_syntax_node(node: Node, source: &str) -> 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() {
|
|
|
|
"statement" => Statement::from_syntax_node(child, source)?,
|
|
|
|
_ => {
|
|
|
|
return Err(Error::UnexpectedSyntax {
|
|
|
|
expected: "comment or statement",
|
|
|
|
actual: child.kind(),
|
|
|
|
location: child.start_position(),
|
|
|
|
relevant_source: source[node.byte_range()].to_string(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
fn run(&self, context: &mut VariableMap) -> Result<Value> {
|
2023-10-09 19:54:47 +00:00
|
|
|
let mut prev_result = Ok(Value::Empty);
|
|
|
|
|
|
|
|
for statement in &self.statements {
|
|
|
|
prev_result?;
|
|
|
|
prev_result = statement.run(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
|
|
|
}
|
|
|
|
}
|