diff options
author | Vincent Ambo <mail@tazj.in> | 2020-12-31T13·39+0300 |
---|---|---|
committer | tazjin <mail@tazj.in> | 2020-12-31T14·32+0000 |
commit | 48a54625ce287ff233219432b82d950bcfe10339 (patch) | |
tree | 7eeecddb148dc0d52d485577db22dd64573a64f9 /users/tazjin | |
parent | cc958e67309593b24634816c0c29d90eda84b3ed (diff) |
refactor(tazjin/rlox): Separate assignment and definition r/2034
So that: > var a = 15; > b = 12; Error in program: Error { line: 0, kind: UndefinedVariable("b") } > a = 12; print a; Number(12.0) Change-Id: I687e95ccc2d3084e39a71bd452656ae981c95191 Reviewed-on: https://cl.tvl.fyi/c/depot/+/2300 Reviewed-by: tazjin <mail@tazj.in> Tested-by: BuildkiteCI
Diffstat (limited to 'users/tazjin')
-rw-r--r-- | users/tazjin/rlox/src/interpreter.rs | 15 |
1 files changed, 14 insertions, 1 deletions
diff --git a/users/tazjin/rlox/src/interpreter.rs b/users/tazjin/rlox/src/interpreter.rs index 0855068b6387..8d968a1f20dd 100644 --- a/users/tazjin/rlox/src/interpreter.rs +++ b/users/tazjin/rlox/src/interpreter.rs @@ -28,6 +28,19 @@ impl Environment { kind: ErrorKind::UndefinedVariable(ident.into()), }) } + + fn assign(&mut self, name: &scanner::Token, value: Literal) -> Result<(), Error> { + let ident = identifier_str(name)?; + let target = self.values + .get_mut(ident) + .ok_or_else(|| Error { + line: name.line, + kind: ErrorKind::UndefinedVariable(ident.into()), + })?; + + *target = value; + Ok(()) + } } fn identifier_str<'a>(name: &'a scanner::Token) -> Result<&'a str, Error> { @@ -156,7 +169,7 @@ impl Interpreter { fn eval_assign<'a>(&mut self, assign: &parser::Assign<'a>) -> Result<Literal, Error> { let value = self.eval(&assign.value)?; - self.globals.define(&assign.name, value.clone())?; + self.globals.assign(&assign.name, value.clone())?; Ok(value) } } |