From cff714c07e5e2c0f11c121504500a554d60c08cc Mon Sep 17 00:00:00 2001 From: Mel Date: Thu, 21 Oct 2021 23:46:01 +0200 Subject: Implement program walking. --- src/interpret/scope.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/interpret/scope.rs (limited to 'src/interpret/scope.rs') diff --git a/src/interpret/scope.rs b/src/interpret/scope.rs new file mode 100644 index 0000000..de32692 --- /dev/null +++ b/src/interpret/scope.rs @@ -0,0 +1,45 @@ +use super::value::Value; +use crate::parse::ast::nodes::Identifier; +use std::collections::HashMap; + +pub struct Scope { + scopes: Vec>, +} + +impl Scope { + pub fn new() -> Self { + Scope { scopes: Vec::new() } + } + + pub fn nest(&mut self) { + self.scopes.push(HashMap::new()); + } + + pub fn unnest(&mut self) { + self.scopes.pop(); + } + + pub fn set_var(&mut self, ident: &Identifier, value: Value) { + for scope in self.scopes.iter_mut() { + if scope.contains_key(ident) { + scope.insert(ident.clone(), value); + return; + } + } + + let inner_scope = self + .scopes + .last_mut() + .expect("Tried accessing scope after last frame is gone."); + inner_scope.insert(ident.clone(), value); + } + + pub fn get_var(&self, ident: &Identifier) -> Option { + for scope in self.scopes.iter().rev() { + if let Some(value) = scope.get(ident) { + return Some(value.clone()); + } + } + None + } +} -- cgit 1.4.1