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        let program = match js_parse::parse_module(source) {
244            Ok(program) => program,
245            Err(error) => {
246                return Err(Signal::Throw(self.make_error(
247                    "SyntaxError",
248                    &format!("{}: {}", loaded.name, error.message),
249                )));
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.make_error(
256                    "SyntaxError",
257                    &format!("{}: {}", loaded.name, error.message),
258                )));
259            }
260        };
261        code.set_filename(&loaded.name);
262        let meta = code
263            .module
264            .as_ref()
265            .map(|meta| (**meta).clone())
266            .unwrap_or_default();
267        let closure_vars = code.closure_vars.clone();
268        let compiled = Gc::new(self.heap, CompiledCode::new(code));
269        // One cell per closure variable. A lexical binding starts in its dead zone and a
270        // `var` as `undefined`; an import's cell is *replaced* during linking by the
271        // exporter's, which is what makes it live.
272        let mut cells = Vec::with_capacity(closure_vars.len());
273        for closure_var in &closure_vars {
274            let initial = if closure_var.is_lexical {
275                Value::Uninitialized
276            } else {
277                Value::Undefined
278            };
279            cells.push(self.new_cell(initial));
280        }
281        let dependencies = vec![None; meta.requests.len()];
282        let record = Gc::new(
283            self.heap,
284            ModuleRecord::new(ModuleInner {
285                name: loaded.name.clone(),
286                url: loaded.url.clone(),
287                code: Some(compiled),
288                meta,
289                cells,
290                dependencies,
291                status: ModuleStatus::Unlinked,
292                kind: ModuleKind::JavaScript,
293                namespace: None,
294                import_meta: None,
295            }),
296        );
297        self.install_import_meta(&record)?;
298        Ok(record)
299    }
300
301    /// A JSON, text or bytes module: one value, exported as `default`.
302    ///
303    /// The value is produced by calling the *builtin* rather than by reaching into the
304    /// JSON parser or the typed-array internals, so a data module behaves exactly like
305    /// `JSON.parse(text)` or `new Uint8Array(bytes)` written out by hand — one
306    /// implementation of each, not two.
307    fn data_module_record(
308        &mut self,
309        loaded: &LoadedModule,
310        kind: ModuleKind,
311    ) -> JsResult<Gc<ModuleRecord>> {
312        let value = match kind {
313            ModuleKind::Json => {
314                let text = String::from_utf8_lossy(&loaded.source).to_string();
315                let Some(json) = self.global_value("JSON") else {
316                    return Err(Signal::Throw(
317                        self.make_error("InternalError", "JSON is not installed"),
318                    ));
319                };
320                let Some(Value::Object(json)) = Some(json) else {
321                    unreachable!()
322                };
323                let Some(parse) = self.get_property(&json, "parse")? else {
324                    return Err(Signal::Throw(
325                        self.make_error("InternalError", "JSON.parse is not installed"),
326                    ));
327                };
328                let text = self.string(&text);
329                match self.call_value(parse, Value::Object(json), vec![text]) {
330                    Ok(value) => value,
331                    Err(Signal::Throw(reason)) => {
332                        let detail = self.describe_exception(&reason);
333                        return Err(Signal::Throw(self.make_error(
334                            "SyntaxError",
335                            &format!("{}: {}", loaded.name, detail),
336                        )));
337                    }
338                    Err(other) => return Err(other),
339                }
340            }
341            ModuleKind::Text => {
342                // Taken as UTF-8 with replacement: a text file that is not valid UTF-8
343                // still has to become a string.
344                let text = String::from_utf8_lossy(&loaded.source).to_string();
345                self.string(&text)
346            }
347            ModuleKind::Bytes => {
348                let numbers: Vec<Value> = loaded
349                    .source
350                    .iter()
351                    .map(|byte| Value::Int(*byte as i32))
352                    .collect();
353                let elements = self.new_array(numbers);
354                let Some(Value::Object(ctor)) = self.global_value("Uint8Array") else {
355                    return Err(Signal::Throw(
356                        self.make_error("InternalError", "Uint8Array is not installed"),
357                    ));
358                };
359                self.construct(
360                    Value::Object(ctor),
361                    Value::Object(elements.clone()),
362                    vec![Value::Object(elements)],
363                )?
364            }
365            ModuleKind::JavaScript => unreachable!("handled by `compile_module_record`"),
366        };
367        let cell = self.new_cell(value.clone());
368        let record = Gc::new(
369            self.heap,
370            ModuleRecord::new(ModuleInner {
371                name: loaded.name.clone(),
372                url: loaded.url.clone(),
373                code: None,
374                meta: js_compile::bytecode::ModuleMeta {
375                    requests: Vec::new(),
376                    imports: Vec::new(),
377                    exports: vec![js_compile::bytecode::ExportEntry::Local {
378                        export_name: "default".to_string(),
379                        var_idx: 0,
380                    }],
381                },
382                cells: vec![cell],
383                dependencies: Vec::new(),
384                // Nothing to link and nothing to run: a data module is born evaluated,
385                // which is what lets `import x from "./m.json"` work inside a cycle.
386                status: ModuleStatus::Evaluated,
387                kind,
388                namespace: None,
389                import_meta: None,
390            }),
391        );
392        Ok(record)
393    }
394
395    /// A binding of the global object, if it exists.
396    fn global_value(&mut self, name: &str) -> Option<Value> {
397        let global = self.realm.global.clone();
398        self.get_property(&global, name).ok().flatten()
399    }
400
401    /// `import.meta` for `record`, built once.
402    fn install_import_meta(&mut self, record: &Gc<ModuleRecord>) -> JsResult<()> {
403        let proto = self.realm.object_proto.clone();
404        let meta = self.new_object(Some(proto));
405        let url = self.string(record.with(|r| r.url.clone()));
406        // Only the two properties the reference defines; a script can add its own.
407        meta.define_data("url", url);
408        meta.define_data("main", Value::Bool(false));
409        record.with_mut(|r| r.import_meta = Some(meta));
410        Ok(())
411    }
412
413    /// Resolve every import of `module` and validate its exports, depth-first.
414    pub fn link_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
415        match module.with(|r| r.status) {
416            // Already linked, or being linked right now — the latter is a cycle, and it is
417            // exactly why the status is set *before* recursing: a cycle stops here rather
418            // than recursing forever.
419            ModuleStatus::Linking | ModuleStatus::Linked | ModuleStatus::Evaluated => {
420                return Ok(());
421            }
422            ModuleStatus::Unlinked => {}
423        }
424        module.with_mut(|r| r.status = ModuleStatus::Linking);
425
426        let requests = module.with(|r| r.meta.requests.clone());
427        for (index, request) in requests.iter().enumerate() {
428            let referrer = module.with(|r| r.name.clone());
429            let dependency =
430                self.load_module(&request.specifier, &request.attributes, &referrer)?;
431            module.with_mut(|r| r.dependencies[index] = Some(dependency.clone()));
432            self.link_module(&dependency)?;
433        }
434
435        // Wire the cells. `import { x } from "m"` makes this module's cell *be* `m`'s, so
436        // a later assignment over there is visible here with no copying.
437        let imports = module.with(|r| r.meta.imports.clone());
438        for entry in &imports {
439            let dependency =
440                module.with(|r| r.dependencies.get(entry.module as usize).cloned().flatten());
441            let Some(dependency) = dependency else {
442                return Err(Signal::Throw(self.make_error(
443                    "InternalError",
444                    "an import names a module that was not loaded",
445                )));
446            };
447            if entry.is_star {
448                let namespace = self.module_namespace(&dependency)?;
449                let cell = module.with(|r| r.cells[entry.var_idx as usize].clone());
450                cell.set(namespace);
451                continue;
452            }
453            let cell = self.resolve_export(&dependency, &entry.name)?;
454            module.with_mut(|r| r.cells[entry.var_idx as usize] = cell);
455        }
456
457        // Validate: `export { a } from "m"` where `m` has no `a` is a link error, and
458        // saying so now beats an `undefined` that surfaces much later.
459        let exports = module.with(|r| r.meta.exports.clone());
460        for entry in &exports {
461            if let js_compile::bytecode::ExportEntry::Indirect {
462                export_name,
463                module: index,
464                import_name,
465            } = entry
466            {
467                let dependency =
468                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
469                let Some(dependency) = dependency else {
470                    continue;
471                };
472                if self.resolve_export(&dependency, import_name).is_err() {
473                    let dependency_name = dependency.with(|r| r.name.clone());
474                    return Err(Signal::Throw(self.make_error(
475                        "SyntaxError",
476                        &format!(
477                            "Could not find export '{import_name}' in module '{dependency_name}' (re-exported as '{export_name}')"
478                        ),
479                    )));
480                }
481            }
482        }
483
484        // Create the module's hoisted bindings *now*, while linking — before any body
485        // runs anywhere in the graph.
486        //
487        // This is the whole trick behind cyclic imports. The body's prologue is
488        // `push_this; if_false <body>`, so calling it with a truthy `this` runs only the
489        // hoisted declarations and returns. Doing that for every module during linking
490        // means that when evaluation finally starts, every exported function in the
491        // cycle already exists — which is why `b.js` can see `a`'s function even though
492        // `a.js` has not run yet.
493        self.hoist_module_bindings(module)?;
494
495        module.with_mut(|r| r.status = ModuleStatus::Linked);
496        Ok(())
497    }
498
499    /// Run `module`'s prologue only, creating its hoisted bindings.
500    fn hoist_module_bindings(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
501        let Some(code) = module.with(|r| r.code.clone()) else {
502            // A JSON/text module has nothing to hoist.
503            return Ok(());
504        };
505        let env = self.module_env(module);
506        self.execute(code, env, Value::Bool(true), Vec::new(), Value::Undefined)
507            .map(|_| ())
508    }
509
510    /// The closure environment a module body runs in: one cell per closure variable.
511    fn module_env(&mut self, module: &Gc<ModuleRecord>) -> Gc<ClosureEnv> {
512        let cells = module.with(|r| r.cells.clone());
513        Gc::new(
514            self.heap,
515            ClosureEnv {
516                cells,
517                eval_scope: None,
518                local_vars: None,
519                local_phase: 0,
520            },
521        )
522    }
523
524    /// The cell behind `name` in `module`, following re-exports.
525    pub fn resolve_export(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Gc<Cell>> {
526        self.resolve_export_inner(module, name, 0)
527    }
528
529    fn resolve_export_inner(
530        &mut self,
531        module: &Gc<ModuleRecord>,
532        name: &str,
533        depth: usize,
534    ) -> JsResult<Gc<Cell>> {
535        // A pathological chain (`a` exports from `b`, `b` from `a`) would otherwise
536        // recurse until the Rust stack gives out.
537        if depth > 64 {
538            return Err(Signal::Throw(
539                self.make_error("SyntaxError", "circular re-export chain"),
540            ));
541        }
542        let exports = module.with(|r| r.meta.exports.clone());
543        // An explicit export wins over any `export *`.
544        for entry in &exports {
545            match entry {
546                js_compile::bytecode::ExportEntry::Local {
547                    export_name,
548                    var_idx,
549                } if export_name == name => {
550                    return Ok(module.with(|r| r.cells[*var_idx as usize].clone()));
551                }
552                js_compile::bytecode::ExportEntry::Indirect {
553                    export_name,
554                    module: index,
555                    import_name,
556                } if export_name == name => {
557                    let dependency =
558                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
559                    let Some(dependency) = dependency else {
560                        return Err(self.missing_export(module, name));
561                    };
562                    return self.resolve_export_inner(&dependency, import_name, depth + 1);
563                }
564                js_compile::bytecode::ExportEntry::StarAs { export_name, .. }
565                    if export_name == name =>
566                {
567                    // The namespace of the re-exported module, wrapped in a cell so the
568                    // export table stays uniform. A fresh cell each time is harmless:
569                    // nothing can assign through it.
570                    let namespace = self.star_namespace(module, name)?;
571                    return Ok(self.new_cell(namespace));
572                }
573                _ => {}
574            }
575        }
576        // `export * from "m"`: forwarded names are visible only if nothing above claimed
577        // them, which is why this is a second pass.
578        for entry in &exports {
579            if let js_compile::bytecode::ExportEntry::Star { module: index } = entry {
580                let dependency =
581                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
582                let Some(dependency) = dependency else {
583                    continue;
584                };
585                if let Ok(cell) = self.resolve_export_inner(&dependency, name, depth + 1) {
586                    return Ok(cell);
587                }
588            }
589        }
590        Err(self.missing_export(module, name))
591    }
592
593    fn missing_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
594        let module_name = module.with(|r| r.name.clone());
595        // The reference's wording, kept verbatim: an error message is part of the
596        // behaviour a user sees, and `qjs` says "Could not find export".
597        Signal::Throw(self.make_error(
598            "SyntaxError",
599            &format!("Could not find export '{name}' in module '{module_name}'"),
600        ))
601    }
602
603    /// The namespace behind `export * as ns from "m"`.
604    fn star_namespace(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Value> {
605        let exports = module.with(|r| r.meta.exports.clone());
606        for entry in &exports {
607            if let js_compile::bytecode::ExportEntry::StarAs {
608                export_name,
609                module: index,
610            } = entry
611                && export_name == name
612            {
613                let dependency =
614                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
615                let Some(dependency) = dependency else {
616                    continue;
617                };
618                return self.module_namespace(&dependency);
619            }
620        }
621        Ok(Value::Undefined)
622    }
623
624    /// The names `module` exports, sorted the way §16.2.1.6 requires.
625    pub fn module_export_names(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Vec<String>> {
626        let mut names: Vec<String> = Vec::new();
627        self.collect_export_names(module, &mut names, 0)?;
628        names.sort();
629        names.dedup();
630        Ok(names)
631    }
632
633    fn collect_export_names(
634        &mut self,
635        module: &Gc<ModuleRecord>,
636        out: &mut Vec<String>,
637        depth: usize,
638    ) -> JsResult<()> {
639        if depth > 64 {
640            return Ok(());
641        }
642        let exports = module.with(|r| r.meta.exports.clone());
643        for entry in &exports {
644            match entry {
645                js_compile::bytecode::ExportEntry::Local { export_name, .. }
646                | js_compile::bytecode::ExportEntry::Indirect { export_name, .. }
647                | js_compile::bytecode::ExportEntry::StarAs { export_name, .. } => {
648                    out.push(export_name.clone());
649                }
650                js_compile::bytecode::ExportEntry::Star { module: index } => {
651                    let dependency =
652                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
653                    if let Some(dependency) = dependency {
654                        let mut forwarded = Vec::new();
655                        self.collect_export_names(&dependency, &mut forwarded, depth + 1)?;
656                        // `export *` never forwards `default` (§16.2.1.6.2).
657                        out.extend(forwarded.into_iter().filter(|name| name != "default"));
658                    }
659                }
660            }
661        }
662        Ok(())
663    }
664
665    /// The namespace object of `module`, built on first use.
666    ///
667    /// An ordinary object with one read-only getter per export, inserted in sorted order.
668    /// The getter reads the cell, which is what makes the binding live: `export let x`
669    /// followed by `x = 1` in the exporting module is visible here without copying.
670    pub fn module_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
671        if let Some(namespace) = module.with(|r| r.namespace.clone()) {
672            return Ok(Value::Object(namespace));
673        }
674        let names = self.module_export_names(module)?;
675        let proto = self.realm.object_proto.clone();
676        let function_proto = self.realm.function_proto.clone();
677        let namespace = self.new_object(Some(proto));
678        for name in &names {
679            let cell = self.resolve_export(module, name)?;
680            let getter = JsObject::function(
681                self.heap,
682                Some(function_proto.clone()),
683                Callable::ModuleBinding { cell },
684            );
685            namespace.define(
686                name,
687                Property {
688                    value: None,
689                    getter: Some(Value::Object(getter)),
690                    setter: None,
691                    writable: false,
692                    enumerable: true,
693                    configurable: false,
694                },
695            );
696        }
697        // A namespace reports `[object Module]`, and cannot gain properties.
698        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
699        let tag = self.string("Module");
700        namespace.define_key(&tag_key, Property::with_attributes(tag, false, false));
701        self.object_prevent_extensions(&namespace)?;
702        module.with_mut(|r| r.namespace = Some(namespace.clone()));
703        Ok(Value::Object(namespace))
704    }
705
706    /// Run `module`'s body, evaluating its dependencies first.
707    ///
708    /// Post-order, once each: a module already evaluated is skipped, which is what
709    /// §16.2.1.5.2.2's "evaluated or evaluating" guard amounts to, and what makes a cycle
710    /// terminate instead of recursing.
711    pub fn evaluate_module_body(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
712        if module.with(|r| r.status) == ModuleStatus::Evaluated {
713            return Ok(());
714        }
715        // Mark before recursing so a cycle stops here.
716        module.with_mut(|r| r.status = ModuleStatus::Evaluated);
717
718        let dependencies: Vec<Gc<ModuleRecord>> = module
719            .with(|r| r.dependencies.clone())
720            .into_iter()
721            .flatten()
722            .collect();
723        for dependency in dependencies {
724            self.evaluate_module_body(&dependency)?;
725        }
726
727        let Some(code) = module.with(|r| r.code.clone()) else {
728            // A JSON/text module has no body; its value is already in its cell.
729            return Ok(());
730        };
731        let name = module.with(|r| r.name.clone());
732        let env = self.module_env(module);
733        // The hoisted bindings already exist: `link_module` ran the prologue pass with a
734        // truthy `this`, which is what the guard in the compiled prefix detects. Here the
735        // receiver is `undefined`, so the body itself runs.
736        //
737        // A body with top-level `await` is compiled as an async function, so it answers a
738        // promise instead of a value. The evaluation is then driven to completion here:
739        // draining the queue is what advances the coroutine, and there is nothing else
740        // pending at this point, since module evaluation is what started it.
741        let async_body = code.code.kind.is_async();
742        self.module_stack.push(name);
743        let result = if async_body {
744            self.run_async_body(code, env)
745                .and_then(|promise| self.await_module_promise(promise))
746        } else {
747            self.execute(code, env, Value::Undefined, Vec::new(), Value::Undefined)
748        };
749        self.module_stack.pop();
750        result.map(|_| ()).inspect_err(|_| {
751            // A body that threw leaves the module unevaluated, so a later import of it
752            // retries rather than silently reporting success.
753            module.with_mut(|r| r.status = ModuleStatus::Linked);
754        })
755    }
756
757    /// Drive a module's own promise to a settled state.
758    ///
759    /// `js_execute_sync_module` in the reference does the same thing and calls a pending
760    /// promise an error ("promise is pending"); draining first is the difference, and it
761    /// is correct here because nothing else can be waiting: this runs before the host has
762    /// been given control, and the only queued jobs are the ones this body queued for
763    /// itself.
764    fn await_module_promise(&mut self, promise: Value) -> JsResult<Value> {
765        let Value::Object(promise) = promise else {
766            return Ok(Value::Undefined);
767        };
768        self.drain_jobs()?;
769        let state = self.promise_state(&promise);
770        let Some(state) = state else {
771            return Ok(Value::Undefined);
772        };
773        let status = state.borrow().status.clone();
774        match status {
775            crate::object::PromiseStatus::Fulfilled(value) => Ok(value),
776            crate::object::PromiseStatus::Rejected(reason) => Err(Signal::Throw(reason)),
777            crate::object::PromiseStatus::Pending => Err(Signal::Throw(self.make_error(
778                "TypeError",
779                "promise is pending: top-level await never settled",
780            ))),
781        }
782    }
783
784    /// `import(specifier)`: load, link, evaluate — asynchronously.
785    ///
786    /// The work happens in a job, because §13.3.10.1 makes dynamic import settle through
787    /// the promise machinery: `import("x").then(f)` must call `f` after the current
788    /// script finishes, never inside the `import` expression.
789    pub fn dynamic_import(&mut self, specifier: Value) -> JsResult<Value> {
790        let promise = self.new_promise();
791        let specifier = self.to_js_string(&specifier)?;
792        // Resolved relative to the module that ran the import, which is the innermost
793        // module body on the stack.
794        let referrer = self
795            .module_stack
796            .last()
797            .cloned()
798            .or_else(|| self.main_module_name.clone())
799            .unwrap_or_default();
800        self.jobs.push_back(crate::interp::Job::Import {
801            specifier,
802            referrer,
803            promise: promise.clone(),
804        });
805        Ok(Value::Object(promise))
806    }
807
808    /// Evaluate a pending dynamic import and settle its promise.
809    pub fn run_dynamic_import(&mut self, specifier: &str, referrer: &str, promise: &Gc<JsObject>) {
810        let outcome = self
811            .load_module(specifier, &[], referrer)
812            .and_then(|module| {
813                self.link_module(&module)?;
814                let name = module.with(|r| r.name.clone());
815                self.module_stack.push(name);
816                let evaluated = self.evaluate_module_body(&module);
817                self.module_stack.pop();
818                evaluated?;
819                self.module_namespace(&module)
820            });
821        match outcome {
822            Ok(namespace) => self.fulfill_promise(promise, namespace),
823            Err(Signal::Throw(reason)) => self.reject_promise(promise, reason),
824            Err(other) => {
825                let _ = other;
826            }
827        }
828    }
829}
830
831/// The registry key for a module: its canonical name plus the attributes that decided
832/// what it means.
833///
834/// Without the attributes, `import m from "./x.json"` and
835/// `import m from "./x.json" with { type: "text" }` would collide on one record and the
836/// second import would silently receive the first one's value.
837fn cache_key(name: &str, attributes: &[(String, String)]) -> String {
838    if attributes.is_empty() {
839        return name.to_string();
840    }
841    let mut key = name.to_string();
842    for (key_name, value) in attributes {
843        key.push('\u{0}');
844        key.push_str(key_name);
845        key.push('=');
846        key.push_str(value);
847    }
848    key
849}
850
851/// Which kind of module `name` and `attributes` describe.
852///
853/// A `type` attribute wins; the `.json` suffix only decides when no attribute was given.
854/// That is what makes `import m from "./m.json" with { type: "text" }` a string while
855/// `import m from "./m.json"` is an object.
856fn module_kind(name: &str, attributes: &[(String, String)]) -> Result<ModuleKind, String> {
857    let declared = attributes
858        .iter()
859        .find(|(key, _)| key == "type")
860        .map(|(_, value)| value.as_str());
861    let kind = match declared {
862        // `json5` is accepted by the reference as an alias for a dialect that permits
863        // comments and trailing commas; this parser is strict JSON, so a document that
864        // needs the extension fails loudly rather than silently parsing differently.
865        Some("json") | Some("json5") => ModuleKind::Json,
866        Some("text") => ModuleKind::Text,
867        Some("bytes") => ModuleKind::Bytes,
868        // An unknown type is an error rather than a fallback to JavaScript: silently
869        // evaluating `with { type: "cbor" }` as code would run a data file.
870        Some(other) => return Err(format!("unsupported module type: '{other}'")),
871        None => {
872            if name.ends_with(".json") {
873                ModuleKind::Json
874            } else {
875                ModuleKind::JavaScript
876            }
877        }
878    };
879    Ok(kind)
880}