summaryrefslogtreecommitdiff
path: root/src/eval/scope.rs
blob: 5178c81916a5e261645f2087148b17c2a87c1147 (plain) (blame)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
use std::iter;
use std::rc::Rc;

use super::{Args, Class, Construct, EvalContext, Function, Set, Value};
use crate::diag::TypResult;
use crate::util::EcoString;

/// A slot where a variable is stored.
pub type Slot = Rc<RefCell<Value>>;

/// A stack of scopes.
#[derive(Debug, Default, Clone)]
pub struct Scopes<'a> {
    /// The active scope.
    pub top: Scope,
    /// The stack of lower scopes.
    pub scopes: Vec<Scope>,
    /// The base scope.
    pub base: Option<&'a Scope>,
}

impl<'a> Scopes<'a> {
    /// Create a new, empty hierarchy of scopes.
    pub fn new(base: Option<&'a Scope>) -> Self {
        Self { top: Scope::new(), scopes: vec![], base }
    }

    /// Enter a new scope.
    pub fn enter(&mut self) {
        self.scopes.push(std::mem::take(&mut self.top));
    }

    /// Exit the topmost scope.
    ///
    /// This panics if no scope was entered.
    pub fn exit(&mut self) {
        self.top = self.scopes.pop().expect("no pushed scope");
    }

    /// Define a constant variable with a value in the active scope.
    pub fn def_const(&mut self, var: impl Into<EcoString>, value: impl Into<Value>) {
        self.top.def_const(var, value);
    }

    /// Define a mutable variable with a value in the active scope.
    pub fn def_mut(&mut self, var: impl Into<EcoString>, value: impl Into<Value>) {
        self.top.def_mut(var, value);
    }

    /// Define a variable with a slot in the active scope.
    pub fn def_slot(&mut self, var: impl Into<EcoString>, slot: Slot) {
        self.top.def_slot(var, slot);
    }

    /// Look up the slot of a variable.
    pub fn get(&self, var: &str) -> Option<&Slot> {
        iter::once(&self.top)
            .chain(self.scopes.iter().rev())
            .chain(self.base.into_iter())
            .find_map(|scope| scope.get(var))
    }
}

/// A map from variable names to variable slots.
#[derive(Default, Clone)]
pub struct Scope {
    /// The mapping from names to slots.
    values: HashMap<EcoString, Slot>,
}

impl Scope {
    /// Create a new empty scope.
    pub fn new() -> Self {
        Self::default()
    }

    /// Define a constant variable with a value.
    pub fn def_const(&mut self, var: impl Into<EcoString>, value: impl Into<Value>) {
        let cell = RefCell::new(value.into());

        // Make it impossible to write to this value again.
        // FIXME: Use Ref::leak once stable.
        std::mem::forget(cell.borrow());

        self.values.insert(var.into(), Rc::new(cell));
    }

    /// Define a mutable variable with a value.
    pub fn def_mut(&mut self, var: impl Into<EcoString>, value: impl Into<Value>) {
        self.values.insert(var.into(), Rc::new(RefCell::new(value.into())));
    }

    /// Define a variable with a slot.
    pub fn def_slot(&mut self, var: impl Into<EcoString>, slot: Slot) {
        self.values.insert(var.into(), slot);
    }

    /// Define a constant function.
    pub fn def_func<F>(&mut self, name: &str, f: F)
    where
        F: Fn(&mut EvalContext, &mut Args) -> TypResult<Value> + 'static,
    {
        let name = EcoString::from(name);
        self.def_const(name.clone(), Function::new(Some(name), f));
    }

    /// Define a constant class.
    pub fn def_class<T>(&mut self, name: &str)
    where
        T: Construct + Set + 'static,
    {
        let name = EcoString::from(name);
        self.def_const(name.clone(), Class::new::<T>(name));
    }

    /// Look up the value of a variable.
    pub fn get(&self, var: &str) -> Option<&Slot> {
        self.values.get(var)
    }

    /// Iterate over all definitions.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &Slot)> {
        self.values.iter().map(|(k, v)| (k.as_str(), v))
    }
}

impl Debug for Scope {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str("Scope ")?;
        f.debug_map()
            .entries(self.values.iter().map(|(k, v)| (k, v.borrow())))
            .finish()
    }
}