1
0
dust/src/abstract_tree/assignment.rs

75 lines
2.3 KiB
Rust
Raw Normal View History

2023-10-06 17:32:58 +00:00
use serde::{Deserialize, Serialize};
use tree_sitter::Node;
2023-10-09 19:54:47 +00:00
use crate::{AbstractTree, Error, Result, Value, VariableMap};
2023-10-06 17:32:58 +00:00
use super::{identifier::Identifier, statement::Statement};
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct Assignment {
identifier: Identifier,
2023-10-09 19:54:47 +00:00
operator: AssignmentOperator,
2023-10-06 17:32:58 +00:00
statement: Statement,
}
2023-10-09 19:54:47 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub enum AssignmentOperator {
Equal,
PlusEqual,
MinusEqual,
}
2023-10-06 17:32:58 +00:00
impl AbstractTree for Assignment {
fn from_syntax_node(node: Node, source: &str) -> Result<Self> {
let identifier_node = node.child(0).unwrap();
let identifier = Identifier::from_syntax_node(identifier_node, source)?;
2023-10-09 19:54:47 +00:00
let operator_node = node.child(1).unwrap().child(0).unwrap();
let operator = match operator_node.kind() {
"=" => AssignmentOperator::Equal,
"+=" => AssignmentOperator::PlusEqual,
"-=" => AssignmentOperator::MinusEqual,
_ => {
return Err(Error::UnexpectedSyntax {
expected: "=, += or -=",
actual: operator_node.kind(),
location: operator_node.start_position(),
relevant_source: source[node.byte_range()].to_string(),
})
}
};
2023-10-06 17:32:58 +00:00
let statement_node = node.child(2).unwrap();
let statement = Statement::from_syntax_node(statement_node, source)?;
Ok(Assignment {
identifier,
2023-10-09 19:54:47 +00:00
operator,
2023-10-06 17:32:58 +00:00
statement,
})
}
fn run(&self, context: &mut VariableMap) -> Result<Value> {
let key = self.identifier.clone().take_inner();
2023-10-09 19:54:47 +00:00
let mut value = self.statement.run(context)?;
match self.operator {
AssignmentOperator::PlusEqual => {
if let Some(previous_value) = context.get_value(&key)? {
value += previous_value
}
}
AssignmentOperator::MinusEqual => {
if let Some(previous_value) = context.get_value(&key)? {
value -= previous_value
}
}
AssignmentOperator::Equal => {}
}
2023-10-06 17:32:58 +00:00
context.set_value(key, value)?;
Ok(Value::Empty)
}
}