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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! [`Heap`], [`JSRef`]s, scopes.

use crate::ast::{
    Binding,
    Identifier,
};
use crate::function::{
    CallContext,
    HostFn,
};
use crate::object::HostClass;
use crate::prelude::*;
use crate::{
    builtin,
    source,
    Exception,
    Interpretable,
    Interpreted,
    JSObject,
    JSResult,
    JSValue,
    JSON,
};

/// A heap reference: a Heap index.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JSRef(usize);

impl JSRef {
    pub const NULL: JSRef = JSRef(0);

    pub fn is_null(&self) -> bool {
        *self == Self::NULL
    }

    pub fn has_proto(&self, protoref: JSRef, heap: &Heap) -> bool {
        (heap.get(*self).protochain(heap)).any(|pref| pref == protoref)
    }

    pub fn isinstance(&self, constructor: JSRef, heap: &Heap) -> JSResult<bool> {
        let protoval = heap.get(constructor).get_own_value("prototype");
        let protoval = protoval.ok_or_else(|| {
            let what = Interpreted::from(constructor);
            Exception::TypeErrorNotCallable(what)
        })?;
        let protoref = protoval.to_ref()?;
        Ok(self.has_proto(protoref, heap))
    }

    /// Check if the object behind the reference `self` has a prototype of `constructor`.
    /// ```
    /// # use sljs::{JSObject, Heap};
    /// # let mut heap = Heap::new();
    /// let array_ref = heap.alloc(JSObject::from_array(vec![]));
    /// array_ref.expect_instance("Array", &heap).unwrap();
    /// ```
    pub fn expect_instance(&self, constructor: &str, heap: &Heap) -> JSResult<()> {
        let ctrval = heap
            .lookup_var(constructor)
            .ok_or_else(|| Exception::ReferenceNotFound(Identifier::from(constructor)))?;
        let ctrref = ctrval.to_ref(heap)?;
        match self.isinstance(ctrref, heap)? {
            true => Ok(()),
            false => {
                let what = Interpreted::from(*self);
                let of = constructor.into();
                Err(Exception::TypeErrorInstanceRequired(what, of))
            }
        }
    }
}

/// Runtime heap
#[derive(Debug)]
pub struct Heap {
    objects: Vec<JSObject>,
    pub loc: Option<Box<source::Location>>,
}

impl Heap {
    // A set of fixed slots on the heap.
    // This untangles the builtins intialization and avoids frequent lookups
    // for e.g. `Array.prototype`.
    pub const NULL: JSRef = JSRef(0);
    pub const GLOBAL: JSRef = JSRef(1);
    pub const OBJECT_PROTO: JSRef = JSRef(2);
    pub const FUNCTION_PROTO: JSRef = JSRef(3);
    pub const ARRAY_PROTO: JSRef = JSRef(4);
    pub const BOOLEAN_PROTO: JSRef = JSRef(5);
    //pub const NUMBER_PROTO: JSRef = JSRef(6);
    pub const STRING_PROTO: JSRef = JSRef(7);
    pub const REGEXP_PROTO: JSRef = JSRef(8);

    pub const ERROR_PROTO: JSRef = JSRef(9);

    const USERSTART: usize = 10;

    pub(crate) const SCOPE_THIS: &'static str = "[[this]]";
    const LOCAL_SCOPE: &'static str = "[[local_scope]]";
    pub(crate) const SAVED_SCOPE: &'static str = "[[saved_scope]]";
    const CAPTURED_SCOPE: &'static str = "[[captured_scope]]";

    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        let mut objects = Vec::with_capacity(1024);
        for _ in 0..Self::USERSTART {
            objects.push(JSObject::new());
        }

        let mut heap = Heap { objects, loc: None };
        builtin::init(&mut heap).expect("failed to initialize builtin objects");
        heap
    }

    pub fn get(&self, objref: JSRef) -> &JSObject {
        self.objects
            .get(objref.0)
            .unwrap_or_else(|| panic!("{:?} is invalid", objref))
    }

    pub fn get_mut(&mut self, objref: JSRef) -> &mut JSObject {
        self.objects
            .get_mut(objref.0)
            .unwrap_or_else(|| panic!("{:?} is invalid", objref))
    }

    pub fn get_index(&self, index: usize) -> Option<&JSObject> {
        self.objects.get(index)
    }

    pub fn alloc(&mut self, object: JSObject) -> JSRef {
        let ind = self.objects.len();
        self.objects.push(object);
        JSRef(ind)
    }

    pub fn alloc_func(&mut self, func: HostFn) -> JSRef {
        let func_obj = JSObject::from_func(func);
        self.alloc(func_obj)
    }

    pub fn init_class(&mut self, proto: JSRef, class: &HostClass) -> JSResult<()> {
        let mut proto_object = JSObject::new();

        for &(name, func) in class.methods.iter() {
            let name = JSString::from(name);
            let func = self.alloc_func(func);
            proto_object.set_hidden(name, func)?;
        }

        *self.get_mut(proto) = proto_object;

        let mut ctor_object = JSObject::from_func(class.constructor);
        ctor_object.set_system(JSString::from("prototype"), proto)?;

        for &(name, func) in class.static_methods.iter() {
            let name = JSString::from(name);
            let func = self.alloc_func(func);
            ctor_object.set_hidden(name, func)?;
        }

        let ctor_ref = self.alloc(ctor_object);
        self.get_mut(proto)
            .set_hidden(JSString::from("constructor"), ctor_ref)?;

        self.get_mut(Heap::GLOBAL)
            .set_hidden(JSString::from(class.name), ctor_ref)?;
        Ok(())
    }

    /*
    /// this is a hack to distingiush e.g. `new Boolean(true)` and `Boolean(true)` calls.
    #[allow(clippy::match_like_matches_macro)]
    pub(crate) fn smells_fresh(&self, objref: JSRef) -> bool {
        match objref {
            Heap::NULL => false,
            _ => match self.get(objref) {
                JSObject {
                    value: ObjectValue::None,
                    properties,
                    ..
                } if properties.is_empty() => true,
                _ => false,
            },
        }
    }
    */

    /// Deserializes JSON into objects on the heap
    pub fn object_from_json(&mut self, json: &JSON) -> JSValue {
        if let Some(jobj) = json.as_object() {
            let mut object = JSObject::new();
            for (key, jval) in jobj.iter() {
                let key = JSString::from(key.clone());
                let value = self.object_from_json(jval);
                object.set_property(key, value).unwrap();
            }
            JSValue::Ref(self.alloc(object))
        } else if let Some(jarray) = json.as_array() {
            let storage = (jarray.iter())
                .map(|jval| self.object_from_json(jval))
                .collect();
            let object = JSObject::from_array(storage);
            JSValue::Ref(self.alloc(object))
        } else {
            JSValue::try_from(json).expect("primitive JSON") // not Object/Array, must be primitive
        }
    }

    /// Find out what `this` currently is.
    pub fn interpret_this(&mut self) -> JSRef {
        self.lookup_var(Self::SCOPE_THIS)
            .expect("no this in the current scope")
            .to_ref(self)
            .expect("this must be JSValue::Ref")
    }

    pub(crate) fn is_scope(&self, objref: JSRef) -> bool {
        objref == Self::GLOBAL || self.get(objref).get_own_value(Heap::SAVED_SCOPE).is_some()
    }

    /// If there's a local scope, return a `JSRef` to it.
    pub(crate) fn local_scope(&self) -> Option<JSRef> {
        match self.get(Heap::GLOBAL).get_own_value(Heap::LOCAL_SCOPE) {
            Some(JSValue::Ref(scope_ref)) => Some(scope_ref),
            _ => None,
        }
    }

    fn scope(&self) -> &JSObject {
        let scope_ref = self.local_scope().unwrap_or(Heap::GLOBAL);
        self.get(scope_ref)
    }

    pub fn scope_mut(&mut self) -> &mut JSObject {
        let scope_ref = self.local_scope().unwrap_or(Heap::GLOBAL);
        self.get_mut(scope_ref)
    }

    pub fn declare_variable(&mut self, var: &Identifier) -> JSResult<()> {
        if self.scope().get_own_value(var.as_str()).is_none() {
            let name = var.0.clone();
            self.scope_mut().set_nonconf(name, JSValue::Undefined)?;
        }
        Ok(())
    }

    pub fn declare_binding(&mut self, binding: &Binding) -> JSResult<()> {
        let name = binding.name().clone();
        let value = if let Some(function) = binding.as_func() {
            // create a closure:
            self.evaluate(&function)?
        } else {
            JSValue::Undefined
        };
        if let Some(prop) = self.scope_mut().get_own_property(name.as_str()) {
            // It might pre-populated and nonconfigurable, like `global.NaN`.
            match prop.is_writable() {
                true => self.scope_mut().set_property(name.0, value),
                false => Ok(()),
            }
        } else {
            // It's fresh
            match binding.is_const() {
                true => self
                    .scope_mut()
                    .define_own_property(name.0, crate::object::Access::ENUM),
                false => self.scope_mut().set_nonconf(name.0, value),
            }
        }
    }

    pub fn declare(&mut self, bindings: impl Iterator<Item = Binding>) -> JSResult<()> {
        for binding in bindings {
            self.declare_binding(&binding)?;
        }
        Ok(())
    }

    pub fn lookup_var(&self, name: &str) -> Option<Interpreted> {
        if let Some(local_ref) = self.local_scope() {
            let local = self.get(local_ref);
            if local.get_own_value(name).is_some() {
                return Some(Interpreted::member(local_ref, name));
            }

            // captured scopes lookup
            let mut scope_ref = match local.get_own_value(Self::CAPTURED_SCOPE) {
                Some(JSValue::Ref(scope_ref)) => scope_ref,
                _ => Heap::NULL,
            };
            while scope_ref != Heap::NULL {
                let scope = self.get(scope_ref);
                if scope.get_own_value(name).is_some() {
                    return Some(Interpreted::member(scope_ref, name));
                }

                scope_ref = match scope.get_own_value(Self::CAPTURED_SCOPE) {
                    Some(JSValue::Ref(scope_ref)) => scope_ref,
                    _ => Heap::NULL,
                };
            }
        }

        self.get(Heap::GLOBAL)
            .get_own_value(name)
            .map(|_| Interpreted::member(Heap::GLOBAL, name))
    }

    /// Lookup a property chain starting from the current scope, e.g.
    /// ```
    /// # use sljs::{Heap, Interpreted};
    /// # let mut heap = Heap::new();
    /// assert_eq!(
    ///     heap.lookup_path(&["Array", "prototype"]).unwrap(),
    ///     Interpreted::from(Heap::ARRAY_PROTO)
    /// );
    /// ```
    pub fn lookup_path(&self, mut names: &[&str]) -> JSResult<Interpreted> {
        let mut scoperef = self.local_scope().unwrap_or(Heap::GLOBAL);
        while let Some((&name, rest)) = names.split_first() {
            names = rest;
            let nameval = self.get(scoperef).get_own_value(name).ok_or_else(|| {
                let what = Interpreted::from(scoperef);
                Exception::TypeErrorGetProperty(what, name.into())
            })?;
            scoperef = nameval.to_ref()?;
        }
        Ok(Interpreted::from(scoperef))
    }

    pub fn enter_new_scope<T, F>(
        &mut self,
        this_ref: JSRef,
        captured_scope: JSRef,
        mut action: F,
    ) -> JSResult<T>
    where
        F: FnMut(&mut Heap) -> JSResult<T>,
    {
        self.push_scope(this_ref)?;
        if captured_scope != Heap::NULL {
            let name = JSString::from(Self::CAPTURED_SCOPE); // TODO: avoid re-creating it
            self.scope_mut().set_system(name, captured_scope)?;
        }
        let result = action(self);
        self.pop_scope()?;
        result
    }

    fn push_scope(&mut self, this_ref: JSRef) -> JSResult<JSRef> {
        let old_scope_ref = self.local_scope().unwrap_or(Heap::GLOBAL);

        let mut scope_object = JSObject::new();

        scope_object.set_system(Self::SAVED_SCOPE.into(), old_scope_ref)?;
        scope_object.set_system(Self::SCOPE_THIS.into(), this_ref)?;

        let new_scope_ref = self.alloc(scope_object);
        self.get_mut(Heap::GLOBAL)
            .set_even_nonwritable(Self::LOCAL_SCOPE.into(), new_scope_ref)?;
        Ok(new_scope_ref)
    }

    fn pop_scope(&mut self) -> JSResult<()> {
        let this_scope_ref = self.local_scope().expect(".pop_scope without local scope"); // yes, panic, this interpreter is broken.
        let this_scope_object = self.get(this_scope_ref);
        let saved_scope = this_scope_object
            .get_own_value(Self::SAVED_SCOPE)
            .expect("SAVED_SCOPE");
        let saved_scope_ref = saved_scope
            .to_ref()
            .expect("saved scope is not a reference"); // yes, panic, this interpreter is broken

        let global = self.get_mut(Heap::GLOBAL);
        if saved_scope_ref == Heap::GLOBAL {
            global.delete_property(Self::LOCAL_SCOPE.into())?;
        } else {
            global.set_even_nonwritable(Self::LOCAL_SCOPE.into(), saved_scope_ref)?;
        }

        Ok(())
    }

    /// Find the location of `propname` on the prototype chain of `objref`.
    /// Return `None` or `Some(Interpreted::Member{..})` pointing to the found own property.
    pub fn lookup_protochain(&self, mut objref: JSRef, propname: &str) -> Option<Interpreted> {
        while objref != Heap::NULL {
            let object = self.get(objref);
            if object.get_own_value(propname).is_some() {
                return Some(Interpreted::member(objref, propname));
            }

            objref = object.get_proto();
        }
        None
    }

    /// A shortcut for `interpretable.evaluate(&mut heap)`.
    pub fn evaluate<T: Interpretable>(&mut self, interpretable: &T) -> JSResult<JSValue> {
        interpretable.interpret(self)?.to_value(self)
    }

    /// Given a `func_ref` to a closure or a native call and a set of arguments,
    /// executes the function. `this_ref` is bound as `this`.
    pub fn execute(&mut self, func_ref: JSRef, mut call: CallContext) -> JSResult<Interpreted> {
        if call.loc.as_ref().is_none() {
            call.loc = self.loc.clone();
        }
        let callable = self.get(func_ref);
        if let Some(hostfn) = callable.as_hostfn() {
            hostfn.call(call, self)
        } else if let Some(closure) = callable.as_closure() {
            closure.call(call, self)
        } else {
            let callee = Interpreted::member(call.this_ref, call.method_name.as_ref());
            Err(Exception::TypeErrorNotCallable(callee))
        }
    }

    pub fn throw<T>(&self, exc: Exception) -> JSResult<T> {
        // TODO: capture the stack
        //let _ = source::print_callstack(self);
        Err(exc)
    }
}