1
0
dust/src/abstract_tree/statement.rs

63 lines
2.2 KiB
Rust
Raw Normal View History

2023-10-06 17:32:58 +00:00
use serde::{Deserialize, Serialize};
use tree_sitter::Node;
use crate::{
2023-10-09 19:54:47 +00:00
r#while::While, AbstractTree, Assignment, Error, Expression, IfElse, Match, Result, Value,
VariableMap,
2023-10-06 17:32:58 +00:00
};
/// Abstract representation of a statement.
///
2023-10-09 19:54:47 +00:00
/// A statement may evaluate to an Empty value when run. If a Statement is an
/// Expression, it will always return a non-empty value when run.
2023-10-06 17:32:58 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub enum Statement {
Assignment(Box<Assignment>),
Expression(Expression),
IfElse(Box<IfElse>),
Match(Match),
2023-10-07 02:45:36 +00:00
While(Box<While>),
2023-10-06 17:32:58 +00:00
}
impl AbstractTree for Statement {
fn from_syntax_node(node: Node, source: &str) -> Result<Self> {
debug_assert_eq!("statement", node.kind());
let child = node.child(0).unwrap();
match child.kind() {
"assignment" => Ok(Statement::Assignment(Box::new(
Assignment::from_syntax_node(child, source)?,
))),
"expression" => Ok(Self::Expression(Expression::from_syntax_node(
child, source,
)?)),
"if_else" => Ok(Statement::IfElse(Box::new(IfElse::from_syntax_node(
child, source,
)?))),
"tool" => Ok(Statement::IfElse(Box::new(IfElse::from_syntax_node(
child, source,
)?))),
2023-10-07 02:45:36 +00:00
"while" => Ok(Statement::While(Box::new(While::from_syntax_node(
child, source,
)?))),
2023-10-06 17:32:58 +00:00
_ => Err(Error::UnexpectedSyntax {
expected: "assignment, expression, if...else or tool",
actual: child.kind(),
location: child.start_position(),
relevant_source: source[node.byte_range()].to_string(),
}),
}
}
fn run(&self, context: &mut VariableMap) -> Result<Value> {
match self {
Statement::Assignment(assignment) => assignment.run(context),
Statement::Expression(expression) => expression.run(context),
Statement::IfElse(if_else) => if_else.run(context),
Statement::Match(r#match) => r#match.run(context),
2023-10-07 02:45:36 +00:00
Statement::While(r#while) => r#while.run(context),
2023-10-06 17:32:58 +00:00
}
}
}