Skip to main content

quickjs/
module.rs

1//! The module system: records, linking, namespaces, and evaluation.
2//!
3//! The design follows §16.2 closely but leans on one thing this engine already has.
4//! A module's top-level bindings compile as *closure variables* of the module body —
5//! `ClosureType::ModuleDecl` for its own declarations, `ClosureType::ModuleImport` for
6//! what it imports — so reading one is an ordinary `get_var_ref`. What makes modules
7//! interesting is then entirely a question of **who fills the cells**:
8//!
9//! * a declaration gets a fresh cell, created here;
10//! * an import gets *the exporting module's* cell, not a copy.
11//!
12//! Sharing the cell is what makes bindings live (`export let x; x = 1` is visible to the
13//! importer) and what makes cyclic imports work: linking wires cells before anything
14//! evaluates, so `a.js` importing from a `b.js` that imports back from `a.js` resolves to
15//! cells on both sides without either body having run.
16//!
17//! The three phases are the spec's: load (read and compile), link (resolve imports,
18//! validate exports), evaluate (run bodies depth-first, once each).
19
20use std::collections::BTreeMap;
21
22use js_gc::{Gc, Trace, Tracer};
23
24use crate::interp::{Interp, JsResult, Signal, WellKnown};
25use crate::object::{Callable, ClosureEnv, CompiledCode, JsObject, Property};
26use crate::value::{Cell, Value};
27
28/// Where a module is in its lifetime.
29///
30/// `Linking` and `Evaluated` are not just bookkeeping: they are what makes a cycle
31/// terminate. A cycle is not an error — it is a graph that must be *linked* depth-first
32/// and then *evaluated* in post-order, and the two-phase split is the mechanism.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum ModuleStatus {
35    /// Loaded and compiled; imports not yet resolved.
36    Unlinked,
37    /// Being linked, so a re-entrant link must not recurse.
38    Linking,
39    /// Imports resolved and exports validated.
40    Linked,
41    /// Body running or already run, so a re-entrant evaluation must not run it twice.
42    Evaluated,
43}
44
45/// How a module's source became a module.
46///
47/// A JSON or text module is not code at all — it is one value exported as `default` — so
48/// it has no body and no imports, which is why this is a flag rather than a second type.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ModuleKind {
51    /// JavaScript: has a compiled body.
52    JavaScript,
53    /// A parsed JSON document, exported as `default`.
54    Json,
55    /// A plain string, exported as `default`.
56    Text,
57    /// A `Uint8Array`, exported as `default`.
58    Bytes,
59}
60
61/// One loaded module.
62///
63/// Held on the GC heap because its cells and namespace are GC values. The whole record is
64/// behind interior mutability the same way a [`Cell`] is: linking writes into it while
65/// other modules already hold references to it.
66pub struct ModuleRecord {
67    inner: std::cell::RefCell<ModuleInner>,
68}
69
70impl ModuleRecord {
71    /// Build a record around `inner`.
72    pub fn new(inner: ModuleInner) -> ModuleRecord {
73        ModuleRecord {
74            inner: std::cell::RefCell::new(inner),
75        }
76    }
77
78    /// Run `f` with the record borrowed.
79    pub fn with<R>(&self, f: impl FnOnce(&ModuleInner) -> R) -> R {
80        f(&self.inner.borrow())
81    }
82
83    /// Run `f` with the record borrowed mutably.
84    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ModuleInner) -> R) -> R {
85        f(&mut self.inner.borrow_mut())
86    }
87}
88
89/// Everything a module record holds; see [`ModuleRecord`].
90pub struct ModuleInner {
91    /// Canonical identity: the cache key, and what a cycle compares.
92    pub name: String,
93    /// What `import.meta.url` reports.
94    pub url: String,
95    /// The compiled body, or `None` for a JSON/text/bytes module.
96    pub code: Option<Gc<CompiledCode>>,
97    /// The tables the compiler produced.
98    pub meta: js_compile::bytecode::ModuleMeta,
99    /// One cell per closure variable of the body; the body reads its bindings here.
100    pub cells: Vec<Gc<Cell>>,
101    /// Resolved dependencies, parallel to `meta.requests`.
102    pub dependencies: Vec<Option<Gc<ModuleRecord>>>,
103    /// Where it is in its lifetime.
104    pub status: ModuleStatus,
105    /// What kind of module it is.
106    pub kind: ModuleKind,
107    /// The namespace object, built on first use.
108    pub namespace: Option<Gc<JsObject>>,
109    /// `import.meta`, built at load time.
110    pub import_meta: Option<Gc<JsObject>>,
111}
112
113impl Trace for ModuleRecord {
114    fn trace(&self, tracer: &mut Tracer) {
115        self.inner.borrow().trace(tracer);
116    }
117}
118
119impl Trace for ModuleInner {
120    fn trace(&self, tracer: &mut Tracer) {
121        if let Some(code) = &self.code {
122            tracer.visit(code);
123        }
124        for cell in &self.cells {
125            tracer.visit(cell);
126        }
127        for dependency in self.dependencies.iter().flatten() {
128            tracer.visit(dependency);
129        }
130        if let Some(namespace) = &self.namespace {
131            tracer.visit(namespace);
132        }
133        if let Some(meta) = &self.import_meta {
134            tracer.visit(meta);
135        }
136    }
137}
138
139/// A host-supplied module, before it is compiled.
140pub struct LoadedModule {
141    /// Canonical identity — the cache key, and how a cycle recognises itself.
142    pub name: String,
143    /// `import.meta.url` for this module.
144    pub url: String,
145    /// The file's bytes. Not necessarily UTF-8: a `bytes` module is arbitrary.
146    pub source: Vec<u8>,
147}
148
149/// How the host turns a specifier into bytes.
150///
151/// The engine cannot do this itself: resolving `./x.js` needs to know that the importer
152/// was a file, and where. A browser-shaped host would answer differently, so the host
153/// supplies this and the engine decides what to do with the bytes.
154pub trait ModuleLoader {
155    /// Resolve `specifier` relative to `referrer` and read it.
156    ///
157    /// `referrer` is empty for the entry module.
158    fn load(
159        &self,
160        specifier: &str,
161        attributes: &[(String, String)],
162        referrer: &str,
163    ) -> Result<LoadedModule, String>;
164}
165
166impl<'a> Interp<'a> {
167    /// The module registry: one entry per canonical name, so each file is compiled once.
168    pub fn module_registry(&self) -> &BTreeMap<String, Gc<ModuleRecord>> {
169        &self.modules
170    }
171
172    /// Evaluate `specifier` as the entry module, the way `qjs -m file.js` does.
173    pub fn run_main_module(&mut self, specifier: &str) -> JsResult<Value> {
174        let module = self.load_module(specifier, &[], "")?;
175        let name = module.with(|r| r.name.clone());
176        self.main_module_name = Some(name.clone());
177        // The record was built before the name was known, so `main` is stamped now.
178        if let Some(meta) = module.with(|r| r.import_meta.clone()) {
179            meta.define_data("main", Value::Bool(true));
180        }
181        self.link_module(&module)?;
182        self.module_stack.push(name);
183        let result = self.evaluate_module_body(&module);
184        self.module_stack.pop();
185        result?;
186        self.module_namespace(&module)
187    }
188
189    /// Load and compile one module.
190    pub fn load_module(
191        &mut self,
192        specifier: &str,
193        attributes: &[(String, String)],
194        referrer: &str,
195    ) -> JsResult<Gc<ModuleRecord>> {
196        let Some(loader) = self.module_loader.take() else {
197            return Err(Signal::Throw(
198                self.make_error("InternalError", "no module loader is installed"),
199            ));
200        };
201        let loaded = loader.load(specifier, attributes, referrer);
202        // Put the loader back whatever happened: it is the host's, and the interpreter
203        // only borrows it so that `&mut self` stays available for compiling.
204        self.module_loader = Some(loader);
205        let loaded = match loaded {
206            Ok(loaded) => loaded,
207            Err(message) => {
208                return Err(Signal::Throw(self.make_error("ReferenceError", &message)));
209            }
210        };
211        // One record per *(name, attributes)*, so importing the same file twice runs it
212        // once — but importing it as JSON and as text is two modules with two contents,
213        // which `hello_module.js` does on purpose.
214        let key = cache_key(&loaded.name, attributes);
215        if let Some(existing) = self.modules.get(&key) {
216            return Ok(existing.clone());
217        }
218        let kind = match module_kind(&loaded.name, attributes) {
219            Ok(kind) => kind,
220            Err(message) => {
221                return Err(Signal::Throw(self.make_error("TypeError", &message)));
222            }
223        };
224        let record = match kind {
225            ModuleKind::JavaScript => self.compile_module_record(&loaded)?,
226            _ => self.data_module_record(&loaded, kind)?,
227        };
228        self.modules.insert(key, record.clone());
229        Ok(record)
230    }
231
232    /// Compile a JavaScript module and create its cells.
233    fn compile_module_record(&mut self, loaded: &LoadedModule) -> JsResult<Gc<ModuleRecord>> {
234        let source = match std::str::from_utf8(&loaded.source) {
235            Ok(source) => source,
236            Err(_) => {
237                return Err(Signal::Throw(self.make_error(
238                    "SyntaxError",
239                    &format!("{}: module source is not valid UTF-8", loaded.name),
240                )));
241            }
242        };
243        // Same shape as a script's compile error: the message, then `at <file>:<line>:<col>`
244        // unless the reference reports this one without a position. The file name is *not*
245        // part of the message — it belongs on the `at` line only.
246        let program = match js_parse::parse_module(source) {
247            Ok(program) => program,
248            Err(error) => {
249                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
250            }
251        };
252        let mut code = match js_compile::compile_module(&program) {
253            Ok(code) => code,
254            Err(error) => {
255                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
256            }
257        };
258        code.set_filename(&loaded.name);
259        let meta = code
260            .module
261            .as_ref()
262            .map(|meta| (**meta).clone())
263            .unwrap_or_default();
264        let closure_vars = code.closure_vars.clone();
265        let compiled = Gc::new(self.heap, CompiledCode::new(code));
266        // One cell per closure variable. A lexical binding starts in its dead zone and a
267        // `var` as `undefined`; an import's cell is *replaced* during linking by the
268        // exporter's, which is what makes it live.
269        let mut cells = Vec::with_capacity(closure_vars.len());
270        for closure_var in &closure_vars {
271            let initial = if closure_var.is_lexical {
272                Value::Uninitialized
273            } else {
274                Value::Undefined
275            };
276            cells.push(self.new_cell(initial));
277        }
278        let dependencies = vec![None; meta.requests.len()];
279        let record = Gc::new(
280            self.heap,
281            ModuleRecord::new(ModuleInner {
282                name: loaded.name.clone(),
283                url: loaded.url.clone(),
284                code: Some(compiled),
285                meta,
286                cells,
287                dependencies,
288                status: ModuleStatus::Unlinked,
289                kind: ModuleKind::JavaScript,
290                namespace: None,
291                import_meta: None,
292            }),
293        );
294        self.install_import_meta(&record)?;
295        Ok(record)
296    }
297
298    /// A JSON, text or bytes module: one value, exported as `default`.
299    ///
300    /// The value is produced by calling the *builtin* rather than by reaching into the
301    /// JSON parser or the typed-array internals, so a data module behaves exactly like
302    /// `JSON.parse(text)` or `new Uint8Array(bytes)` written out by hand — one
303    /// implementation of each, not two.
304    fn data_module_record(
305        &mut self,
306        loaded: &LoadedModule,
307        kind: ModuleKind,
308    ) -> JsResult<Gc<ModuleRecord>> {
309        let value = match kind {
310            ModuleKind::Json => {
311                let text = String::from_utf8_lossy(&loaded.source).to_string();
312                let Some(json) = self.global_value("JSON") else {
313                    return Err(Signal::Throw(
314                        self.make_error("InternalError", "JSON is not installed"),
315                    ));
316                };
317                let Some(Value::Object(json)) = Some(json) else {
318                    unreachable!()
319                };
320                let Some(parse) = self.get_property(&json, "parse")? else {
321                    return Err(Signal::Throw(
322                        self.make_error("InternalError", "JSON.parse is not installed"),
323                    ));
324                };
325                let text = self.string(&text);
326                match self.call_value(parse, Value::Object(json), vec![text]) {
327                    Ok(value) => value,
328                    Err(Signal::Throw(reason)) => {
329                        let detail = self.describe_exception(&reason);
330                        return Err(Signal::Throw(self.make_error(
331                            "SyntaxError",
332                            &format!("{}: {}", loaded.name, detail),
333                        )));
334                    }
335                    Err(other) => return Err(other),
336                }
337            }
338            ModuleKind::Text => {
339                // Taken as UTF-8 with replacement: a text file that is not valid UTF-8
340                // still has to become a string.
341                let text = String::from_utf8_lossy(&loaded.source).to_string();
342                self.string(&text)
343            }
344            ModuleKind::Bytes => {
345                let numbers: Vec<Value> = loaded
346                    .source
347                    .iter()
348                    .map(|byte| Value::Int(*byte as i32))
349                    .collect();
350                let elements = self.new_array(numbers);
351                let Some(Value::Object(ctor)) = self.global_value("Uint8Array") else {
352                    return Err(Signal::Throw(
353                        self.make_error("InternalError", "Uint8Array is not installed"),
354                    ));
355                };
356                self.construct(
357                    Value::Object(ctor),
358                    Value::Object(elements.clone()),
359                    vec![Value::Object(elements)],
360                )?
361            }
362            ModuleKind::JavaScript => unreachable!("handled by `compile_module_record`"),
363        };
364        let cell = self.new_cell(value.clone());
365        let record = Gc::new(
366            self.heap,
367            ModuleRecord::new(ModuleInner {
368                name: loaded.name.clone(),
369                url: loaded.url.clone(),
370                code: None,
371                meta: js_compile::bytecode::ModuleMeta {
372                    requests: Vec::new(),
373                    imports: Vec::new(),
374                    exports: vec![js_compile::bytecode::ExportEntry::Local {
375                        export_name: "default".to_string(),
376                        var_idx: 0,
377                    }],
378                },
379                cells: vec![cell],
380                dependencies: Vec::new(),
381                // Nothing to link and nothing to run: a data module is born evaluated,
382                // which is what lets `import x from "./m.json"` work inside a cycle.
383                status: ModuleStatus::Evaluated,
384                kind,
385                namespace: None,
386                import_meta: None,
387            }),
388        );
389        Ok(record)
390    }
391
392    /// A binding of the global object, if it exists.
393    fn global_value(&mut self, name: &str) -> Option<Value> {
394        let global = self.realm.global.clone();
395        self.get_property(&global, name).ok().flatten()
396    }
397
398    /// `import.meta` for `record`, built once.
399    fn install_import_meta(&mut self, record: &Gc<ModuleRecord>) -> JsResult<()> {
400        let proto = self.realm.object_proto.clone();
401        let meta = self.new_object(Some(proto));
402        let url = self.string(record.with(|r| r.url.clone()));
403        // Only the two properties the reference defines; a script can add its own.
404        meta.define_data("url", url);
405        meta.define_data("main", Value::Bool(false));
406        record.with_mut(|r| r.import_meta = Some(meta));
407        Ok(())
408    }
409
410    /// Resolve every import of `module` and validate its exports, depth-first.
411    pub fn link_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
412        match module.with(|r| r.status) {
413            // Already linked, or being linked right now — the latter is a cycle, and it is
414            // exactly why the status is set *before* recursing: a cycle stops here rather
415            // than recursing forever.
416            ModuleStatus::Linking | ModuleStatus::Linked | ModuleStatus::Evaluated => {
417                return Ok(());
418            }
419            ModuleStatus::Unlinked => {}
420        }
421        module.with_mut(|r| r.status = ModuleStatus::Linking);
422
423        let requests = module.with(|r| r.meta.requests.clone());
424        for (index, request) in requests.iter().enumerate() {
425            let referrer = module.with(|r| r.name.clone());
426            let dependency =
427                self.load_module(&request.specifier, &request.attributes, &referrer)?;
428            module.with_mut(|r| r.dependencies[index] = Some(dependency.clone()));
429            self.link_module(&dependency)?;
430        }
431
432        // Wire the cells. `import { x } from "m"` makes this module's cell *be* `m`'s, so
433        // a later assignment over there is visible here with no copying.
434        let imports = module.with(|r| r.meta.imports.clone());
435        for entry in &imports {
436            let dependency =
437                module.with(|r| r.dependencies.get(entry.module as usize).cloned().flatten());
438            let Some(dependency) = dependency else {
439                return Err(Signal::Throw(self.make_error(
440                    "InternalError",
441                    "an import names a module that was not loaded",
442                )));
443            };
444            if entry.is_star {
445                let namespace = self.module_namespace(&dependency)?;
446                let cell = module.with(|r| r.cells[entry.var_idx as usize].clone());
447                cell.set(namespace);
448                continue;
449            }
450            let cell = self.resolve_export(&dependency, &entry.name)?;
451            module.with_mut(|r| r.cells[entry.var_idx as usize] = cell);
452        }
453
454        // Validate: `export { a } from "m"` where `m` has no `a` is a link error, and
455        // saying so now beats an `undefined` that surfaces much later.
456        let exports = module.with(|r| r.meta.exports.clone());
457        for entry in &exports {
458            if let js_compile::bytecode::ExportEntry::Indirect {
459                export_name,
460                module: index,
461                import_name,
462            } = entry
463            {
464                let dependency =
465                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
466                let Some(dependency) = dependency else {
467                    continue;
468                };
469                if self.resolve_export(&dependency, import_name).is_err() {
470                    let dependency_name = dependency.with(|r| r.name.clone());
471                    return Err(Signal::Throw(self.make_error(
472                        "SyntaxError",
473                        &format!(
474                            "Could not find export '{import_name}' in module '{dependency_name}' (re-exported as '{export_name}')"
475                        ),
476                    )));
477                }
478            }
479        }
480
481        // Create the module's hoisted bindings *now*, while linking — before any body
482        // runs anywhere in the graph.
483        //
484        // This is the whole trick behind cyclic imports. The body's prologue is
485        // `push_this; if_false <body>`, so calling it with a truthy `this` runs only the
486        // hoisted declarations and returns. Doing that for every module during linking
487        // means that when evaluation finally starts, every exported function in the
488        // cycle already exists — which is why `b.js` can see `a`'s function even though
489        // `a.js` has not run yet.
490        self.hoist_module_bindings(module)?;
491
492        module.with_mut(|r| r.status = ModuleStatus::Linked);
493        Ok(())
494    }
495
496    /// Run `module`'s prologue only, creating its hoisted bindings.
497    fn hoist_module_bindings(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
498        let Some(code) = module.with(|r| r.code.clone()) else {
499            // A JSON/text module has nothing to hoist.
500            return Ok(());
501        };
502        let env = self.module_env(module);
503        self.execute(code, env, Value::Bool(true), Vec::new(), Value::Undefined)
504            .map(|_| ())
505    }
506
507    /// The closure environment a module body runs in: one cell per closure variable.
508    fn module_env(&mut self, module: &Gc<ModuleRecord>) -> Gc<ClosureEnv> {
509        let cells = module.with(|r| r.cells.clone());
510        Gc::new(
511            self.heap,
512            ClosureEnv {
513                cells,
514                eval_scope: None,
515                local_vars: None,
516                local_phase: 0,
517            },
518        )
519    }
520
521    /// The cell behind `name` in `module`, following re-exports.
522    pub fn resolve_export(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Gc<Cell>> {
523        self.resolve_export_inner(module, name, 0)
524    }
525
526    fn resolve_export_inner(
527        &mut self,
528        module: &Gc<ModuleRecord>,
529        name: &str,
530        depth: usize,
531    ) -> JsResult<Gc<Cell>> {
532        // A pathological chain (`a` exports from `b`, `b` from `a`) would otherwise
533        // recurse until the Rust stack gives out.
534        if depth > 64 {
535            return Err(Signal::Throw(
536                self.make_error("SyntaxError", "circular re-export chain"),
537            ));
538        }
539        let exports = module.with(|r| r.meta.exports.clone());
540        // An explicit export wins over any `export *`.
541        for entry in &exports {
542            match entry {
543                js_compile::bytecode::ExportEntry::Local {
544                    export_name,
545                    var_idx,
546                } if export_name == name => {
547                    return Ok(module.with(|r| r.cells[*var_idx as usize].clone()));
548                }
549                js_compile::bytecode::ExportEntry::Indirect {
550                    export_name,
551                    module: index,
552                    import_name,
553                } if export_name == name => {
554                    let dependency =
555                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
556                    let Some(dependency) = dependency else {
557                        return Err(self.missing_export(module, name));
558                    };
559                    return self.resolve_export_inner(&dependency, import_name, depth + 1);
560                }
561                js_compile::bytecode::ExportEntry::StarAs { export_name, .. }
562                    if export_name == name =>
563                {
564                    // The namespace of the re-exported module, wrapped in a cell so the
565                    // export table stays uniform. A fresh cell each time is harmless:
566                    // nothing can assign through it.
567                    let namespace = self.star_namespace(module, name)?;
568                    return Ok(self.new_cell(namespace));
569                }
570                _ => {}
571            }
572        }
573        // `export * from "m"`: forwarded names are visible only if nothing above claimed
574        // them, which is why this is a second pass.
575        for entry in &exports {
576            if let js_compile::bytecode::ExportEntry::Star { module: index } = entry {
577                let dependency =
578                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
579                let Some(dependency) = dependency else {
580                    continue;
581                };
582                if let Ok(cell) = self.resolve_export_inner(&dependency, name, depth + 1) {
583                    return Ok(cell);
584                }
585            }
586        }
587        Err(self.missing_export(module, name))
588    }
589
590    fn missing_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
591        let module_name = module.with(|r| r.name.clone());
592        // The reference's wording, kept verbatim: an error message is part of the
593        // behaviour a user sees, and `qjs` says "Could not find export".
594        Signal::Throw(self.make_error(
595            "SyntaxError",
596            &format!("Could not find export '{name}' in module '{module_name}'"),
597        ))
598    }
599
600    /// The namespace behind `export * as ns from "m"`.
601    fn star_namespace(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Value> {
602        let exports = module.with(|r| r.meta.exports.clone());
603        for entry in &exports {
604            if let js_compile::bytecode::ExportEntry::StarAs {
605                export_name,
606                module: index,
607            } = entry
608                && export_name == name
609            {
610                let dependency =
611                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
612                let Some(dependency) = dependency else {
613                    continue;
614                };
615                return self.module_namespace(&dependency);
616            }
617        }
618        Ok(Value::Undefined)
619    }
620
621    /// The names `module` exports, sorted the way §16.2.1.6 requires.
622    pub fn module_export_names(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Vec<String>> {
623        let mut names: Vec<String> = Vec::new();
624        self.collect_export_names(module, &mut names, 0)?;
625        names.sort();
626        names.dedup();
627        Ok(names)
628    }
629
630    fn collect_export_names(
631        &mut self,
632        module: &Gc<ModuleRecord>,
633        out: &mut Vec<String>,
634        depth: usize,
635    ) -> JsResult<()> {
636        if depth > 64 {
637            return Ok(());
638        }
639        let exports = module.with(|r| r.meta.exports.clone());
640        for entry in &exports {
641            match entry {
642                js_compile::bytecode::ExportEntry::Local { export_name, .. }
643                | js_compile::bytecode::ExportEntry::Indirect { export_name, .. }
644                | js_compile::bytecode::ExportEntry::StarAs { export_name, .. } => {
645                    out.push(export_name.clone());
646                }
647                js_compile::bytecode::ExportEntry::Star { module: index } => {
648                    let dependency =
649                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
650                    if let Some(dependency) = dependency {
651                        let mut forwarded = Vec::new();
652                        self.collect_export_names(&dependency, &mut forwarded, depth + 1)?;
653                        // `export *` never forwards `default` (§16.2.1.6.2).
654                        out.extend(forwarded.into_iter().filter(|name| name != "default"));
655                    }
656                }
657            }
658        }
659        Ok(())
660    }
661
662    /// The namespace object of `module`, built on first use.
663    ///
664    /// An ordinary object with one read-only getter per export, inserted in sorted order.
665    /// The getter reads the cell, which is what makes the binding live: `export let x`
666    /// followed by `x = 1` in the exporting module is visible here without copying.
667    pub fn module_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
668        if let Some(namespace) = module.with(|r| r.namespace.clone()) {
669            return Ok(Value::Object(namespace));
670        }
671        let names = self.module_export_names(module)?;
672        let proto = self.realm.object_proto.clone();
673        let function_proto = self.realm.function_proto.clone();
674        let namespace = self.new_object(Some(proto));
675        for name in &names {
676            let cell = self.resolve_export(module, name)?;
677            let getter = JsObject::function(
678                self.heap,
679                Some(function_proto.clone()),
680                Callable::ModuleBinding { cell },
681            );
682            namespace.define(
683                name,
684                Property {
685                    value: None,
686                    getter: Some(Value::Object(getter)),
687                    setter: None,
688                    writable: false,
689                    enumerable: true,
690                    configurable: false,
691                },
692            );
693        }
694        // A namespace reports `[object Module]`, and cannot gain properties.
695        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
696        let tag = self.string("Module");
697        namespace.define_key(&tag_key, Property::with_attributes(tag, false, false));
698        self.object_prevent_extensions(&namespace)?;
699        module.with_mut(|r| r.namespace = Some(namespace.clone()));
700        Ok(Value::Object(namespace))
701    }
702
703    /// Run `module`'s body, evaluating its dependencies first.
704    ///
705    /// Post-order, once each: a module already evaluated is skipped, which is what
706    /// §16.2.1.5.2.2's "evaluated or evaluating" guard amounts to, and what makes a cycle
707    /// terminate instead of recursing.
708    pub fn evaluate_module_body(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
709        if module.with(|r| r.status) == ModuleStatus::Evaluated {
710            return Ok(());
711        }
712        // Mark before recursing so a cycle stops here.
713        module.with_mut(|r| r.status = ModuleStatus::Evaluated);
714
715        let dependencies: Vec<Gc<ModuleRecord>> = module
716            .with(|r| r.dependencies.clone())
717            .into_iter()
718            .flatten()
719            .collect();
720        for dependency in dependencies {
721            self.evaluate_module_body(&dependency)?;
722        }
723
724        let Some(code) = module.with(|r| r.code.clone()) else {
725            // A JSON/text module has no body; its value is already in its cell.
726            return Ok(());
727        };
728        let name = module.with(|r| r.name.clone());
729        let env = self.module_env(module);
730        // The hoisted bindings already exist: `link_module` ran the prologue pass with a
731        // truthy `this`, which is what the guard in the compiled prefix detects. Here the
732        // receiver is `undefined`, so the body itself runs.
733        //
734        // A body with top-level `await` is compiled as an async function, so it answers a
735        // promise instead of a value. The evaluation is then driven to completion here:
736        // draining the queue is what advances the coroutine, and there is nothing else
737        // pending at this point, since module evaluation is what started it.
738        let async_body = code.code.kind.is_async();
739        self.module_stack.push(name);
740        let result = if async_body {
741            self.run_async_body(code, env, Value::Undefined)
742                .and_then(|promise| self.await_module_promise(promise))
743        } else {
744            self.execute(code, env, Value::Undefined, Vec::new(), Value::Undefined)
745        };
746        self.module_stack.pop();
747        result.map(|_| ()).inspect_err(|_| {
748            // A body that threw leaves the module unevaluated, so a later import of it
749            // retries rather than silently reporting success.
750            module.with_mut(|r| r.status = ModuleStatus::Linked);
751        })
752    }
753
754    /// Drive a module's own promise to a settled state.
755    ///
756    /// `js_execute_sync_module` in the reference does the same thing and calls a pending
757    /// promise an error ("promise is pending"); draining first is the difference, and it
758    /// is correct here because nothing else can be waiting: this runs before the host has
759    /// been given control, and the only queued jobs are the ones this body queued for
760    /// itself.
761    fn await_module_promise(&mut self, promise: Value) -> JsResult<Value> {
762        let Value::Object(promise) = promise else {
763            return Ok(Value::Undefined);
764        };
765        self.drain_jobs()?;
766        let state = self.promise_state(&promise);
767        let Some(state) = state else {
768            return Ok(Value::Undefined);
769        };
770        let status = state.borrow().status.clone();
771        match status {
772            crate::object::PromiseStatus::Fulfilled(value) => Ok(value),
773            crate::object::PromiseStatus::Rejected(reason) => Err(Signal::Throw(reason)),
774            crate::object::PromiseStatus::Pending => Err(Signal::Throw(self.make_error(
775                "TypeError",
776                "promise is pending: top-level await never settled",
777            ))),
778        }
779    }
780
781    /// `import(specifier)`: load, link, evaluate — asynchronously.
782    ///
783    /// The work happens in a job, because §13.3.10.1 makes dynamic import settle through
784    /// the promise machinery: `import("x").then(f)` must call `f` after the current
785    /// script finishes, never inside the `import` expression.
786    pub fn dynamic_import(&mut self, specifier: Value) -> JsResult<Value> {
787        let promise = self.new_promise();
788        let specifier = self.to_js_string(&specifier)?;
789        // Resolved relative to whatever is running the import — the reference asks
790        // `JS_GetScriptOrModuleName(ctx, 0)`, which is the innermost frame's file name and
791        // does not care whether that frame came from a module or a plain script.
792        //
793        // Only consulting the module stack (as this did) made every `import('./x.js')` from
794        // a *script* resolve against the working directory instead of the script's own
795        // directory, so `await import('./module-code_FIXTURE.js')` in test262's
796        // `dynamic-import` tests failed with "could not load module filename" for a file
797        // sitting right next to the test.
798        let referrer = self
799            .script_or_module_name()
800            .or_else(|| self.module_stack.last().cloned())
801            .or_else(|| self.main_module_name.clone())
802            .unwrap_or_default();
803        self.jobs.push_back(crate::interp::Job::Import {
804            specifier,
805            referrer,
806            promise: promise.clone(),
807        });
808        Ok(Value::Object(promise))
809    }
810
811    /// Evaluate a pending dynamic import and settle its promise.
812    pub fn run_dynamic_import(&mut self, specifier: &str, referrer: &str, promise: &Gc<JsObject>) {
813        let outcome = self
814            .load_module(specifier, &[], referrer)
815            .and_then(|module| {
816                self.link_module(&module)?;
817                let name = module.with(|r| r.name.clone());
818                self.module_stack.push(name);
819                let evaluated = self.evaluate_module_body(&module);
820                self.module_stack.pop();
821                evaluated?;
822                self.module_namespace(&module)
823            });
824        match outcome {
825            Ok(namespace) => self.fulfill_promise(promise, namespace),
826            Err(Signal::Throw(reason)) => self.reject_promise(promise, reason),
827            Err(other) => {
828                let _ = other;
829            }
830        }
831    }
832}
833
834/// The registry key for a module: its canonical name plus the attributes that decided
835/// what it means.
836///
837/// Without the attributes, `import m from "./x.json"` and
838/// `import m from "./x.json" with { type: "text" }` would collide on one record and the
839/// second import would silently receive the first one's value.
840fn cache_key(name: &str, attributes: &[(String, String)]) -> String {
841    if attributes.is_empty() {
842        return name.to_string();
843    }
844    let mut key = name.to_string();
845    for (key_name, value) in attributes {
846        key.push('\u{0}');
847        key.push_str(key_name);
848        key.push('=');
849        key.push_str(value);
850    }
851    key
852}
853
854/// Which kind of module `name` and `attributes` describe.
855///
856/// A `type` attribute wins; the `.json` suffix only decides when no attribute was given.
857/// That is what makes `import m from "./m.json" with { type: "text" }` a string while
858/// `import m from "./m.json"` is an object.
859fn module_kind(name: &str, attributes: &[(String, String)]) -> Result<ModuleKind, String> {
860    let declared = attributes
861        .iter()
862        .find(|(key, _)| key == "type")
863        .map(|(_, value)| value.as_str());
864    let kind = match declared {
865        // `json5` is accepted by the reference as an alias for a dialect that permits
866        // comments and trailing commas; this parser is strict JSON, so a document that
867        // needs the extension fails loudly rather than silently parsing differently.
868        Some("json") | Some("json5") => ModuleKind::Json,
869        Some("text") => ModuleKind::Text,
870        Some("bytes") => ModuleKind::Bytes,
871        // An unknown type is an error rather than a fallback to JavaScript: silently
872        // evaluating `with { type: "cbor" }` as code would run a data file.
873        Some(other) => return Err(format!("unsupported module type: '{other}'")),
874        None => {
875            if name.ends_with(".json") {
876                ModuleKind::Json
877            } else {
878                ModuleKind::JavaScript
879            }
880        }
881    };
882    Ok(kind)
883}