dust/src/abstract_tree/expression.rs

54 lines
2.1 KiB
Rust
Raw Normal View History

2023-10-06 17:32:58 +00:00
use serde::{Deserialize, Serialize};
use tree_sitter::Node;
2023-10-10 17:29:11 +00:00
use crate::{value::ValueNode, AbstractTree, Error, Identifier, Result, Value, VariableMap};
2023-10-06 17:32:58 +00:00
use super::{function_call::FunctionCall, logic::Logic, math::Math};
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub enum Expression {
2023-10-10 17:29:11 +00:00
Value(ValueNode),
2023-10-06 17:32:58 +00:00
Identifier(Identifier),
Math(Box<Math>),
Logic(Box<Logic>),
FunctionCall(FunctionCall),
}
impl AbstractTree for Expression {
2023-10-10 17:29:11 +00:00
fn from_syntax_node(source: &str, node: Node) -> Result<Self> {
2023-10-06 17:32:58 +00:00
debug_assert_eq!("expression", node.kind());
let child = node.child(0).unwrap();
let expression = match child.kind() {
2023-10-10 17:29:11 +00:00
"value" => Expression::Value(ValueNode::from_syntax_node(source, child)?),
"identifier" => Self::Identifier(Identifier::from_syntax_node(source, child)?),
"math" => Expression::Math(Box::new(Math::from_syntax_node(source, child)?)),
"logic" => Expression::Logic(Box::new(Logic::from_syntax_node(source, child)?)),
2023-10-06 17:32:58 +00:00
"function_call" => {
2023-10-10 17:29:11 +00:00
Expression::FunctionCall(FunctionCall::from_syntax_node(source, child)?)
2023-10-06 17:32:58 +00:00
}
_ => {
2023-10-10 17:29:11 +00:00
return Err(Error::UnexpectedSyntaxNode {
2023-10-06 17:32:58 +00:00
expected: "value, identifier, math or function_call",
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-06 17:32:58 +00:00
})
}
};
Ok(expression)
}
2023-10-10 17:29:11 +00:00
fn run(&self, source: &str, context: &mut VariableMap) -> Result<Value> {
2023-10-06 17:32:58 +00:00
match self {
2023-10-10 17:29:11 +00:00
Expression::Value(value_node) => value_node.run(source, context),
Expression::Identifier(identifier) => identifier.run(source, context),
Expression::Math(math) => math.run(source, context),
Expression::Logic(logic) => logic.run(source, context),
Expression::FunctionCall(function_call) => function_call.run(source, context),
2023-10-06 17:32:58 +00:00
}
}
}