dust/src/abstract_tree/math.rs

72 lines
2.3 KiB
Rust
Raw Normal View History

2023-10-06 17:32:58 +00:00
use serde::{Deserialize, Serialize};
2024-01-10 20:03:52 +00:00
use crate::{
2024-01-31 18:51:48 +00:00
error::{RuntimeError, SyntaxError, ValidationError},
2024-02-11 00:31:47 +00:00
AbstractTree, Context, Expression, Format, MathOperator, SyntaxNode, Type, Value,
2024-01-10 20:03:52 +00:00
};
2023-10-06 17:32:58 +00:00
2023-12-06 19:13:22 +00:00
/// Abstract representation of a math operation.
///
/// Dust currently supports the four basic operations and the modulo (or
/// remainder) operator.
2023-10-06 17:32:58 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct Math {
left: Expression,
operator: MathOperator,
right: Expression,
}
impl AbstractTree for Math {
2024-02-11 00:31:47 +00:00
fn from_syntax(node: SyntaxNode, source: &str, context: &Context) -> Result<Self, SyntaxError> {
2024-02-01 00:35:27 +00:00
SyntaxError::expect_syntax_node(source, "math", node)?;
2023-12-30 02:15:03 +00:00
2023-10-06 17:32:58 +00:00
let left_node = node.child(0).unwrap();
2024-01-10 20:03:52 +00:00
let left = Expression::from_syntax(left_node, source, context)?;
2023-10-06 17:32:58 +00:00
2024-01-06 13:11:09 +00:00
let operator_node = node.child(1).unwrap();
2024-01-10 20:03:52 +00:00
let operator = MathOperator::from_syntax(operator_node, source, context)?;
2023-10-06 17:32:58 +00:00
let right_node = node.child(2).unwrap();
2024-01-10 20:03:52 +00:00
let right = Expression::from_syntax(right_node, source, context)?;
2023-10-06 17:32:58 +00:00
Ok(Math {
left,
operator,
right,
})
}
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
self.left.expected_type(context)
}
2024-02-11 00:31:47 +00:00
fn validate(&self, _source: &str, _context: &Context) -> Result<(), ValidationError> {
2024-02-01 01:52:34 +00:00
self.left.validate(_source, _context)?;
self.right.validate(_source, _context)
2024-01-31 18:51:48 +00:00
}
2024-02-11 00:31:47 +00:00
fn run(&self, source: &str, context: &Context) -> Result<Value, RuntimeError> {
2023-10-13 23:56:57 +00:00
let left = self.left.run(source, context)?;
let right = self.right.run(source, context)?;
let value = match self.operator {
MathOperator::Add => left + right,
MathOperator::Subtract => left - right,
MathOperator::Multiply => left * right,
MathOperator::Divide => left / right,
MathOperator::Modulo => left % right,
}?;
2023-10-06 17:32:58 +00:00
2023-10-13 23:56:57 +00:00
Ok(value)
2023-10-06 17:32:58 +00:00
}
}
2024-01-06 13:11:09 +00:00
impl Format for Math {
fn format(&self, output: &mut String, indent_level: u8) {
self.left.format(output, indent_level);
output.push(' ');
self.operator.format(output, indent_level);
output.push(' ');
self.right.format(output, indent_level);
2024-01-06 10:00:36 +00:00
}
}