1
0
dust/src/abstract_tree/math_operator.rs

68 lines
1.8 KiB
Rust
Raw Normal View History

2024-01-06 13:11:09 +00:00
use serde::{Deserialize, Serialize};
2024-01-31 18:51:48 +00:00
use crate::{
error::{RuntimeError, SyntaxError, ValidationError},
2024-02-11 00:31:47 +00:00
AbstractTree, Context, Format, SyntaxNode, Type, Value,
2024-01-31 18:51:48 +00:00
};
2024-01-06 13:11:09 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub enum MathOperator {
Add,
Subtract,
Multiply,
Divide,
Modulo,
}
impl AbstractTree for MathOperator {
2024-02-11 00:31:47 +00:00
fn from_syntax(
node: SyntaxNode,
_source: &str,
2024-02-11 00:31:47 +00:00
_context: &Context,
) -> Result<Self, SyntaxError> {
2024-01-06 13:11:09 +00:00
let operator_node = node.child(0).unwrap();
let operator = match operator_node.kind() {
"+" => MathOperator::Add,
"-" => MathOperator::Subtract,
"*" => MathOperator::Multiply,
"/" => MathOperator::Divide,
"%" => MathOperator::Modulo,
_ => {
2024-02-01 00:07:18 +00:00
return Err(SyntaxError::UnexpectedSyntaxNode {
2024-01-06 13:11:09 +00:00
expected: "+, -, *, / or %".to_string(),
actual: operator_node.kind().to_string(),
position: node.range().into(),
2024-01-06 13:11:09 +00:00
})
}
};
Ok(operator)
}
2024-02-11 00:31:47 +00:00
fn expected_type(&self, _context: &Context) -> Result<Type, ValidationError> {
2024-01-31 18:51:48 +00:00
Ok(Type::None)
2024-01-06 13:11:09 +00:00
}
2024-02-11 00:31:47 +00:00
fn validate(&self, _source: &str, _context: &Context) -> Result<(), ValidationError> {
2024-01-31 18:51:48 +00:00
Ok(())
}
2024-02-11 00:31:47 +00:00
fn run(&self, _source: &str, _context: &Context) -> Result<Value, RuntimeError> {
2024-01-31 18:51:48 +00:00
Ok(Value::none())
2024-01-06 13:11:09 +00:00
}
}
impl Format for MathOperator {
2024-01-06 13:53:31 +00:00
fn format(&self, output: &mut String, _indent_level: u8) {
2024-01-06 13:11:09 +00:00
let char = match self {
MathOperator::Add => '+',
MathOperator::Subtract => '-',
MathOperator::Multiply => '*',
MathOperator::Divide => '/',
MathOperator::Modulo => '%',
};
output.push(char);
}
}