From e9db34be8bf38f1d636ffac82e4bc3db5c727524 Mon Sep 17 00:00:00 2001 From: Jeff Date: Sun, 1 Oct 2023 05:27:02 -0400 Subject: [PATCH] Implement assignment --- src/interface.rs | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/src/interface.rs b/src/interface.rs index 3722feb..3d62f10 100644 --- a/src/interface.rs +++ b/src/interface.rs @@ -181,10 +181,14 @@ pub enum Statement { impl EvaluatorTree for Statement { fn new(node: Node, source: &str) -> Result { - let child = node.child(0).unwrap(); + let node = if node.kind() == "statement" { + node.child(0).unwrap() + } else { + node + }; match node.kind() { - "expression" => Ok(Self::Expression(Expression::new(child, source)?)), + "expression" => Ok(Self::Expression(Expression::new(node, source)?)), _ => Err(Error::UnexpectedSyntax { expected: "expression", actual: node.kind(), @@ -237,10 +241,10 @@ impl EvaluatorTree for Expression { fn run(&self, context: &mut VariableMap) -> Result { match self { - Expression::Identifier(identifier) => identifier.run(context), Expression::Value(value) => Ok(value.clone()), + Expression::Identifier(identifier) => identifier.run(context), Expression::ControlFlow(control_flow) => control_flow.run(context), - Expression::Assignment(_) => todo!(), + Expression::Assignment(assignment) => assignment.run(context), Expression::Math(math) => math.run(context), } } @@ -253,6 +257,10 @@ impl Identifier { pub fn take_inner(self) -> String { self.0 } + + pub fn inner(&self) -> &String { + &self.0 + } } impl EvaluatorTree for Identifier { @@ -311,25 +319,33 @@ impl EvaluatorTree for ControlFlow { #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)] pub struct Assignment { - identifier: String, + identifier: Identifier, statement: Statement, } -impl Assignment { - pub fn new(node: Node, source: &str) -> Result { +impl EvaluatorTree for Assignment { + fn new(node: Node, source: &str) -> Result { let sexp = node.to_sexp(); println!("{sexp}"); let identifier_node = node.child(0).unwrap(); let statement_node = node.child(2).unwrap(); - let identifier = source[identifier_node.byte_range()].to_string(); + let identifier = Identifier::new(identifier_node, source)?; let statement = Statement::new(statement_node, source)?; - Ok(Self { + Ok(Assignment { identifier, statement, }) } + + fn run(&self, context: &mut VariableMap) -> Result { + let value = self.statement.run(context)?; + + context.set_value(self.identifier.inner(), value)?; + + Ok(Value::Empty) + } } #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]