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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//! # Lexical Environment
//!
//! <https://tc39.es/ecma262/#sec-lexical-environment-operations>
//!
//! The following operations are used to operate upon lexical environments
//! This is the entrypoint to lexical environments.

use super::global_environment_record::GlobalEnvironmentRecord;
use crate::{
    environment::environment_record_trait::EnvironmentRecordTrait, object::JsObject, BoaProfiler,
    Context, JsResult, JsValue,
};
use gc::Gc;
use std::{collections::VecDeque, error, fmt};

/// Environments are wrapped in a Box and then in a GC wrapper
pub type Environment = Gc<Box<dyn EnvironmentRecordTrait>>;

/// Give each environment an easy way to declare its own type
/// This helps with comparisons
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EnvironmentType {
    Declarative,
    Function,
    Global,
    Object,
}

/// The scope of a given variable
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VariableScope {
    /// The variable declaration is scoped to the current block (`let` and `const`)
    Block,
    /// The variable declaration is scoped to the current function (`var`)
    Function,
}

#[derive(Debug, Clone)]
pub struct LexicalEnvironment {
    environment_stack: VecDeque<Environment>,
}

/// An error that occurred during lexing or compiling of the source input.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EnvironmentError {
    details: String,
}

impl EnvironmentError {
    pub fn new(msg: &str) -> Self {
        Self {
            details: msg.to_string(),
        }
    }
}

impl fmt::Display for EnvironmentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.details)
    }
}

impl error::Error for EnvironmentError {}

impl LexicalEnvironment {
    pub fn new(global: JsObject) -> Self {
        let _timer = BoaProfiler::global().start_event("LexicalEnvironment::new", "env");
        let global_env = GlobalEnvironmentRecord::new(global.clone(), global);
        let mut lexical_env = Self {
            environment_stack: VecDeque::new(),
        };

        // lexical_env.push(global_env);
        lexical_env.environment_stack.push_back(global_env.into());
        lexical_env
    }
}

impl Context {
    pub(crate) fn push_environment<T: Into<Environment>>(&mut self, env: T) {
        self.realm
            .environment
            .environment_stack
            .push_back(env.into());
    }

    pub(crate) fn pop_environment(&mut self) -> Option<Environment> {
        self.realm.environment.environment_stack.pop_back()
    }

    pub(crate) fn get_this_binding(&mut self) -> JsResult<JsValue> {
        self.get_current_environment()
            .recursive_get_this_binding(self)
    }

    pub(crate) fn create_mutable_binding(
        &mut self,
        name: &str,
        deletion: bool,
        scope: VariableScope,
    ) -> JsResult<()> {
        self.get_current_environment()
            .recursive_create_mutable_binding(name, deletion, scope, self)
    }

    pub(crate) fn create_immutable_binding(
        &mut self,
        name: &str,
        deletion: bool,
        scope: VariableScope,
    ) -> JsResult<()> {
        self.get_current_environment()
            .recursive_create_immutable_binding(name, deletion, scope, self)
    }

    pub(crate) fn set_mutable_binding(
        &mut self,
        name: &str,
        value: JsValue,
        strict: bool,
    ) -> JsResult<()> {
        self.get_current_environment()
            .recursive_set_mutable_binding(name, value, strict, self)
    }

    pub(crate) fn initialize_binding(&mut self, name: &str, value: JsValue) -> JsResult<()> {
        self.get_current_environment()
            .recursive_initialize_binding(name, value, self)
    }

    /// When neededing to clone an environment (linking it with another environnment)
    /// cloning is more suited. The GC will remove the env once nothing is linking to it anymore
    pub(crate) fn get_current_environment(&mut self) -> Environment {
        self.realm
            .environment
            .environment_stack
            .back_mut()
            .expect("Could not get mutable reference to back object")
            .clone()
    }

    pub(crate) fn has_binding(&mut self, name: &str) -> JsResult<bool> {
        self.get_current_environment()
            .recursive_has_binding(name, self)
    }

    pub(crate) fn get_binding_value(&mut self, name: &str) -> JsResult<JsValue> {
        self.get_current_environment()
            .recursive_get_binding_value(name, self)
    }
}

#[cfg(test)]
mod tests {
    use crate::exec;

    #[test]
    fn let_is_blockscoped() {
        let scenario = r#"
          {
            let bar = "bar";
          }

          try{
            bar;
          } catch (err) {
            err.message
          }
        "#;

        assert_eq!(&exec(scenario), "\"bar is not defined\"");
    }

    #[test]
    fn const_is_blockscoped() {
        let scenario = r#"
          {
            const bar = "bar";
          }

          try{
            bar;
          } catch (err) {
            err.message
          }
        "#;

        assert_eq!(&exec(scenario), "\"bar is not defined\"");
    }

    #[test]
    fn var_not_blockscoped() {
        let scenario = r#"
          {
            var bar = "bar";
          }
          bar == "bar";
        "#;

        assert_eq!(&exec(scenario), "true");
    }

    #[test]
    fn functions_use_declaration_scope() {
        let scenario = r#"
          function foo() {
            try {
                bar;
            } catch (err) {
                return err.message;
            }
          }
          {
            let bar = "bar";
            foo();
          }
        "#;

        assert_eq!(&exec(scenario), "\"bar is not defined\"");
    }

    #[test]
    fn set_outer_var_in_blockscope() {
        let scenario = r#"
          var bar;
          {
            bar = "foo";
          }
          bar == "foo";
        "#;

        assert_eq!(&exec(scenario), "true");
    }

    #[test]
    fn set_outer_let_in_blockscope() {
        let scenario = r#"
          let bar;
          {
            bar = "foo";
          }
          bar == "foo";
        "#;

        assert_eq!(&exec(scenario), "true");
    }
}