interpreter/
runtime.rs

1//! This module contains the [`Environment`] struct, which is used to store and lookup
2//! SAP variables and functions. It also contains a type alias for a shared
3//! [`Environment`] reference.
4use std::cell::RefCell;
5use std::collections::HashMap;
6use std::rc::Rc;
7
8use crate::Value;
9
10/// The `EnvRef` type is a reference-counted, mutable reference to an [`Environment`].
11///
12/// The [`Rc`] type is used to allow multiple references to the same [`Environment`]. This
13/// is useful when creating a tree of environments, where each environment can lookup
14/// all the variables and functions of it's parent enviornment.
15///
16/// The [`RefCell`] type is used to allow the [`Environment`] to be mutable, even when it
17/// is shared between multiple references.
18pub type EnvRef = Rc<RefCell<Environment>>;
19
20/// An [`Environment`] is a hashmap in which SAP variables and functions are stored. It
21/// also contains an optional reference to the outer environment. This creates a tree of
22/// environments, where each environment can lookup all the variables and functions of
23/// it's parent enviornment.
24#[derive(Debug, PartialEq)]
25pub struct Environment {
26    /// A `HashMap` containing all variables and functions in the current environment.
27    members: HashMap<String, Rc<Value>>,
28    /// An optional reference to the parent environment.
29    outer: Option<EnvRef>,
30}
31
32impl Environment {
33    pub fn new() -> Self {
34        Self {
35            members: HashMap::new(),
36            outer: None,
37        }
38    }
39
40    /// Creates a new child [`Environment`] to the given `outer` environment.
41    ///
42    /// Equivalent to:
43    /// ```compile_fail ignore
44    /// let mut env = Environment::new();
45    /// env.outer = Some(Rc::clone(outer));
46    /// ```
47    pub fn new_enclosed_environment(outer: &EnvRef) -> Self {
48        let mut env = Self::new();
49        env.outer = Some(Rc::clone(outer));
50        return env;
51    }
52
53    /// Looks up the given `name` in the current environment and all parent environments.
54    ///
55    /// If the name is found, the function returns a reference to the `Value` associated
56    /// with the name. If the name is not found, the function returns `None`.
57    pub fn lookup(&self, name: &str) -> Option<Rc<Value>> {
58        match self.members.get(name) {
59            Some(obj) => Some(Rc::clone(obj)),
60            None => {
61                if let Some(outer) = &self.outer {
62                    return outer.borrow().lookup(name);
63                } else {
64                    return None;
65                }
66            }
67        }
68    }
69
70    /// Stores the given `name` and `value` in the current environment.
71    pub fn store(&mut self, name: String, value: Rc<Value>) {
72        self.members.insert(name, value);
73    }
74}
75
76/// Implements the `Display` trait for [`Environment`]. This allows an [`Environment`] to
77/// be printed in a human-readable format.
78impl std::fmt::Display for Environment {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        let mut formatted_members = self
81            .members
82            .iter()
83            .map(|(key, value)| format!("    <{}> {} = {:?}", (**value).variant_name(), key, value))
84            .collect::<Vec<String>>();
85        formatted_members.sort();
86
87        write!(f, "== Env ====================\n")?;
88
89        if formatted_members.len() > 0 {
90            write!(f, "\n{}\n", formatted_members.join("\n"))?
91        } else {
92            write!(f, "\n    <no members>\n")?
93        }
94
95        write!(f, "\n===========================")
96    }
97}