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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use core::fmt;
use hashbrown::HashMap;
use std::cell::RefCell;
use std::fmt::Display;
use std::rc::Rc;

use crate::callable::builtins::BUILTIN;
use crate::context::Context;
use crate::error::Error;
use crate::lang::{EvalResult, Signal};
use crate::object::types::Character;
use crate::object::ViewMut;

use super::{Expr, ExprList, List, Obj};

#[derive(Default, Clone, PartialEq)]
pub struct Environment {
    pub values: RefCell<HashMap<String, Obj>>,
    pub parent: Option<Rc<Environment>>,
}

impl fmt::Debug for Environment {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Environment")
            .field("map", &self.values)
            .finish()
    }
}

impl Environment {
    pub fn from_builtins() -> Rc<Environment> {
        let env = Rc::new(Environment::default());
        for (name, builtin) in BUILTIN.iter() {
            let builtin_fn = Obj::Function(
                ExprList::new(),
                Expr::Primitive(builtin.clone()),
                env.clone(),
            );

            env.insert(String::from(*name), builtin_fn);
        }
        env
    }

    pub fn len(&self) -> usize {
        self.values.borrow().len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn insert(&self, name: String, value: Obj) {
        self.values.borrow_mut().insert(name, value);
    }

    pub fn append(&self, l: List) {
        for (key, value) in l.pairs_ref().iter() {
            if let Character::Some(name) = key {
                self.values.borrow_mut().insert(name.clone(), value.clone());
            }
        }
    }

    pub fn get(&self, name: String) -> EvalResult {
        let (x, _) = self.find(name.clone())?;
        EvalResult::Ok(x.clone())
    }

    /// Find a variable in the environment or one of its parents.
    /// If the variable is found, a mutable view on it is returned.
    pub fn find(&self, name: String) -> Result<(Obj, Rc<Environment>), Signal> {
        let mut env = self;

        loop {
            if let Some(value) = env.values.borrow().get(&name) {
                let result = value.view_mut();

                let x = match result {
                    Obj::Promise(None, expr, env) => env.clone().eval(expr)?,
                    Obj::Promise(Some(result), ..) => *result,
                    _ => result,
                };

                return Result::Ok((x, Rc::new(env.clone())));

            // if not found, search through parent if available
            } else if let Some(parent) = &env.parent {
                env = parent;
                continue;

            // if we're at the top level, fall back to primitives if available
            } else if let Some(prim) = BUILTIN.get(name.as_str()) {
                let x = Obj::Function(
                    ExprList::new(),
                    Expr::Primitive(prim.clone()),
                    Rc::new(self.clone()), // TODO(bug): will this retain shared ref?
                );

                return Result::Ok((x, Rc::new(env.clone())));

            // otherwise, throw error
            } else {
                return Result::Err(Signal::Error(Error::VariableNotFound(name)));
            }
        }
    }

    pub fn get_mut(&self, name: String) -> EvalResult {
        let (x, env) = self.find(name.clone())?;
        if *self == *env {
            return EvalResult::Ok(x.view_mut());
        }

        // we found it in the parent environment, which means we first have to find it in the
        // current environment so we then modify it in the correct scope
        let xc = x.clone();
        let xm = xc.view_mut();
        self.insert(name, xc);

        EvalResult::Ok(xm)
    }
}

impl Display for Environment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<environment {:?}", self.values.as_ptr())?;

        // // print defined variable names
        // if self.values.borrow().len() > 0 {
        //     write!(f, " [")?;
        // }
        // for (i, k) in self.values.borrow().keys().enumerate() {
        //     if i > 0 {
        //         write!(f, ", ")?;
        //     }
        //     write!(f, "{}", k)?;
        // }
        // if self.values.borrow().len() > 0 {
        //     write!(f, "]")?;
        // }

        write!(f, ">")?;
        Ok(())
    }
}

#[cfg(test)]

mod tests {
    use crate::{r, r_expect};

    #[test]
    fn dollar() {
        r_expect! {{"
            e = environment()
            e$x = 1
            e$x == 1
        "}}
    }
}