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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! [`JSObject`], its content and its properties.

use bitflags::bitflags;
use serde_json::json;

use crate::prelude::*;

use crate::ast;
use crate::function::{
    Closure,
    HostFn,
    HostFunc,
};
use crate::{
    Exception,
    Heap,
    JSNumber,
    JSRef,
    JSResult,
    JSString,
    JSValue,
    JSON,
};

/// Javascript objects.
/// A `JSObject` always has a `proto`.
/// It can have an optional `ObjectValue` (a primitive or array/function/closure).
/// It has a dictionary of `properties`.
#[derive(Debug, Clone)]
pub struct JSObject {
    proto: JSRef,
    value: ObjectValue,
    properties: HashMap<JSString, Property>, // TODO: StrKey
}

impl JSObject {
    pub fn new() -> JSObject {
        JSObject {
            proto: Heap::OBJECT_PROTO,
            value: ObjectValue::None,
            properties: HashMap::new(),
        }
    }

    /// Wrap the given native call into a Function.
    pub fn from_func(f: HostFn) -> JSObject {
        JSObject {
            proto: Heap::FUNCTION_PROTO,
            value: ObjectValue::from_func(f),
            properties: HashMap::new(),
        }
    }

    /// Wrap the given `closure` into a Function.
    pub fn from_closure(closure: Closure) -> JSObject {
        let params_count = closure.function.params.len() as f64;
        let mut function_object = JSObject {
            proto: Heap::FUNCTION_PROTO,
            value: ObjectValue::Closure(closure),
            properties: HashMap::new(),
        };
        function_object
            .set_nonconf(JSString::from("length"), Content::from(params_count))
            .unwrap();
        function_object
    }

    /// Wrap the given vector into an Array.
    pub fn from_array(values: Vec<JSValue>) -> JSObject {
        JSObject {
            proto: Heap::ARRAY_PROTO,
            value: ObjectValue::Array(JSArray { storage: values }),
            properties: HashMap::new(),
        }
    }

    /// Wrap the given bool into Boolean
    pub fn from_bool(value: bool) -> JSObject {
        JSObject {
            proto: Heap::BOOLEAN_PROTO,
            value: ObjectValue::Boolean(value),
            properties: HashMap::new(),
        }
    }

    /// Wrap the given string into String
    fn from_string(value: JSString) -> JSObject {
        let mut properties = HashMap::new();
        // TODO: String.prototype.length
        properties.insert(
            JSString::from("length"),
            Property {
                access: Access::empty(),
                content: Content::from(value.as_str().chars().count() as i64),
            },
        );
        JSObject {
            proto: Heap::STRING_PROTO,
            value: ObjectValue::String(value),
            properties,
        }
    }

    pub fn get_proto(&self) -> JSRef {
        self.proto
    }

    pub fn set_proto(&mut self, proto: JSRef) {
        self.proto = proto;
    }

    /// It's roughly `Object.valueOf(self)`
    pub fn to_primitive(&self) -> Option<JSValue> {
        use ObjectValue::*;
        match &self.value {
            Boolean(b) => Some(JSValue::Bool(*b)),
            Number(n) => Some(JSValue::Number(*n)),
            String(s) => Some(JSValue::String(s.clone())),
            _ => Option::None,
        }
    }

    /// It `self` is an Array, give its underlying storage.
    pub fn as_array(&self) -> Option<&JSArray> {
        match &self.value {
            ObjectValue::Array(array) => Some(array),
            _ => None,
        }
    }

    /// If `self` is an Array, give its underlying storage mutably.
    pub fn as_array_mut(&mut self) -> Option<&mut JSArray> {
        match &mut self.value {
            ObjectValue::Array(array) => Some(array),
            _ => None,
        }
    }

    /// If `self` is a String, get it primitive value
    pub fn as_str(&self) -> Option<&str> {
        match &self.value {
            ObjectValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    pub fn is_callable(&self) -> bool {
        #[allow(clippy::match_like_matches_macro)]
        match self.value {
            ObjectValue::HostFn(_) | ObjectValue::Closure(_) => true,
            _ => false,
        }
    }

    pub fn as_hostfn(&self) -> Option<HostFunc> {
        match &self.value {
            ObjectValue::HostFn(hostfn) => Some(hostfn.clone()),
            _ => None,
        }
    }

    pub fn as_closure(&self) -> Option<Closure> {
        match &self.value {
            ObjectValue::Closure(closure) => Some(closure.clone()),
            _ => None,
        }
    }

    pub fn get_own_property(&self, name: &str) -> Option<Property> {
        // indexing
        if let Ok(index) = usize::from_str(name) {
            match &self.value {
                ObjectValue::Array(array) => {
                    if let Some(value) = array.storage.get(index) {
                        return Some(Property {
                            content: Content::from(value.clone()),
                            access: Access::all(), // TODO: recheck
                        });
                    }
                }
                ObjectValue::String(s) => {
                    // TODO: optimizie nth()'s sequential access
                    if let Some(c) = s.chars().nth(index) {
                        return Some(Property {
                            content: Content::from(c.to_string()),
                            access: Access::ENUM,
                        });
                    }
                }
                _ => (),
            }
        } else if name == "length" {
            // TODO: make this hack a regular getter once getters are ready
            let len = match &self.value {
                ObjectValue::Array(array) => Some(array.storage.len() as i64),
                ObjectValue::String(s) => Some(s.len() as i64),
                ObjectValue::Closure(closure) => Some(closure.function.params.len() as i64),
                _ => None,
            };
            if let Some(len) = len {
                return Some(Property {
                    content: Content::from(len),
                    access: Access::empty(), // TODO: recheck
                });
            }
        }

        self.properties.get(name).cloned()
    }

    /// Tries to get JSValue of the own property `name`.
    /// This might call getters of the property.
    pub fn get_own_value(&self, name: &str) -> Option<JSValue> {
        self.get_own_property(name).and_then(Property::into_value)
    }

    /// Check own and all inherited properties for `name` and returns the first found value.
    /// ES5: \[\[Get\]\], None corresponds to `undefined`
    pub fn lookup_value(&self, name: &str, heap: &Heap) -> Option<JSValue> {
        if let Some(value) = self.get_own_value(name) {
            return Some(value);
        }
        for protoref in self.protochain(heap) {
            if let Some(value) = heap.get(protoref).get_own_value(name) {
                return Some(value);
            }
        }
        None
    }

    pub fn protochain<'a>(&self, heap: &'a Heap) -> ProtoChainIter<'a> {
        ProtoChainIter {
            heap,
            protoref: self.proto,
        }
    }

    pub fn get_own_keys(&self) -> Vec<JSString> {
        let mut keys = Vec::new();
        if let Some(array) = self.as_array() {
            let indices = 0..array.storage.len();
            keys.extend(indices.map(|i| i.to_string().into()));
        }
        keys.extend(self.properties.keys().cloned());
        keys
    }

    pub fn get_own_enumerable_keys(&self) -> Vec<JSString> {
        let mut keys = Vec::new();
        if let Some(array) = self.as_array() {
            let indices = 0..array.storage.len();
            keys.extend(indices.map(|i| i.to_string().into()));
        }
        // TODO: strings iteration
        keys.extend(self.properties.iter().filter_map(|(k, v)| {
            if v.is_enumerable() {
                Some(k.clone())
            } else {
                None
            }
        }));
        keys
    }

    fn set_maybe_nonwritable(
        &mut self,
        name: JSString,
        content: Content,
        access: Access,
        even_nonwritable: bool,
    ) -> JSResult<()> {
        if let Ok(index) = usize::from_str(name.as_str()) {
            if let Some(array) = self.as_array_mut() {
                // TODO: a[100500] will be interesting.
                while array.storage.len() <= index {
                    array.storage.push(JSValue::Undefined);
                }
                let value = content.to_value()?;
                array.storage[index] = value;
                return Ok(());
            }
        }

        match self.properties.get_mut(name.as_str()) {
            Some(property) => {
                if property.access != access && !property.is_configurable() {
                    let what = Interpreted::from("???"); // TODO
                    return Err(Exception::TypeErrorNotConfigurable(what, name));
                }

                if !(even_nonwritable || property.is_writable()) {
                    let what = Interpreted::from("???"); // TODO
                    return Err(Exception::TypeErrorSetReadonly(what, name));
                }

                property.access = access;
                property.content = content;
            }
            None => {
                let prop = Property { content, access };
                self.properties.insert(name, prop);
            }
        }
        Ok(())
    }

    pub fn define_own_property(&mut self, name: JSString, access: Access) -> JSResult<()> {
        let content = Content::from(JSValue::Undefined);
        self.set_maybe_nonwritable(name, content, access, true)
    }

    pub fn delete_property(&mut self, name: JSString) -> JSResult<()> {
        let configurable = match self.properties.get(name.as_str()) {
            Some(p) => p.is_configurable(),
            None => return Ok(()),
        };
        if configurable {
            self.properties.remove(name.as_str());
            Ok(())
        } else {
            Err(Exception::TypeErrorNotConfigurable(
                Interpreted::VOID,
                name.clone(),
            ))
        }
    }

    /// - if own property `name` does not exist, create it with the given `content` and `access`.
    /// - if `name` is a number and `self` is an Array, assign value of `content` into the array.
    /// - if the existing own property is not configurable and the given `access` differs, fail.
    /// - if the existing own property is not writable, fail
    /// - else: replace `content` and `access` of the property.
    fn set(&mut self, name: JSString, content: Content, access: Access) -> JSResult<()> {
        self.set_maybe_nonwritable(name, content, access, false)
    }

    /// If `name` is a number and `self` is an Array, just set the array elemnt to `value`.
    /// Otherwise: if the own property `name` does not exist, create it with `Access::all()` and
    /// set to `Content::from(value)`.
    /// If the own property exists already, call `.set()` with its current access. This will fail
    /// to update non-writable properties.
    /// ES5: \[\[Put\]\] with strict error handing
    pub fn set_property<V>(&mut self, name: JSString, value: V) -> JSResult<()>
    where
        Content: From<V>,
    {
        let access = (self.properties.get(name.as_str()))
            .map(|prop| prop.access)
            .unwrap_or(Access::all());
        self.set(name, Content::from(value), access)
    }

    /// Just like `.set_property()`, but updates even non-writable properties.
    pub fn set_even_nonwritable<V>(&mut self, name: JSString, value: V) -> JSResult<()>
    where
        Content: From<V>,
    {
        let access = (self.properties.get(name.as_str()))
            .map(|prop| prop.access)
            .unwrap_or(Access::all());
        self.set_maybe_nonwritable(name, Content::from(value), access, true)
    }

    // are these shortcuts a good idea?
    /// A shortcut for `define_own_property(Access::NONE)` and assigning the value.
    pub fn set_system<V>(&mut self, name: JSString, value: V) -> JSResult<()>
    where
        Content: From<V>,
    {
        self.set(name, Content::from(value), Access::empty())
    }

    /// A shortcut for defining a non-enumerable property and setting its value.
    pub fn set_hidden<V>(&mut self, name: JSString, value: V) -> JSResult<()>
    where
        Content: From<V>,
    {
        self.set(name, Content::from(value), Access::HIDDEN)
    }

    /// A shortcut for defining a non-configurable property and setting its value.
    pub fn set_nonconf<V>(&mut self, name: JSString, value: V) -> JSResult<()>
    where
        Content: From<V>,
    {
        self.set(name, Content::from(value), Access::NONCONF)
    }

    /// A shortcut for defining a non-writable property and setting its value.
    pub fn set_readonly<V>(&mut self, name: JSString, value: V) -> JSResult<()>
    where
        Content: From<V>,
    {
        self.set(name, Content::from(value), Access::READONLY)
    }

    /// Create a `JSON` from this `JSObject`.
    pub fn to_json(&self, heap: &Heap) -> JSResult<JSON> {
        if let Some(array) = self.as_array() {
            let jvals = (array.storage.iter())
                .map(|v| v.to_json(heap))
                .collect::<JSResult<Vec<_>>>()?;
            return Ok(JSON::Array(jvals));
        }

        let mut json = json!({});
        for (key, property) in self.properties.iter() {
            if !property.is_enumerable() {
                continue;
            }

            let jvalue = property.content.to_value()?.to_json(heap)?;
            json[key.to_string()] = jvalue;
        }
        Ok(json)
    }

    /// Create a human-readable representation of contents of an Array or an Object.
    pub fn to_string(&self, heap: &mut Heap) -> JSResult<JSString> {
        fn is_valid_identifier(s: &str) -> bool {
            let is_start = |c: char| (c.is_alphabetic() || c == '_' || c == '$');

            let mut it = s.chars();
            if let Some(c) = it.next() {
                is_start(c) && it.all(|c| is_start(c) || c.is_numeric())
            } else {
                false
            }
        }

        let is_array = self.as_array().is_some();

        let mut s = String::new();
        let mut empty = true;

        if let Some(array) = self.as_array() {
            s.push('[');
            for item in array.storage.iter() {
                empty = false;
                let itemstr = item.to_string(heap)?;
                s.push_str(&itemstr);
                s.push(',');
                s.push(' ');
            }
            if !empty {
                s.pop();
                s.push(' ');
            }
        } else {
            s.push('{');
        }

        for (key, property) in self.properties.iter() {
            if !property.is_enumerable() {
                continue;
            }

            s.push(' ');
            if is_valid_identifier(key) {
                s.push_str(key);
            } else {
                let skey = JSON::from(key.as_str()).to_string();
                s.push_str(&skey);
            }
            s.push_str(": ");
            let val = property.content.to_value()?.to_string(heap)?;
            s.push_str(&val);
            s.push(',');
            empty = false;
        }
        if is_array {
            if !empty {
                s.pop();
                s.pop();
            }
            s.push(']');
        } else {
            if !empty {
                s.pop();
                s.push(' ');
            }
            s.push('}');
        }
        Ok(JSString::from(s))
    }
}

impl<S> From<S> for JSObject
where
    JSString: From<S>,
{
    fn from(s: S) -> Self {
        JSObject::from_string(JSString::from(s))
    }
}

/*
impl From<&str> for JSObject {
    fn from(s: &str) -> Self {
        JSObject::from_string(JSString::from(s))
    }
}
*/

impl Default for JSObject {
    fn default() -> Self {
        JSObject::new()
    }
}

pub struct ProtoChainIter<'a> {
    heap: &'a Heap,
    protoref: JSRef,
}

impl<'a> Iterator for ProtoChainIter<'a> {
    type Item = JSRef;

    fn next(&mut self) -> Option<Self::Item> {
        match self.protoref {
            Heap::NULL => None,
            prevref => {
                self.protoref = self.heap.get(prevref).proto;
                Some(prevref)
            }
        }
    }
}

/// `ObjectValue` is used:
/// - as the primitive value of a `Number`/`Boolean`/`String` object;
/// - as the function entry in a `Function`.
/// - as optimizied storage in an `Array`
#[derive(Debug, Clone)]
pub enum ObjectValue {
    None,

    // primitive values
    Boolean(bool),
    Number(JSNumber),
    String(JSString),

    // Function
    HostFn(HostFunc),
    Closure(Closure),

    // Array
    Array(JSArray),
}

impl ObjectValue {
    pub fn from_func(func: HostFn) -> ObjectValue {
        ObjectValue::HostFn(HostFunc::from(func))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Property {
    /// A `JSValue` or accessors
    pub content: Content,
    /// (non)writable | (non)configurable | (non)enumerable
    pub access: Access,
}

impl Property {
    pub fn to_ref(&self) -> Option<JSRef> {
        self.to_value().and_then(|v| v.to_ref().ok())
    }

    pub fn to_value(&self) -> Option<JSValue> {
        match self {
            Property {
                content: Content::Value(val),
                ..
            } => Some(val.clone()),
        }
    }

    pub fn into_value(self) -> Option<JSValue> {
        match self {
            Property {
                content: Content::Value(val),
                ..
            } => Some(val),
        }
    }

    pub fn is_enumerable(&self) -> bool {
        self.access.contains(Access::ENUM)
    }

    pub fn is_configurable(&self) -> bool {
        self.access.contains(Access::CONF)
    }

    pub fn is_writable(&self) -> bool {
        self.access.contains(Access::WRITE)
    }
}

bitflags! {
    pub struct Access: u8 {
        const ENUM = 0b001;
        const CONF = 0b010;
        const WRITE = 0b100;

        const HIDDEN = Self::CONF.bits | Self::WRITE.bits;
        const READONLY = Self::ENUM.bits | Self::CONF.bits;
        const NONCONF = Self::ENUM.bits | Self::WRITE.bits;
    }
}

impl Access {
    pub fn new(configurable: bool, enumerable: bool, writable: bool) -> Access {
        let mut access = Access::empty();
        if configurable {
            access |= Access::CONF;
        }
        if enumerable {
            access |= Access::ENUM;
        }
        if writable {
            access |= Access::WRITE;
        }
        access
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Content {
    Value(JSValue),
    /*
    Accessor{
        get: Option<JSRef>,
        set: Option<JSRef>,
    },
    */
}

impl Content {
    /// This might call getters of the property.
    pub fn to_value(&self) -> JSResult<JSValue> {
        match self {
            Self::Value(value) => Ok(value.clone()),
        }
    }
}

impl<T> From<T> for Content
where
    JSValue: From<T>,
{
    fn from(x: T) -> Content {
        Content::Value(JSValue::from(x))
    }
}

/// The underlying storage of an Array object.
#[derive(Clone, Debug)]
pub struct JSArray {
    pub storage: Vec<JSValue>,
}

impl JSArray {}

#[derive(Debug, Clone, PartialEq)]
pub enum Interpreted {
    /// An object member; might not exist yet.
    Member { of: JSRef, name: JSString },

    /// A value
    Value(JSValue),
}

impl Interpreted {
    pub const VOID: Interpreted = Interpreted::Value(JSValue::Undefined);
    pub const NAN: Interpreted = Interpreted::Value(JSValue::Number(f64::NAN));

    /// A convenience wrapper for Interpreted::Member{} construction
    pub fn member(of: JSRef, name: &str) -> Interpreted {
        Interpreted::Member {
            of,
            name: name.into(),
        }
    }

    /// If Interpreted::Value, unwrap;
    /// if Interpreted::Member{of, name}, [`JSObject::lookup_value`] of `name` in `of`.
    pub fn to_value(&self, heap: &Heap) -> JSResult<JSValue> {
        match self {
            Interpreted::Value(value) => Ok(value.clone()),
            Interpreted::Member { of, name } => {
                if let Some(value) = heap.get(*of).lookup_value(name, heap) {
                    Ok(value)
                } else if heap.is_scope(*of) {
                    let ident = ast::Identifier(name.clone());
                    Err(Exception::ReferenceNotFound(ident))
                } else {
                    Ok(JSValue::Undefined)
                }
            }
        }
    }

    pub fn to_ref(&self, heap: &Heap) -> JSResult<JSRef> {
        match self {
            Interpreted::Value(JSValue::Ref(r)) => Ok(*r),
            Interpreted::Member { of, name } => match heap.get(*of).lookup_value(name, heap) {
                Some(JSValue::Ref(r)) => Ok(r),
                None if heap.is_scope(*of) => {
                    let ident = ast::Identifier(name.clone());
                    Err(Exception::ReferenceNotFound(ident))
                }
                _ => Err(Exception::TypeErrorGetProperty(self.clone(), name.clone())),
            },
            _ => Err(Exception::ReferenceNotAnObject(self.clone())),
        }
    }

    pub fn put_value(&self, value: JSValue, heap: &mut Heap) -> JSResult<()> {
        match self {
            Interpreted::Member { of, name } => heap.get_mut(*of).set_property(name.clone(), value),
            _ => Err(Exception::TypeErrorCannotAssign(self.clone())),
        }
    }

    /// Resolve self to: a callable JSRef, `this` JSRef and the method name.
    pub fn resolve_call(&self, heap: &Heap) -> JSResult<(JSRef, JSRef, JSString)> {
        match self {
            Interpreted::Member { of: this_ref, name } => {
                let of = match heap.lookup_protochain(*this_ref, name) {
                    Some(Interpreted::Member { of, .. }) => of,
                    Some(_) => unreachable!(),
                    None => return Err(Exception::TypeErrorNotCallable(self.clone())),
                };
                let func_value = (heap.get(of).get_own_value(name)).ok_or_else(|| {
                    Exception::TypeErrorNotCallable(Interpreted::member(of, name))
                })?;
                let func_ref = (func_value.to_ref())
                    .map_err(|_| Exception::TypeErrorNotCallable(Interpreted::member(of, name)))?;
                Ok((func_ref, *this_ref, name.clone()))
            }
            Interpreted::Value(JSValue::Ref(func_ref)) => {
                let this_ref = Heap::GLOBAL; // TODO: figure out what is this
                Ok((*func_ref, this_ref, "<anonymous>".into()))
            }
            _ => Err(Exception::TypeErrorNotCallable(self.clone())),
        }
    }

    /// Corresponds to Javascript `delete` operator and all its weirdness.
    /// `Ok`/`Err` correspond to `true`/`false` from `delete`.
    /// <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete>
    pub fn delete(&self, heap: &mut Heap) -> JSResult<()> {
        match self {
            Interpreted::Member { of, name } => heap.get_mut(*of).delete_property(name.clone()),
            _ => Ok(()),
        }
    }
}

impl<T> From<T> for Interpreted
where
    JSValue: From<T>,
{
    fn from(value: T) -> Interpreted {
        Interpreted::Value(JSValue::from(value))
    }
}

/// A description of a JavaScript prototype+constructor with host methods.
pub struct HostClass {
    pub name: &'static str,
    pub constructor: HostFn,
    pub methods: &'static [(&'static str, HostFn)],
    pub static_methods: &'static [(&'static str, HostFn)],
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn own_enumerable_keys() {
        let mut obj = JSObject::new();
        obj.set_property("one".into(), 1).unwrap();
        obj.set_property("two".into(), 2).unwrap();
        obj.set_property("three".into(), 3).unwrap();
        obj.set_hidden("invisible".into(), "property").unwrap();

        let mut enum_keys = obj.get_own_enumerable_keys();
        enum_keys.sort();
        assert_eq!(&enum_keys, &["one", "three", "two"].map(JSString::from));
    }
}