From 382cfdd9034663a0e41c2179403b2242dc6f150e Mon Sep 17 00:00:00 2001 From: numzero Date: Fri, 11 Apr 2025 20:29:40 +0300 Subject: [PATCH] add scope ops --- src/run.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/run.rs b/src/run.rs index 8f3cf68..e7507e0 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, fmt::Debug, rc::Rc}; +use std::{borrow::Cow, collections::HashMap, fmt::Debug, rc::Rc}; use crate::{ ast::{Constant, Expression, Location}, @@ -36,6 +36,20 @@ pub struct Scope { pub functions: HashMap, } +impl Scope { + pub fn get(&self, name: impl AsRef) -> Value { + self.variables.get(name.as_ref()).cloned() + } + + pub fn set(&mut self, name: Cow, value: Value) { + if let Some(value) = value { + self.variables.insert(name.into(), value); + } else { + self.variables.remove(name.as_ref()); + } + } +} + pub trait Eval { fn eval(&self, scope: &mut Scope) -> Value; } @@ -54,7 +68,7 @@ impl Eval for Constant { impl Eval for Location { fn eval(&self, scope: &mut Scope) -> Value { match self { - Location::Variable { name } => scope.variables.get(name).cloned(), + Location::Variable { name } => scope.get(name), Location::Field { table, index } => { let table = table.eval(scope); let Some(ValueInner::Table(table)) = table else {