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
// 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/.

//! ### [16.2.1 Module Semantics](https://tc39.es/ecma262/#sec-module-semantics)

mod abstract_module_records;
mod cyclic_module_records;
mod source_text_module_records;

pub use abstract_module_records::*;
pub use cyclic_module_records::*;
pub use source_text_module_records::*;

use super::continue_dynamic_import;
use ahash::AHasher;
use hashbrown::{HashTable, hash_table::Entry};
use oxc_ast::ast;
use std::hash::{Hash, Hasher};

use crate::{
    ecmascript::{
        Agent, HostDefined, JsResult, Module, Realm, Script, ScriptOrModule,
        module_namespace_create, types::String,
    },
    engine::{Bindable, HeapRootData, HeapRootRef, NoGcScope, Rootable, bindable_handle},
    heap::{
        ArenaAccess, BaseIndex, CompactionLists, HeapIndexHandle, HeapMarkAndSweep, WorkQueues,
        arena_vec_access,
    },
};

/// ### [16.2.1.3 ModuleRequest Records](https://tc39.es/ecma262/#sec-modulerequest-record)
///
/// A ModuleRequest Record represents the request to import a module with given
/// import attributes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ModuleRequestRecord<'a> {
    /// ### \[\[Specifier]]
    ///
    /// a String
    ///
    /// The module specifier
    specifier: String<'a>,
    /// ### \[\[Attributes]]
    ///
    /// a List of ImportAttribute Records
    ///
    /// The import attributes
    ///
    /// > NOTE: The attributes are sorted by key in a stable, deterministic,
    /// > but undetermined order.
    attributes: Option<Box<[ImportAttributeRecord<'a>]>>,
    /// Precomputed hash of the ModuleRequest specifier and attributes.
    hash: u64,
}

impl<'a> ModuleRequestRecord<'a> {
    /// ### \[\[Attributes]]
    fn attributes(&self) -> &[ImportAttributeRecord<'a>] {
        self.attributes.as_ref().map_or(&[], |attrs| attrs.as_ref())
    }
}

impl AsRef<[ModuleRequestRecord<'static>]> for Agent {
    fn as_ref(&self) -> &[ModuleRequestRecord<'static>] {
        &self.heap.module_request_records
    }
}

impl AsMut<[ModuleRequestRecord<'static>]> for Agent {
    fn as_mut(&mut self) -> &mut [ModuleRequestRecord<'static>] {
        &mut self.heap.module_request_records
    }
}

/// ### [16.2.1.3 ModuleRequest Records](https://tc39.es/ecma262/#sec-modulerequest-record)
///
/// A ModuleRequest Record represents the request to import a module with given
/// import attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct ModuleRequest<'a>(BaseIndex<'a, ModuleRequestRecord<'static>>);
bindable_handle!(ModuleRequest);
arena_vec_access!(ModuleRequest, 'a, ModuleRequestRecord, module_request_records);

impl<'r> ModuleRequest<'r> {
    /// Create a new ModuleRequest from a specifier string and a `with`
    /// clause.
    pub(super) fn new(
        agent: &mut Agent,
        specifier: &str,
        with_clause: Option<&ast::WithClause>,
        gc: NoGcScope<'r, '_>,
    ) -> Self {
        let mut state = AHasher::default();
        specifier.hash(&mut state);
        let specifier = String::from_str(agent, specifier, gc).unbind();
        let attributes = with_clause.map(|with_clause| {
            // Note: we first have to collect the key-value pairs into a
            // separate boxed slice to be able to sort them by key. Only then
            // can we hash them and perform the conversion into
            // ImportAttributeRecord structs.
            let mut key_value_pairs = with_clause
                .with_entries
                .iter()
                .map(|attr| {
                    let key = attr.key.as_atom().as_str();
                    let value = attr.value.value.as_str();
                    (key, value)
                })
                .collect::<Box<[(&str, &str)]>>();
            key_value_pairs.sort_by_key(|attr| attr.0);

            key_value_pairs
                .into_iter()
                .map(|(key, value)| {
                    key.hash(&mut state);
                    value.hash(&mut state);
                    ImportAttributeRecord {
                        key: String::from_str(agent, key, gc).unbind(),
                        value: String::from_str(agent, value, gc).unbind(),
                    }
                })
                .collect()
        });
        let hash = state.finish();
        let index = agent.heap.module_request_records.len() as u32;
        agent.heap.module_request_records.push(ModuleRequestRecord {
            specifier,
            attributes,
            hash,
        });
        Self::from_index_u32(index)
    }

    /// Create a new ModuleRequest from a specifier String and a list of
    /// import attribute records.
    pub(super) fn new_dynamic(
        agent: &mut Agent,
        specifier: String,
        attributes: Box<[ImportAttributeRecord]>,
        gc: NoGcScope<'r, '_>,
    ) -> Self {
        let mut state = AHasher::default();
        specifier.to_string_lossy_(agent).hash(&mut state);
        for attribute in attributes.iter() {
            attribute.key.to_string_lossy_(agent).hash(&mut state);
            attribute.value.to_string_lossy_(agent).hash(&mut state);
        }
        let hash = state.finish();
        let index = agent.heap.module_request_records.len() as u32;
        agent.heap.module_request_records.push(
            ModuleRequestRecord {
                specifier,
                attributes: Some(attributes),
                hash,
            }
            .unbind(),
        );
        Self::from_index_u32(index).bind(gc)
    }

    /// Get the ModuleRequest's \[\[Specifier]] string.
    pub fn specifier(self, agent: &Agent) -> String<'r> {
        self.get(agent).specifier
    }

    /// Get the ModuleRequest's \[\[Attributes]] list.
    pub fn attributes(self, agent: &Agent) -> &[ImportAttributeRecord<'r>] {
        self.get(agent).attributes()
    }
}

impl HeapIndexHandle for ModuleRequest<'_> {
    const _DEF: Self = Self(BaseIndex::MAX);
    #[inline]
    fn from_index_u32(index: u32) -> Self {
        Self(BaseIndex::from_index_u32(index))
    }
    #[inline]
    fn get_index_u32(self) -> u32 {
        self.0.get_index_u32()
    }
}

bindable_handle!(ModuleRequestRecord);

/// # [LoadedModuleRequest Records](https://tc39.es/ecma262/#table-loadedmodulerequest-fields)
#[derive(Debug)]
pub(crate) struct LoadedModuleRequestRecord<'a> {
    module_request: ModuleRequest<'a>,
    /// ### \[\[Module]]
    ///
    /// a Module Record
    ///
    /// The loaded module corresponding to this module request
    module: AbstractModule<'a>,
}

/// # [ImportAttribute Records](https://tc39.es/ecma262/#table-importattribute-fields)
///
/// Import attribute records are used by the ECMAScript module import code to
/// express import attributes. Each attribute consists of a key and value string
/// pair.
///
/// # Example
///
/// ```javascript
/// import {} from "" with { "key": "value" };
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportAttributeRecord<'a> {
    /// ### \[\[Key]]
    ///
    /// a String
    ///
    /// The attribute key
    pub(crate) key: String<'a>,
    /// ### \[\[Value]]
    ///
    /// a String
    ///
    /// The attribute value
    pub(crate) value: String<'a>,
}
bindable_handle!(ImportAttributeRecord);

/// ### \[\[LoadedModules]]
///
/// a List of LoadedModuleRequest Records
///
/// A map from the module requests to loaded used by the module represented by this
/// record to request the importation of a module with the relative import
/// attributes to the resolved Module Record. The list does not contain two
/// different Records r1 and r2 such that ModuleRequestsEqual(r1, r2) is true.
#[derive(Debug, Default)]
pub(crate) struct LoadedModules<'a> {
    table: HashTable<LoadedModuleRequestRecord<'a>>,
}

impl<'a> LoadedModules<'a> {
    /// Get a loaded module for a module request, if present.
    pub(crate) fn get_loaded_module(
        &self,
        requests: &Vec<ModuleRequestRecord<'static>>,
        module_request: ModuleRequest<'a>,
    ) -> Option<AbstractModule<'a>> {
        let hash = module_request.get(requests).hash;
        self.table
            .find(hash, |record| {
                module_requests_equal(
                    record.module_request.get(requests),
                    module_request.get(requests),
                )
            })
            .map(|record| record.module)
    }

    /// Add a loaded module for a module request.
    pub(crate) fn insert_loaded_module<'gc>(
        &mut self,
        requests: &Vec<ModuleRequestRecord<'static>>,
        module_request: ModuleRequest<'gc>,
        module: AbstractModule<'gc>,
    ) {
        let hash = module_request.get(requests).hash;
        // a. If referrer.[[LoadedModules]] contains a LoadedModuleRequest
        //    Record record such that ModuleRequestsEqual(record,
        //    moduleRequest) is true, then
        match self.table.entry(
            hash,
            |record| {
                module_requests_equal(
                    record.module_request.get(requests),
                    module_request.get(requests),
                )
            },
            |record| record.module_request.get(requests).hash,
        ) {
            Entry::Occupied(e) => {
                // i. Assert: record.[[Module]] and result.[[Value]] are the
                //    same Module Record.
                assert!(e.get().module == module);
            }
            Entry::Vacant(e) => {
                // b. Else,
                // i. Append the LoadedModuleRequest Record {
                e.insert(LoadedModuleRequestRecord {
                    // [[Specifier]]: moduleRequest.[[Specifier]],
                    // [[Attributes]]: moduleRequest.[[Attributes]],
                    module_request: module_request.unbind(),
                    // [[Module]]: result.[[Value]]
                    module: module.unbind(),
                });
                // } to referrer.[[LoadedModules]].
            }
        }
    }
}

/// ### [16.2.1.3.1 ModuleRequestsEqual ( left, right )](https://tc39.es/ecma262/#sec-ModuleRequestsEqual)
///
/// The abstract operation ModuleRequestsEqual takes arguments left (a
/// ModuleRequest Record or a LoadedModuleRequest Record) and right (a
/// ModuleRequest Record or a LoadedModuleRequest Record) and returns a
/// Boolean.
fn module_requests_equal(left: &ModuleRequestRecord, right: &ModuleRequestRecord) -> bool {
    // 1. If left.[[Specifier]] is not right.[[Specifier]], return false.
    if left.specifier != right.specifier {
        return false;
    }
    // 2. Let leftAttrs be left.[[Attributes]].
    let left_attrs = left.attributes();
    // 3. Let rightAttrs be right.[[Attributes]].
    let right_attrs = right.attributes();
    // 4. Let leftAttrsCount be the number of elements in leftAttrs.
    let left_attrs_count = left_attrs.len();
    // 5. Let rightAttrsCount be the number of elements in rightAttrs.
    let right_attrs_count = right_attrs.len();
    // 6. If leftAttrsCount ≠ rightAttrsCount, return false.
    if left_attrs_count != right_attrs_count {
        return false;
    }
    // NOTE: ModuleRequestRecords have an invariant over module imports holding
    // attributes ordered by key.
    // 7. For each ImportAttribute Record l of leftAttrs, do
    for (l, r) in left_attrs.iter().zip(right_attrs.iter()) {
        // a. If rightAttrs does not contain an ImportAttribute Record r
        //    such that l.[[Key]] is r.[[Key]] and l.[[Value]] is
        //    r.[[Value]], return false.
        if l.key != r.key || l.value != r.value {
            return false;
        }
    }
    // 8. Return true.
    true
}

/// ### [16.2.1.9 GetImportedModule ( referrer, request )](https://tc39.es/ecma262/#sec-GetImportedModule)
///
/// The abstract operation GetImportedModule takes arguments referrer (a Cyclic
/// Module Record) and request (a ModuleRequest Record) and returns a Module
/// Record.
pub(crate) fn get_imported_module<'a>(
    agent: &Agent,
    referrer: SourceTextModule<'a>,
    request: ModuleRequest,
    gc: NoGcScope<'a, '_>,
) -> AbstractModule<'a> {
    // 1. Let records be a List consisting of each LoadedModuleRequest Record r
    //    of referrer.[[LoadedModules]] such that ModuleRequestsEqual(r,
    //    request) is true.
    // 2. Assert: records has exactly one element, since LoadRequestedModules
    //    has completed successfully on referrer prior to invoking this
    //    abstract operation.
    // 3. Let record be the sole element of records.
    // 4. Return record.[[Module]].
    referrer
        .get_loaded_module(agent, request)
        .expect("Could not find loaded module for request")
        .bind(gc)
}

/// Module loading referrer.
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct Referrer<'a>(InnerReferrer<'a>);

impl Referrer<'_> {
    /// Get the Realm that this referrer belongs to.
    pub fn realm<'a>(self, agent: &Agent, gc: NoGcScope<'a, '_>) -> Realm<'a> {
        match self.0 {
            InnerReferrer::Script(s) => s.realm(agent, gc),
            InnerReferrer::SourceTextModule(m) => m.realm(agent, gc),
            InnerReferrer::Realm(r) => r.bind(gc),
        }
    }

    /// Get the host defined data of this referrer.
    pub fn host_defined(self, agent: &Agent) -> Option<HostDefined> {
        match self.0 {
            InnerReferrer::Script(s) => s.host_defined(agent),
            InnerReferrer::SourceTextModule(m) => m.host_defined(agent),
            InnerReferrer::Realm(r) => r.host_defined(agent),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum InnerReferrer<'a> {
    Script(Script<'a>),
    SourceTextModule(SourceTextModule<'a>),
    Realm(Realm<'a>),
}

impl<'a> From<Script<'a>> for Referrer<'a> {
    fn from(value: Script<'a>) -> Self {
        Self(InnerReferrer::Script(value))
    }
}

impl<'a> From<SourceTextModule<'a>> for Referrer<'a> {
    fn from(value: SourceTextModule<'a>) -> Self {
        Self(InnerReferrer::SourceTextModule(value))
    }
}

impl<'a> From<Realm<'a>> for Referrer<'a> {
    fn from(value: Realm<'a>) -> Self {
        Self(InnerReferrer::Realm(value))
    }
}

impl<'a> From<ScriptOrModule<'a>> for Referrer<'a> {
    fn from(value: ScriptOrModule<'a>) -> Self {
        match value {
            ScriptOrModule::Script(s) => Self(InnerReferrer::Script(s)),
            ScriptOrModule::SourceTextModule(m) => Self(InnerReferrer::SourceTextModule(m)),
        }
    }
}

bindable_handle!(Referrer);

impl Rootable for Referrer<'_> {
    type RootRepr = HeapRootRef;

    fn to_root_repr(value: Self) -> Result<Self::RootRepr, HeapRootData> {
        InnerReferrer::to_root_repr(value.0)
    }

    fn from_root_repr(value: &Self::RootRepr) -> Result<Self, HeapRootRef> {
        InnerReferrer::from_root_repr(value).map(Self)
    }

    fn from_heap_ref(heap_ref: HeapRootRef) -> Self::RootRepr {
        heap_ref
    }

    fn from_heap_data(heap_data: HeapRootData) -> Option<Self> {
        InnerReferrer::from_heap_data(heap_data).map(Self)
    }
}

bindable_handle!(InnerReferrer);

impl Rootable for InnerReferrer<'_> {
    type RootRepr = HeapRootRef;

    fn to_root_repr(value: Self) -> Result<Self::RootRepr, HeapRootData> {
        match value {
            Self::Script(s) => Err(HeapRootData::from(s)),
            Self::SourceTextModule(m) => Err(HeapRootData::from(m)),
            Self::Realm(r) => Err(HeapRootData::from(r)),
        }
    }

    fn from_root_repr(value: &Self::RootRepr) -> Result<Self, HeapRootRef> {
        Err(*value)
    }

    fn from_heap_ref(heap_ref: HeapRootRef) -> Self::RootRepr {
        heap_ref
    }

    fn from_heap_data(heap_data: HeapRootData) -> Option<Self> {
        match heap_data {
            HeapRootData::Script(s) => Some(Self::Script(s)),
            HeapRootData::SourceTextModule(m) => Some(Self::SourceTextModule(m)),
            HeapRootData::Realm(r) => Some(Self::Realm(r)),
            _ => None,
        }
    }
}

impl Referrer<'_> {
    fn insert_loaded_module(
        self,
        agent: &mut Agent,
        request: ModuleRequest,
        module: AbstractModule,
    ) {
        match self.0 {
            InnerReferrer::Script(s) => s.insert_loaded_module(agent, request, module),
            InnerReferrer::SourceTextModule(m) => m.insert_loaded_module(agent, request, module),
            InnerReferrer::Realm(r) => r.insert_loaded_module(agent, request, module),
        }
    }
}

/// ### [16.2.1.11 FinishLoadingImportedModule ( referrer, moduleRequest, payload, result )](https://tc39.es/ecma262/#sec-FinishLoadingImportedModule)
///
/// The abstract operation FinishLoadingImportedModule takes arguments referrer
/// (a Script Record, a Cyclic Module Record, or a Realm Record), moduleRequest
/// (a ModuleRequest Record), payload (a GraphLoadingState Record or a
/// PromiseCapability Record), and result (either a normal completion
/// containing a Module Record or a throw completion) and returns unused.
pub fn finish_loading_imported_module<'a>(
    agent: &mut Agent,
    referrer: Referrer<'a>,
    module_request: ModuleRequest<'a>,
    payload: &mut GraphLoadingStateRecord<'a>,
    result: JsResult<'a, AbstractModule<'a>>,
    gc: NoGcScope<'a, '_>,
) {
    // 1. If result is a normal completion, then
    if let Ok(result) = result {
        // a. If referrer.[[LoadedModules]] contains a LoadedModuleRequest
        //    Record record such that ModuleRequestsEqual(record,
        //    moduleRequest) is true, then
        // i. Assert: record.[[Module]] and result.[[Value]] are the same
        //    Module Record.
        // b. Else,
        // i. Append the LoadedModuleRequest Record {
        // [[Specifier]]: moduleRequest.[[Specifier]],
        // [[Attributes]]: moduleRequest.[[Attributes]],
        // [[Module]]: result.[[Value]]
        // } to referrer.[[LoadedModules]].
        referrer.insert_loaded_module(agent, module_request, result);
    }
    // 2. If payload is a GraphLoadingState Record, then
    if payload.pending_modules_count > 0 {
        // HACK: [[PendingModulesCount]] is being used as a marker between
        // static and dynamic import. Static import always has non-zero count.
        // a. Perform ContinueModuleLoading(payload, result).
        continue_module_loading(agent, payload, result, gc);
    } else {
        // 3. Else,
        // a. Perform ContinueDynamicImport(payload, result).
        continue_dynamic_import(agent, payload.promise_capability.clone(), result, gc);
    }
    // 4. Return unused.
}

/// ### [16.2.1.12 AllImportAttributesSupported ( attributes )](https://tc39.es/ecma262/#sec-AllImportAttributesSupported)
///
/// The abstract operation AllImportAttributesSupported takes argument
/// _attributes_ (a List of ImportAttribute Records) and returns a Boolean.
pub(crate) fn all_import_attributes_supported(
    agent: &Agent,
    attributes: &[ImportAttributeRecord],
) -> bool {
    // 1. Let supported be HostGetSupportedImportAttributes().
    let supported = agent.host_hooks.get_supported_import_attributes();
    // 2. For each ImportAttribute Record attribute of attributes, do
    for attribute in attributes {
        let key = attribute.key.to_string_lossy_(agent);
        // a. If supported does not contain attribute.[[Key]], return false.
        if !supported.contains(&key.as_ref()) {
            return false;
        }
    }
    // 3. Return true.
    true
}

/// ### [16.2.1.13 GetModuleNamespace ( module )](https://tc39.es/ecma262/#sec-getmodulenamespace)
///
/// The abstract operation GetModuleNamespace takes argument module (an
/// instance of a concrete subclass of Module Record) and returns a Module
/// Namespace Object. It retrieves the Module Namespace Object representing
/// module's exports, lazily creating it the first time it was requested, and
/// storing it in module.\[\[Namespace]] for future retrieval.
///
/// > NOTE: GetModuleNamespace never throws. Instead, unresolvable names are
/// > simply excluded from the namespace at this point. They will lead to a
/// > real linking error later unless they are all ambiguous star exports that
/// > are not explicitly requested anywhere.
pub(crate) fn get_module_namespace<'a>(
    agent: &mut Agent,
    module: AbstractModule,
    gc: NoGcScope<'a, '_>,
) -> Module<'a> {
    let module = module.bind(gc);
    if let Some(module) = module.as_source_text_module() {
        // 1. Assert: If module is a Cyclic Module Record, then module.[[Status]]
        //    is not new or unlinked.
        debug_assert!(!matches!(
            module.status(agent),
            CyclicModuleRecordStatus::New | CyclicModuleRecordStatus::Unlinked
        ));
    }
    // 2. Let namespace be module.[[Namespace]].
    let namespace = module.namespace(agent, gc);
    // 3. If namespace is empty, then
    let Some(namespace) = namespace else {
        // a. Let exportedNames be module.GetExportedNames().
        let exported_names = module.get_exported_names(agent, &mut vec![], gc);
        // b. Let unambiguousNames be a new empty List.
        // c. For each element name of exportedNames, do
        let unambiguous_names = exported_names
            .into_iter()
            .filter(|name| {
                // i. Let resolution be module.ResolveExport(name).
                let resolution = module.resolve_export(agent, *name, &mut vec![], gc);
                // ii. If resolution is a ResolvedBinding Record, append name to
                //     unambiguousNames.
                matches!(resolution, Some(ResolvedBinding::Resolved { .. }))
            })
            .collect::<Box<[String]>>();
        // d. Set namespace to ModuleNamespaceCreate(module, unambiguousNames).
        return module_namespace_create(agent, module, unambiguous_names, gc);
    };
    // 4. Return namespace.
    namespace
}

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

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

impl HeapMarkAndSweep for LoadedModules<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        for loaded_module_request in self.table.iter() {
            loaded_module_request.mark_values(queues);
        }
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        // Note: we do not need to perform rehashing of the table, as we've
        // hashed the requests based on their string data which doesn't change
        // during GC, unlike the String indexes.
        for loaded_module_request in self.table.iter_mut() {
            loaded_module_request.sweep_values(compactions);
        }
    }
}

impl HeapMarkAndSweep for LoadedModuleRequestRecord<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        let Self {
            module_request,
            module,
        } = self;
        module_request.mark_values(queues);
        module.mark_values(queues);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        let Self {
            module_request,
            module,
        } = self;
        module_request.sweep_values(compactions);
        module.sweep_values(compactions);
    }
}