nova_vm 1.0.0

Nova Virtual Machine
Documentation
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

mod data;

pub(crate) use data::*;

use std::ops::ControlFlow;

use crate::{
    ecmascript::{
        AbstractModule, AbstractModuleMethods, AbstractModuleSlots, Agent, BUILTIN_STRING_MEMORY,
        ExceptionType, InternalMethods, InternalSlots, JsResult, Object, OrdinaryObject,
        PropertyDescriptor, PropertyKey, ResolvedBinding, SetResult, String, TryError,
        TryGetResult, TryHasResult, TryResult, Value, get_module_namespace, object_handle,
        same_value, throw_uninitialized_binding,
    },
    engine::{Bindable, GcScope, NoGcScope, Scopable},
    heap::{
        ArenaAccess, BaseIndex, CompactionLists, CreateHeapData, HeapMarkAndSweep,
        HeapSweepWeakReference, WellKnownSymbols, WorkQueues, arena_vec_access,
    },
};

use super::ordinary::{
    ObjectShape, {PropertyLookupCache, PropertyOffset},
};

/// ### [10.4.6 Module Namespace Exotic Objects](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects)
///
/// A module namespace exotic object is an exotic object that exposes the
/// bindings exported from an ECMAScript _Module_ (See 16.2.3). There is a
/// one-to-one correspondence between the String-keyed own properties of a
/// module namespace exotic object and the binding names exported by the Module.
/// The exported bindings include any bindings that are indirectly exported
/// using **`export *`** export items. Each String-valued own property key is
/// the StringValue of the corresponding exported binding name. These are the
/// only String-keyed properties of a module namespace exotic object. Each such
/// property has the attributes `{ [[Writable]]: true, [[Enumerable]]: true,
/// [[Configurable]]: false }`. Module namespace exotic objects are not
/// extensible.
///
/// #### Example
///
/// ```javascript
/// import * as m1 from "";
/// const m2 = await import("");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Module<'a>(BaseIndex<'a, ModuleHeapData<'static>>);
object_handle!(Module);
arena_vec_access!(Module, 'a, ModuleHeapData, modules);

impl<'a> InternalSlots<'a> for Module<'a> {
    #[inline(always)]
    fn get_backing_object(self, _agent: &Agent) -> Option<OrdinaryObject<'static>> {
        None
    }

    #[inline(always)]
    fn set_backing_object(self, _agent: &mut Agent, _backing_object: OrdinaryObject<'static>) {
        unreachable!()
    }

    #[inline(always)]
    fn create_backing_object(self, _: &mut Agent) -> OrdinaryObject<'static> {
        unreachable!();
    }

    #[inline(always)]
    fn internal_extensible(self, _agent: &Agent) -> bool {
        unreachable!()
    }

    #[inline(always)]
    fn internal_set_extensible(self, _agent: &mut Agent, _value: bool) {
        unreachable!()
    }

    #[inline(always)]
    fn internal_prototype(self, _agent: &Agent) -> Option<Object<'static>> {
        None
    }

    #[inline(always)]
    fn internal_set_prototype(self, _agent: &mut Agent, _prototype: Option<Object>) {
        unreachable!()
    }

    #[inline(always)]
    fn object_shape(self, _: &mut Agent) -> ObjectShape<'static> {
        unreachable!()
    }
}

impl<'a> InternalMethods<'a> for Module<'a> {
    /// ### [10.4.6.1 \[\[GetPrototypeOf\]\] ( )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-getprototypeof)
    fn try_get_prototype_of<'gc>(
        self,
        _: &mut Agent,
        _: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, Option<Object<'gc>>> {
        TryResult::Continue(None)
    }

    /// ### [10.4.6.2 \[\[SetPrototypeOf\]\] ( V )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-setprototypeof-v)
    fn try_set_prototype_of<'gc>(
        self,
        _: &mut Agent,
        prototype: Option<Object>,
        _: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, bool> {
        // This is what it all comes down to in the end.
        TryResult::Continue(prototype.is_none())
    }

    /// ### [10.4.6.3 \[\[IsExtensible\]\] ( )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-isextensible)
    fn try_is_extensible<'gc>(self, _: &mut Agent, _: NoGcScope<'gc, '_>) -> TryResult<'gc, bool> {
        TryResult::Continue(false)
    }

    /// ### [10.4.6.4 \[\[PreventExtensions\]\] ( )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-preventextensions)
    fn try_prevent_extensions<'gc>(
        self,
        _: &mut Agent,
        _: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, bool> {
        TryResult::Continue(true)
    }

    fn try_get_own_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        _cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, Option<PropertyDescriptor<'gc>>> {
        match property_key {
            PropertyKey::Symbol(symbol) => {
                // 1. If P is a Symbol, return OrdinaryGetOwnProperty(O, P).
                if symbol == WellKnownSymbols::ToStringTag.into() {
                    TryResult::Continue(Some(PropertyDescriptor {
                        value: Some(BUILTIN_STRING_MEMORY.Module.into()),
                        writable: Some(false),
                        get: None,
                        set: None,
                        enumerable: Some(false),
                        configurable: Some(false),
                    }))
                } else {
                    TryResult::Continue(None)
                }
            }
            PropertyKey::PrivateName(_) => unreachable!(),
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                let key = match property_key {
                    PropertyKey::SmallString(data) => String::SmallString(data),
                    PropertyKey::String(data) => String::String(data),
                    PropertyKey::Integer(data) => {
                        String::from_string(agent, format!("{}", data.into_i64()), gc)
                    }
                    PropertyKey::Symbol(_) | PropertyKey::PrivateName(_) => unreachable!(),
                };
                // 2. Let exports be O.[[Exports]].
                let exports: &[String] = &self.get(agent).exports;
                let exports_contains_p = exports.contains(&key);
                // 3. If exports does not contain P, return undefined.
                if !exports_contains_p {
                    TryResult::Continue(None)
                } else {
                    // 4. Let value be ? O.[[Get]](P, O).
                    let value = match self.try_get(agent, property_key, self.into(), None, gc) {
                        ControlFlow::Continue(TryGetResult::Unset) => Value::Undefined,
                        ControlFlow::Continue(TryGetResult::Value(v)) => v,
                        _ => return TryError::GcError.into(),
                    };
                    // 5. Return PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }.
                    TryResult::Continue(Some(PropertyDescriptor {
                        value: Some(value),
                        writable: Some(true),
                        get: None,
                        set: None,
                        enumerable: Some(true),
                        configurable: Some(false),
                    }))
                }
            }
        }
    }

    /// 10.4.6.5 \[\[GetOwnProperty\]\] ( P )
    fn internal_get_own_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, Option<PropertyDescriptor<'gc>>> {
        let property_key = property_key.bind(gc.nogc());
        match property_key {
            PropertyKey::Symbol(symbol) => {
                // 1. If P is a Symbol, return OrdinaryGetOwnProperty(O, P).
                if symbol == WellKnownSymbols::ToStringTag.into() {
                    Ok(Some(PropertyDescriptor {
                        value: Some(BUILTIN_STRING_MEMORY.Module.into()),
                        writable: Some(false),
                        get: None,
                        set: None,
                        enumerable: Some(false),
                        configurable: Some(false),
                    }))
                } else {
                    Ok(None)
                }
            }
            PropertyKey::PrivateName(_) => unreachable!(),
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                let key = match property_key {
                    PropertyKey::SmallString(data) => String::SmallString(data),
                    PropertyKey::String(data) => String::String(data),
                    PropertyKey::Integer(data) => {
                        String::from_string(agent, format!("{}", data.into_i64()), gc.nogc())
                    }
                    PropertyKey::Symbol(_) | PropertyKey::PrivateName(_) => unreachable!(),
                };
                // 2. Let exports be O.[[Exports]].
                let exports: &[String] = &self.get(agent).exports;
                let exports_contains_p = exports.contains(&key);
                // 3. If exports does not contain P, return undefined.
                if !exports_contains_p {
                    Ok(None)
                } else {
                    // 4. Let value be ? O.[[Get]](P, O).
                    let value = self.internal_get(agent, property_key.unbind(), self.into(), gc)?;
                    // 5. Return PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }.
                    Ok(Some(PropertyDescriptor {
                        value: Some(value.unbind()),
                        writable: Some(true),
                        get: None,
                        set: None,
                        enumerable: Some(true),
                        configurable: Some(false),
                    }))
                }
            }
        }
    }

    /// ### [10.4.6.6 \[\[DefineOwnProperty\]\] ( P, Desc )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-defineownproperty-p-desc)
    fn try_define_own_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        property_descriptor: PropertyDescriptor,
        cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, bool> {
        match property_key {
            PropertyKey::Symbol(symbol) => {
                // 1. If P is a Symbol, return ! OrdinaryDefineOwnProperty(O, P, Desc).
                if symbol == WellKnownSymbols::ToStringTag.into() {
                    // Note: it's always okay for a field to not exist on the
                    // descriptor. It just means that the defineOwnProperty
                    // isn't trying to change it. Hence the map_or checks below.
                    TryResult::Continue(
                        property_descriptor
                            .value
                            .is_none_or(|v| v == BUILTIN_STRING_MEMORY.Module.into())
                            && property_descriptor.writable.is_none_or(|v| !v)
                            && property_descriptor.get.is_none()
                            && property_descriptor.set.is_none()
                            && property_descriptor.enumerable.is_none_or(|v| !v)
                            && property_descriptor.configurable.is_none_or(|v| !v),
                    )
                } else {
                    TryResult::Continue(false)
                }
            }
            PropertyKey::PrivateName(_) => unreachable!(),
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                // 2. Let current be ? O.[[GetOwnProperty]](P).
                let current = self.try_get_own_property(agent, property_key, cache, gc)?;
                // 3. If current is undefined, return false.
                let Some(current) = current else {
                    return TryResult::Continue(false);
                };
                // 4. If Desc has a [[Configurable]] field and Desc.[[Configurable]] is true, return false.
                if property_descriptor.configurable == Some(true) {
                    return TryResult::Continue(false);
                }
                // 5. If Desc has an [[Enumerable]] field and Desc.[[Enumerable]] is false, return false.
                if property_descriptor.enumerable == Some(false) {
                    return TryResult::Continue(false);
                }
                // 6. If IsAccessorDescriptor(Desc) is true, return false.
                if property_descriptor.is_accessor_descriptor() {
                    return TryResult::Continue(false);
                }
                // 7. If Desc has a [[Writable]] field and Desc.[[Writable]] is false, return false.
                if property_descriptor.writable == Some(false) {
                    return TryResult::Continue(false);
                }
                // 8. If Desc has a [[Value]] field, return SameValue(Desc.[[Value]], current.[[Value]]).
                if let Some(value) = property_descriptor.value {
                    TryResult::Continue(same_value(agent, value, current.value.unwrap()))
                } else {
                    // 9. Return true.
                    TryResult::Continue(true)
                }
            }
        }
    }

    /// ### [10.4.6.6 \[\[DefineOwnProperty\]\] ( P, Desc )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-defineownproperty-p-desc)
    fn internal_define_own_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        property_descriptor: PropertyDescriptor,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, bool> {
        let o = self.bind(gc.nogc());
        let property_key = property_key.bind(gc.nogc());
        let property_descriptor = property_descriptor.bind(gc.nogc());
        match property_key {
            PropertyKey::Symbol(symbol) => {
                // 1. If P is a Symbol, return ! OrdinaryDefineOwnProperty(O, P, Desc).
                if symbol == WellKnownSymbols::ToStringTag.into() {
                    // Note: it's always okay for a field to not exist on the
                    // descriptor. It just means that the defineOwnProperty
                    // isn't trying to change it. Hence the is_none_or usage
                    // below.
                    Ok(property_descriptor
                        .value
                        .is_none_or(|v| v == BUILTIN_STRING_MEMORY.Module.into())
                        && property_descriptor.writable.is_none_or(|v| !v)
                        && property_descriptor.get.is_none()
                        && property_descriptor.set.is_none()
                        && property_descriptor.enumerable.is_none_or(|v| !v)
                        && property_descriptor.configurable.is_none_or(|v| !v))
                } else {
                    Ok(false)
                }
            }
            PropertyKey::PrivateName(_) => unreachable!(),
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                // 2. Let current be ? O.[[GetOwnProperty]](P).
                let is_accessor_descriptor = property_descriptor.is_accessor_descriptor();
                let PropertyDescriptor {
                    value,
                    writable,
                    enumerable,
                    configurable,
                    ..
                } = property_descriptor;
                let value = value.map(|v| v.scope(agent, gc.nogc()));
                let current =
                    o.unbind()
                        .internal_get_own_property(agent, property_key.unbind(), gc)?;
                // 3. If current is undefined, return false.
                let Some(current) = current else {
                    return Ok(false);
                };
                // 4. If Desc has a [[Configurable]] field and Desc.[[Configurable]] is true, return false.
                if configurable == Some(true) {
                    return Ok(false);
                }
                // 5. If Desc has an [[Enumerable]] field and Desc.[[Enumerable]] is false, return false.
                if enumerable == Some(false) {
                    return Ok(false);
                }
                // 6. If IsAccessorDescriptor(Desc) is true, return false.
                if is_accessor_descriptor {
                    return Ok(false);
                }
                // 7. If Desc has a [[Writable]] field and Desc.[[Writable]] is false, return false.
                if writable == Some(false) {
                    return Ok(false);
                }
                // 8. If Desc has a [[Value]] field, return SameValue(Desc.[[Value]], current.[[Value]]).
                if let Some(value) = value {
                    Ok(same_value(
                        agent,
                        value.get(agent),
                        current.value.unwrap_or(Value::Undefined),
                    ))
                } else {
                    // 9. Return true.
                    Ok(true)
                }
            }
        }
    }

    /// ### [10.4.6.7 \[\[HasProperty\]\] ( P )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-hasproperty-p)
    fn try_has_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        _cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, TryHasResult<'gc>> {
        match property_key {
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                let p = match property_key {
                    PropertyKey::String(data) => String::String(data),
                    PropertyKey::SmallString(data) => String::SmallString(data),
                    PropertyKey::Integer(_data) => todo!(),
                    _ => unreachable!(),
                };
                // 2. Let exports be O.[[Exports]].
                let exports: &[String] = &self.get(agent).exports;
                // 3. If exports contains P, return true.
                if exports.contains(&p) {
                    TryHasResult::Custom(1, self.bind(gc).into()).into()
                } else {
                    // 4. Return false.
                    TryHasResult::Unset.into()
                }
            }
            PropertyKey::Symbol(symbol) => {
                // 1. If P is a Symbol, return ! OrdinaryHasProperty(O, P).
                if symbol == WellKnownSymbols::ToStringTag.into() {
                    TryHasResult::Custom(0, self.bind(gc).into()).into()
                } else {
                    TryHasResult::Unset.into()
                }
            }
            PropertyKey::PrivateName(_) => unreachable!(),
        }
    }

    fn internal_has_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, bool> {
        Ok(!matches!(
            self.try_has_property(agent, property_key, None, gc.into_nogc()),
            ControlFlow::Continue(TryHasResult::Unset)
        ))
    }

    /// ### [10.4.6.8 \[\[Get\]\] ( P, Receiver )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-get-p-receiver)
    fn try_get<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        _receiver: Value,
        _cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, TryGetResult<'gc>> {
        // NOTE: ResolveExport is side-effect free. Each time this operation
        // is called with a specific exportName, resolveSet pair as arguments
        // it must return the same result. An implementation might choose to
        // pre-compute or cache the ResolveExport results for the [[Exports]]
        // of each module namespace exotic object.

        match property_key {
            // 1. If P is a Symbol, then
            PropertyKey::Symbol(symbol) => {
                // a. Return ! OrdinaryGet(O, P, Receiver).
                if symbol == WellKnownSymbols::ToStringTag.into() {
                    TryGetResult::Value(BUILTIN_STRING_MEMORY.Module.into()).into()
                } else {
                    TryGetResult::Unset.into()
                }
            }
            PropertyKey::PrivateName(_) => unreachable!(),
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                // 2. Let exports be O.[[Exports]].
                let exports: &[String] = &self.get(agent).exports;
                let key = match property_key {
                    PropertyKey::SmallString(data) => String::SmallString(data),
                    PropertyKey::String(data) => String::String(data),
                    PropertyKey::Integer(_) => todo!(),
                    _ => unreachable!(),
                };
                let exports_contains_p = exports.contains(&key);
                // 3. If exports does not contain P, return undefined.
                if !exports_contains_p {
                    TryGetResult::Unset.into()
                } else {
                    // 4. Let m be O.[[Module]].
                    let m = &self.get(agent).module;
                    // 5. Let binding be m.ResolveExport(P).
                    let binding = m.resolve_export(agent, key, &mut vec![], gc);
                    // 6. Assert: binding is a ResolvedBinding Record.
                    let Some(ResolvedBinding::Resolved {
                        // 7. Let targetModule be binding.[[Module]].
                        // 8. Assert: targetModule is not undefined.
                        module: target_module,
                        binding_name,
                    }) = binding
                    else {
                        unreachable!();
                    };
                    // 9. If binding.[[BindingName]] is NAMESPACE, then
                    let Some(binding_name) = binding_name else {
                        // a. Return GetModuleNamespace(targetModule).
                        return TryGetResult::Value(
                            get_module_namespace(agent, target_module.unbind(), gc).into(),
                        )
                        .into();
                    };
                    // 10. Let targetEnv be targetModule.[[Environment]].
                    let target_env = target_module.environment(agent, gc);
                    // 11. If targetEnv is EMPTY, throw a ReferenceError exception.
                    let Some(target_env) = target_env else {
                        return agent
                            .throw_exception_with_static_message(
                                ExceptionType::ReferenceError,
                                "Attempted to access unlinked module's environment",
                                gc,
                            )
                            .into();
                    };
                    // 12. Return ? targetEnv.GetBindingValue(binding.[[BindingName]], true).
                    if let Some(value) = target_env.get_binding_value(agent, binding_name, true, gc)
                    {
                        TryGetResult::Value(value).into()
                    } else {
                        throw_uninitialized_binding(agent, binding_name, gc).into()
                    }
                }
            }
        }
    }

    /// ### [10.4.6.8 \[\[Get\]\] ( P, Receiver )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-get-p-receiver)
    fn internal_get<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        _receiver: Value,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, Value<'gc>> {
        let gc = gc.into_nogc();
        let property_key = property_key.bind(gc);

        // NOTE: ResolveExport is side-effect free. Each time this operation
        // is called with a specific exportName, resolveSet pair as arguments
        // it must return the same result. An implementation might choose to
        // pre-compute or cache the ResolveExport results for the [[Exports]]
        // of each module namespace exotic object.

        match property_key {
            // 1. If P is a Symbol, then
            PropertyKey::Symbol(symbol) => {
                // a. Return ! OrdinaryGet(O, P, Receiver).
                if symbol == WellKnownSymbols::ToStringTag.into() {
                    Ok(BUILTIN_STRING_MEMORY.Module.into())
                } else {
                    Ok(Value::Undefined)
                }
            }
            PropertyKey::PrivateName(_) => unreachable!(),
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                // 2. Let exports be O.[[Exports]].
                let exports: &[String] = &self.get(agent).exports;
                let key = match property_key {
                    PropertyKey::SmallString(data) => String::SmallString(data),
                    PropertyKey::String(data) => String::String(data),
                    PropertyKey::Integer(_) => todo!(),
                    _ => unreachable!(),
                };
                let exports_contains_p = exports.contains(&key);
                // 3. If exports does not contain P,
                if !exports_contains_p {
                    // return undefined.
                    Ok(Value::Undefined)
                } else {
                    // 4. Let m be O.[[Module]].
                    let m = &self.get(agent).module;
                    // 5. Let binding be m.ResolveExport(P).
                    let binding = m.resolve_export(agent, key, &mut vec![], gc);
                    // 6. Assert: binding is a ResolvedBinding Record.
                    let Some(ResolvedBinding::Resolved {
                        // 7. Let targetModule be binding.[[Module]].
                        // 8. Assert: targetModule is not undefined.
                        module: target_module,
                        binding_name,
                    }) = binding
                    else {
                        unreachable!();
                    };
                    // 9. If binding.[[BindingName]] is NAMESPACE, then
                    let Some(binding_name) = binding_name else {
                        // a. Return GetModuleNamespace(targetModule).
                        return Ok(get_module_namespace(agent, target_module.unbind(), gc).into());
                    };
                    // 10. Let targetEnv be targetModule.[[Environment]].
                    let target_env = target_module.environment(agent, gc);
                    // 11. If targetEnv is EMPTY, throw a ReferenceError exception.
                    let Some(target_env) = target_env else {
                        return Err(agent.throw_exception(
                            ExceptionType::ReferenceError,
                            format!(
                                "Could not resolve module '{}'.",
                                key.to_string_lossy_(agent)
                            ),
                            gc,
                        ));
                    };
                    // 12. Return ? targetEnv.GetBindingValue(binding.[[BindingName]], true).
                    if let Some(value) = target_env.get_binding_value(agent, binding_name, true, gc)
                    {
                        Ok(value)
                    } else {
                        Err(throw_uninitialized_binding(agent, binding_name, gc))
                    }
                }
            }
        }
    }

    /// ### [10.4.6.9 \[\[Set\]\] ( P, V, Receiver )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-set-p-v-receiver)
    fn try_set<'gc>(
        self,
        _: &mut Agent,
        _: PropertyKey,
        _: Value,
        _: Value,
        _: Option<PropertyLookupCache>,
        _: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, SetResult<'gc>> {
        SetResult::Unwritable.into()
    }

    fn internal_set<'gc>(
        self,
        _: &mut Agent,
        _: PropertyKey,
        _: Value,
        _: Value,
        _: GcScope<'gc, '_>,
    ) -> JsResult<'gc, bool> {
        Ok(false)
    }

    /// ### [10.4.6.10 \[\[Delete\]\] ( P )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-delete-p)
    fn try_delete<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        _: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, bool> {
        match property_key {
            PropertyKey::Symbol(symbol) => {
                // 1. If P is a Symbol, then
                // a. Return ! OrdinaryDelete(O, P).
                TryResult::Continue(symbol != WellKnownSymbols::ToStringTag.into())
            }
            PropertyKey::PrivateName(_) => {
                unreachable!()
            }
            PropertyKey::Integer(_) | PropertyKey::SmallString(_) | PropertyKey::String(_) => {
                let p = match property_key {
                    PropertyKey::String(data) => String::String(data),
                    PropertyKey::SmallString(data) => String::SmallString(data),
                    PropertyKey::Integer(_) => todo!(),
                    _ => unreachable!(),
                };
                // 2. Let exports be O.[[Exports]].
                let exports = &self.get(agent).exports;
                // 3. If exports contains P,
                if exports.contains(&p) {
                    // return false.
                    TryResult::Continue(false)
                } else {
                    // 4. Return true.
                    TryResult::Continue(true)
                }
            }
        }
    }

    /// ### [10.4.6.11 \[\[OwnPropertyKeys\]\] ( )](https://tc39.es/ecma262/#sec-module-namespace-exotic-objects-ownpropertykeys)
    fn try_own_property_keys<'gc>(
        self,
        agent: &mut Agent,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, Vec<PropertyKey<'gc>>> {
        // 1. Let exports be O.[[Exports]].
        let exports = self
            .bind(gc)
            .get(agent)
            .exports
            .iter()
            .map(|string| PropertyKey::from(*string));
        let exports_count = exports.len();
        // 2. Let symbolKeys be OrdinaryOwnPropertyKeys(O).
        // 3. Return the list-concatenation of exports and symbolKeys.
        let mut own_property_keys = Vec::with_capacity(exports_count + 1);
        exports.for_each(|export_key| own_property_keys.push(export_key));
        own_property_keys.push(WellKnownSymbols::ToStringTag.into());
        TryResult::Continue(own_property_keys)
    }

    #[inline(always)]
    fn get_own_property_at_offset<'gc>(
        self,
        _: &Agent,
        _: PropertyOffset,
        _: NoGcScope<'gc, '_>,
    ) -> TryGetResult<'gc> {
        unreachable!()
    }
}

/// ### [10.4.6.12 ModuleNamespaceCreate ( module, exports )](https://tc39.es/ecma262/#sec-modulenamespacecreate)
///
/// The abstract operation ModuleNamespaceCreate takes arguments module (a
/// Module Record) and exports (a List of Strings) and returns a module
/// namespace exotic object. It is used to specify the creation of new module
/// namespace exotic objects.
pub(crate) fn module_namespace_create<'a>(
    agent: &mut Agent,
    module: AbstractModule<'a>,
    mut exports: Box<[String<'a>]>,
    gc: NoGcScope<'a, '_>,
) -> Module<'a> {
    // 1. Assert: module.[[Namespace]] is empty.
    debug_assert!(module.namespace(agent, gc).is_none());
    // 2. Let internalSlotsList be the internal slots listed in Table 33.
    // 3. Let M be MakeBasicObject(internalSlotsList).
    // 4. Set M's essential internal methods to the definitions specified in 10.4.6.
    // 5. Set M.[[Module]] to module.
    // 6. Let sortedExports be a List whose elements are the elements of
    //    exports, sorted according to lexicographic code unit order.
    // TODO: this implements UTF-8 lexicographic order, not UTF-16.
    exports.sort_by(|a, b| a.as_wtf8_(agent).cmp(b.as_wtf8_(agent)));
    // 7. Set M.[[Exports]] to sortedExports.
    // 8. Create own properties of M corresponding to the definitions in 28.3.
    let m = agent.heap.create(ModuleHeapData { module, exports });
    // 9. Set module.[[Namespace]] to M.
    module.set_namespace(agent, m);
    // 10. Return M.
    m
}

impl HeapMarkAndSweep for Module<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        queues.modules.push(*self);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        compactions.modules.shift_index(&mut self.0);
    }
}

impl HeapSweepWeakReference for Module<'static> {
    fn sweep_weak_reference(self, compactions: &CompactionLists) -> Option<Self> {
        compactions.modules.shift_weak_index(self.0).map(Self)
    }
}