From c4c312cc88bdf3cc987d0537b4ae0a5344a92420 Mon Sep 17 00:00:00 2001 From: Artemy Date: Mon, 8 Aug 2022 17:28:04 +0300 Subject: [PATCH] feat: check the existence of variable before define --- ROADMAP.md | 2 +- src/interpreter.rs | 38 ++++++++++++++++++++++++-------------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 5e27bde..c335bab 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -3,7 +3,6 @@ - [ ] Functions - [ ] imports - [ ] scopes of visibility -- [ ] parallel tasks `{parallel:[..tasks]}` - [ ] types conversion - [ ] methods for arrays - [ ] methods for strings @@ -12,5 +11,6 @@ - [x] yaml support? - [ ] command execution function - [ ] function for random +- [ ] delete variable and something else diff --git a/src/interpreter.rs b/src/interpreter.rs index 768243f..877d4cb 100644 --- a/src/interpreter.rs +++ b/src/interpreter.rs @@ -285,14 +285,19 @@ impl Interpreter { fn define(&mut self, vars: &Map) -> Value { for (name, value) in vars { - match value { - Value::Object(_) => { - let value = self.eval_node(value); - self.vars.insert(name.to_string(), value); - } - _ => { - self.vars.insert(name.to_string(), value.clone()); + if !self.var_exists(&name) { + match value { + Value::Object(_) => { + let value = self.eval_node(value); + self.vars.insert(name.to_string(), value); + } + _ => { + self.vars.insert(name.to_string(), value.clone()); + } } + } else { + self.error(&format!("The variable {} already exist, use assign", name)); + panic!() } } Value::Null @@ -311,9 +316,8 @@ impl Interpreter { fn assign(&mut self, vars: &Map) -> Value { for (name, value) in vars { - let var = self.vars.get(name); - match var { - Some(_) => match value { + if self.var_exists(&name) { + match value { Value::Object(_) => { let value = self.eval_node(value); self.vars.insert(name.to_string(), value); @@ -321,16 +325,22 @@ impl Interpreter { _ => { self.vars.insert(name.to_string(), value.clone()); } - }, - None => { - self.error(&format!("The variable {} does not exist", name)); - panic!(); } + } else { + self.error(&format!("The variable {} does not exist, use define", name)); + panic!(); } } Value::Null } + fn var_exists(&self, name: &String) -> bool { + match self.vars.get(name) { + Some(_) => true, + None => false, + } + } + fn calc(&mut self, value: &Vec) -> Value { let op1 = &value[0]; let operation = &value[1];