about summary refs log tree commit diff
path: root/src/interpret/scope.rs
blob: d8b8f43409c5806e729e4ae1522c77f5fafafeee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use super::value::Value;
use crate::parse::ast::nodes::Identifier;
use std::collections::HashMap;

pub struct Scope {
    scopes: Vec<HashMap<Identifier, Value>>,
}

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: &str, value: Value) {
        for scope in self.scopes.iter_mut() {
            if scope.contains_key(ident) {
                scope.insert(ident.to_string(), value);
                return;
            }
        }

        let inner_scope = self
            .scopes
            .last_mut()
            .expect("Tried accessing scope after last frame is gone.");
        inner_scope.insert(ident.to_string(), value);
    }

    pub fn get_var(&self, ident: &str) -> Option<Value> {
        for scope in self.scopes.iter().rev() {
            if let Some(value) = scope.get(ident) {
                return Some(value.clone());
            }
        }
        None
    }
}