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};
27use js_compile::bytecode::Function as CompiledFunction;
28use js_parse::ast::ImportPhase;
29
30/// The reference's textual specifier rule, shared with the AOT bundler.
31///
32/// See [`js_parse::normalize_specifier`]: the loader and the bundler have to agree on a
33/// module's name, or a product reports "could not load module filename" for a module it is
34/// carrying.
35pub use js_parse::normalize_specifier;
36
37/// Where a module is in its lifetime.
38///
39/// `Linking` and `Evaluated` are not just bookkeeping: they are what makes a cycle
40/// terminate. A cycle is not an error — it is a graph that must be *linked* depth-first
41/// and then *evaluated* in post-order, and the two-phase split is the mechanism.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum ModuleStatus {
44    /// Loaded and compiled; imports not yet resolved.
45    Unlinked,
46    /// Being linked, so a re-entrant link must not recurse.
47    Linking,
48    /// Imports resolved and exports validated.
49    Linked,
50    /// Body running right now.
51    ///
52    /// Distinct from [`ModuleStatus::Evaluated`] because the deferred-import proposal asks
53    /// the difference: `ReadyForSyncExecution` answers *false* for a module that is
54    /// `~evaluating~`, and the only way a namespace read can observe that is if the two
55    /// states are not the same flag. A re-entrant evaluation still stops at either.
56    Evaluating,
57    /// Body has run to completion, or has failed.
58    ///
59    /// A body that threw is `Evaluated` too — §16.2.1.5.3.1 records the completion in
60    /// `[[EvaluationError]]` and marks the module evaluated, so a second attempt reports
61    /// the *same* exception object rather than running the body again.
62    Evaluated,
63}
64
65/// How a module's source became a module.
66///
67/// A JSON or text module is not code at all — it is one value exported as `default` — so
68/// it has no body and no imports, which is why this is a flag rather than a second type.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum ModuleKind {
71    /// JavaScript: has a compiled body.
72    JavaScript,
73    /// A parsed JSON document, exported as `default`.
74    Json,
75    /// A plain string, exported as `default`.
76    Text,
77    /// A `Uint8Array`, exported as `default`.
78    Bytes,
79    /// A native module: exports supplied by the host, with no source at all.
80    ///
81    /// This is the C API's `JS_NewCModule`. The values are already built when the module
82    /// appears, so the record is born evaluated — the same shape a data module has, with
83    /// several exports instead of one.
84    Native,
85}
86
87/// One loaded module.
88///
89/// Held on the GC heap because its cells and namespace are GC values. The whole record is
90/// behind interior mutability the same way a [`Cell`] is: linking writes into it while
91/// other modules already hold references to it.
92pub struct ModuleRecord {
93    inner: std::cell::RefCell<ModuleInner>,
94}
95
96impl ModuleRecord {
97    /// Build a record around `inner`.
98    pub fn new(inner: ModuleInner) -> ModuleRecord {
99        ModuleRecord {
100            inner: std::cell::RefCell::new(inner),
101        }
102    }
103
104    /// Run `f` with the record borrowed.
105    pub fn with<R>(&self, f: impl FnOnce(&ModuleInner) -> R) -> R {
106        f(&self.inner.borrow())
107    }
108
109    /// Run `f` with the record borrowed mutably.
110    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ModuleInner) -> R) -> R {
111        f(&mut self.inner.borrow_mut())
112    }
113
114    /// Whether the module's body contains a top-level `await`.
115    ///
116    /// §16.2.1.5.3.1's `[[HasTLA]]`. A body with one compiles to an async function, so the
117    /// flag is the compiled kind rather than a second piece of bookkeeping: the two can
118    /// never disagree.
119    pub fn has_tla(&self) -> bool {
120        self.with(|r| {
121            r.code
122                .as_ref()
123                .is_some_and(|code| code.code.kind.is_async())
124        })
125    }
126}
127
128/// Everything a module record holds; see [`ModuleRecord`].
129pub struct ModuleInner {
130    /// Canonical identity: the cache key, and what a cycle compares.
131    pub name: String,
132    /// What `import.meta.url` reports.
133    pub url: String,
134    /// The compiled body, or `None` for a JSON/text/bytes module.
135    pub code: Option<Gc<CompiledCode>>,
136    /// The tables the compiler produced.
137    pub meta: js_compile::bytecode::ModuleMeta,
138    /// One cell per closure variable of the body; the body reads its bindings here.
139    pub cells: Vec<Gc<Cell>>,
140    /// Resolved dependencies, parallel to `meta.requests`.
141    pub dependencies: Vec<Option<Gc<ModuleRecord>>>,
142    /// Where it is in its lifetime.
143    pub status: ModuleStatus,
144    /// The completion of a body that threw, rethrown on every later attempt.
145    ///
146    /// §16.2.1.5.3.1 stores the *abrupt completion* on the record. Without it a second
147    /// read through a deferred namespace ran the body again and produced a second, equal,
148    /// but not identical error object — which `import-defer/errors/module-throws` compares
149    /// by identity.
150    pub evaluation_error: Option<Value>,
151    /// What kind of module it is.
152    pub kind: ModuleKind,
153    /// The namespace object, built on first use.
154    pub namespace: Option<Gc<JsObject>>,
155    /// The deferred namespace object, built on first use.
156    ///
157    /// A second object rather than a flag on the first: the deferred namespace's whole
158    /// point is that reading it evaluates the module, and the eager one must stay usable on
159    /// a module that is still `Linked`. It is cached here so two `import defer` clauses for
160    /// one module hand back the same object, which the proposal requires.
161    pub deferred_namespace: Option<Gc<JsObject>>,
162    /// `import.meta`, built at load time.
163    pub import_meta: Option<Gc<JsObject>>,
164    /// The wrapper cell behind each `export * as ns from "m"`, keyed by `ns`.
165    ///
166    /// §16.2.1.6.3 `ResolveExport` identifies a binding by *(module, name)*, and the
167    /// ambiguity test compares those identities. A namespace re-export needs a cell in the
168    /// export table, and building a fresh one per lookup gave the same export two different
169    /// identities — so a name reached through two `export *` that both pass through one
170    /// `export * as ns` looked ambiguous. Caching makes the identity stable, which is what
171    /// `namespace-unambiguous-if-export-star-as-from` checks.
172    pub star_cells: BTreeMap<String, Gc<Cell>>,
173}
174
175impl Trace for ModuleRecord {
176    fn trace(&self, tracer: &mut Tracer) {
177        self.inner.borrow().trace(tracer);
178    }
179}
180
181impl Trace for ModuleInner {
182    fn trace(&self, tracer: &mut Tracer) {
183        if let Some(code) = &self.code {
184            tracer.visit(code);
185        }
186        for cell in &self.cells {
187            tracer.visit(cell);
188        }
189        for dependency in self.dependencies.iter().flatten() {
190            tracer.visit(dependency);
191        }
192        if let Some(namespace) = &self.namespace {
193            tracer.visit(namespace);
194        }
195        if let Some(namespace) = &self.deferred_namespace {
196            tracer.visit(namespace);
197        }
198        if let Some(error) = &self.evaluation_error {
199            error.trace(tracer);
200        }
201        if let Some(meta) = &self.import_meta {
202            tracer.visit(meta);
203        }
204    }
205}
206
207/// A host-supplied module, before it is compiled.
208pub struct LoadedModule {
209    /// Canonical identity — the cache key, and how a cycle recognises itself.
210    pub name: String,
211    /// `import.meta.url` for this module.
212    pub url: String,
213    /// The file's bytes. Not necessarily UTF-8: a `bytes` module is arbitrary.
214    pub source: Vec<u8>,
215}
216
217/// How the host turns a specifier into bytes.
218///
219/// The engine cannot do this itself: resolving `./x.js` needs to know that the importer
220/// was a file, and where. A browser-shaped host would answer differently, so the host
221/// supplies this and the engine decides what to do with the bytes.
222pub trait ModuleLoader {
223    /// Resolve `specifier` relative to `referrer` and read it.
224    ///
225    /// `referrer` is empty for the entry module.
226    fn load(
227        &self,
228        specifier: &str,
229        attributes: &[(String, String)],
230        referrer: &str,
231    ) -> Result<LoadedModule, String>;
232
233    /// Load a native module, if this loader has one at `name`.
234    ///
235    /// The answer is a *record*, not bytes: a `.so` is not text to compile, it is a library
236    /// that hands back exports. `None` means "this name is not native", which sends the
237    /// engine on to [`ModuleLoader::load`] — so a loader that knows nothing about native
238    /// modules needs no change at all.
239    ///
240    /// `interp` is the interpreter doing the load, because the library's entry point takes
241    /// a `JSContext *` and will call back into this very interpreter.
242    fn load_native(
243        &self,
244        interp: &mut Interp<'_>,
245        name: &str,
246    ) -> Option<Result<Gc<ModuleRecord>, String>> {
247        let _ = (interp, name);
248        None
249    }
250
251    /// The name `specifier` resolves to from `referrer`, without reading anything.
252    ///
253    /// A precompiled module is registered under the name a *loader* would give it, so the
254    /// engine has to know that name before it can decide whether the module is already in
255    /// memory. Without this the only way to ask is [`ModuleLoader::load`], which reads the
256    /// file — and a product that carries its dependencies has no files to read.
257    ///
258    /// `None` means "this loader can only answer by loading", which is the behaviour a
259    /// loader that resolves against something other than text (an in-memory map, a
260    /// network) legitimately has. Precompiled modules are then matched after the load, by
261    /// the name the load reported.
262    fn resolve(&self, specifier: &str, referrer: &str) -> Option<String> {
263        let _ = (specifier, referrer);
264        None
265    }
266}
267
268/// What `ResolveExport` answered, including the two ways it can fail to name a binding.
269///
270/// §16.2.1.6.3 distinguishes them and so must the caller: **not found** is a missing export,
271/// while **ambiguous** is a module that must fail to link even though the name exists twice.
272/// Collapsing both into `Err` is what let the star loop treat an ambiguity as absence and
273/// resolve the name to whichever dependency happened to be listed first.
274enum Resolution {
275    Cell {
276        cell: Gc<Cell>,
277        /// The module the binding actually lives in.
278        module: Gc<ModuleRecord>,
279        /// Its name there — `*namespace*` for a namespace re-export.
280        binding: String,
281    },
282    NotFound,
283    Ambiguous,
284}
285
286impl Resolution {
287    /// Whether two resolutions name the **same binding**.
288    ///
289    /// §16.2.1.6.3 compares `[[Module]]` and `[[BindingName]]`, nothing else: two
290    /// `export *` paths that arrive at one binding are not ambiguous, and two paths that
291    /// arrive at different bindings are. Comparing the export *cells* instead was wrong for
292    /// `export * as ns from "m"`, where the cell belongs to the re-exporting module while the
293    /// binding belongs to `m` — so two modules that both re-export the same namespace looked
294    /// like two different bindings.
295    fn same_binding(&self, other: &Resolution) -> bool {
296        match (self, other) {
297            (
298                Resolution::Cell {
299                    module: a,
300                    binding: a_name,
301                    ..
302                },
303                Resolution::Cell {
304                    module: b,
305                    binding: b_name,
306                    ..
307                },
308            ) => a.ptr_eq(b) && a_name == b_name,
309            _ => false,
310        }
311    }
312}
313
314impl<'a> Interp<'a> {
315    /// The module registry: one entry per canonical name, so each file is compiled once.
316    pub fn module_registry(&self) -> &BTreeMap<String, Gc<ModuleRecord>> {
317        &self.modules
318    }
319
320    /// Evaluate `specifier` as the entry module, the way `qjs -m file.js` does.
321    pub fn run_main_module(&mut self, specifier: &str) -> JsResult<Value> {
322        let module = self.load_module(specifier, &[], "")?;
323        let name = module.with(|r| r.name.clone());
324        self.main_module_name = Some(name.clone());
325        // The record was built before the name was known, so `main` is stamped now.
326        if let Some(meta) = module.with(|r| r.import_meta.clone()) {
327            meta.define_data("main", Value::Bool(true));
328        }
329        self.link_module(&module)?;
330        self.module_stack.push(name);
331        let result = self.evaluate_module_body(&module);
332        self.module_stack.pop();
333        result?;
334        self.module_namespace(&module)
335    }
336
337    /// Run a module whose bytecode the caller already has.
338    ///
339    /// This is `qjs`'s `-m` for an AOT binary: nothing is parsed or compiled, but the
340    /// module's *requests* still go through the host loader, so a precompiled entry
341    /// module can import ordinary source files. The blob's own file name is what those
342    /// requests are resolved against, which is why it has to travel in the blob rather
343    /// than be supplied at the call site.
344    pub fn run_precompiled_module(&mut self, code: CompiledFunction) -> JsResult<Value> {
345        let name = code
346            .filename
347            .clone()
348            .unwrap_or_else(|| "<bytecode>".to_string());
349        let url = name.clone();
350        let module = self.module_record_from_code(&name, &url, code)?;
351        self.main_module_name = Some(name.clone());
352        // Registered under its own name before linking, so a module that imports itself
353        // finds this record instead of re-entering the loader for a file that may not
354        // exist at all.
355        self.modules.insert(cache_key(&name, &[]), module.clone());
356        if let Some(meta) = module.with(|r| r.import_meta.clone()) {
357            meta.define_data("main", Value::Bool(true));
358        }
359        self.link_module(&module)?;
360        self.module_stack.push(name);
361        let result = self.evaluate_module_body(&module);
362        self.module_stack.pop();
363        result?;
364        self.module_namespace(&module)
365    }
366
367    /// Register a module from bytecode, so a later import finds it without a loader.
368    ///
369    /// This is what an AOT product does with the modules it carries: the names are the
370    /// ones the *bundler* resolved, which are the ones this interpreter would have
371    /// resolved through the loader, so an `import "./dep.js"` lands here instead of on the
372    /// filesystem.
373    ///
374    /// The module is registered as `Unlinked`: nothing is wired up until something imports
375    /// it (or it is the entry), which is what keeps a bundle's registration order
376    /// irrelevant — a cycle among precompiled modules links the same way a cycle among
377    /// source files does.
378    pub fn register_module(&mut self, code: CompiledFunction) -> JsResult<String> {
379        let name = code.filename.clone().ok_or_else(|| {
380            Signal::Throw(self.make_error(
381                "InternalError",
382                "precompiled module has no name; it was serialized without its file name",
383            ))
384        })?;
385        let url = name.clone();
386        let record = self.module_record_from_code(&name, &url, code)?;
387        self.modules.insert(cache_key(&name, &[]), record);
388        Ok(name)
389    }
390
391    /// Register a JSON, text or bytes module from its bytes, by name.
392    ///
393    /// A data module is a value, not code, so it has no bytecode to carry: the bundle keeps
394    /// the file's bytes and the product hands them here. `attributes` is what decided the
395    /// kind at bundle time, and passing it again keeps the two ends from disagreeing about
396    /// a `.json` file imported as text.
397    pub fn register_data_module(
398        &mut self,
399        name: &str,
400        source: Vec<u8>,
401        attributes: &[(String, String)],
402    ) -> JsResult<()> {
403        let kind = match module_kind(name, attributes) {
404            Ok(kind) => kind,
405            Err(message) => return Err(Signal::Throw(self.make_error("TypeError", &message))),
406        };
407        let loaded = LoadedModule {
408            name: name.to_string(),
409            url: name.to_string(),
410            source,
411        };
412        let record = self.data_module_record(&loaded, kind)?;
413        self.modules.insert(cache_key(name, attributes), record);
414        Ok(())
415    }
416
417    /// Register a native module: a name and the exports a library handed back.
418    ///
419    /// This is what `JS_NewCModule` amounts to. The record is born evaluated and carries one
420    /// cell per export, so the namespace machinery — sorted names, read-only getters,
421    /// `[object Module]` — is the ordinary one rather than a second implementation for C
422    /// modules.
423    ///
424    /// The exports are in the order the library declared them, which is the order
425    /// `JS_AddModuleExport` was called in; the namespace sorts them, as it does for every
426    /// module.
427    pub fn register_native_module(
428        &mut self,
429        name: &str,
430        exports: Vec<(String, Value)>,
431    ) -> Gc<ModuleRecord> {
432        let mut cells = Vec::with_capacity(exports.len());
433        let mut entries = Vec::with_capacity(exports.len());
434        for (index, (export_name, value)) in exports.into_iter().enumerate() {
435            cells.push(self.new_cell(value));
436            entries.push(js_compile::bytecode::ExportEntry::Local {
437                export_name,
438                var_idx: index as u32,
439            });
440        }
441        let record = Gc::new(
442            self.heap,
443            ModuleRecord::new(ModuleInner {
444                name: name.to_string(),
445                url: name.to_string(),
446                code: None,
447                meta: js_compile::bytecode::ModuleMeta {
448                    requests: Vec::new(),
449                    imports: Vec::new(),
450                    exports: entries,
451                },
452                cells,
453                // A native module's exports are values, not bindings to wire up: there is
454                // nothing to resolve and nothing to run, so it starts evaluated. That is
455                // also what lets an ordinary module import one inside a cycle.
456                dependencies: Vec::new(),
457                status: ModuleStatus::Evaluated,
458                evaluation_error: None,
459                kind: ModuleKind::Native,
460                namespace: None,
461                deferred_namespace: None,
462                import_meta: None,
463                star_cells: BTreeMap::new(),
464            }),
465        );
466        self.modules.insert(cache_key(name, &[]), record.clone());
467        record
468    }
469
470    /// Load and compile one module.
471    pub fn load_module(
472        &mut self,
473        specifier: &str,
474        attributes: &[(String, String)],
475        referrer: &str,
476    ) -> JsResult<Gc<ModuleRecord>> {
477        // A module that is already in memory — registered from bytecode, which is what an
478        // AOT product does with its bundle — must be found *before* the loader runs. The
479        // reference has the same ordering (`js_find_loaded_module` first, `js_module_loader`
480        // only if that misses); getting it the other way round makes a product carry a
481        // module and still report "could not load module filename" for it.
482        //
483        // With no loader installed at all, the textual rule is the only one there is: it is
484        // what an AOT product relies on, since its modules are registered under exactly the
485        // names that rule produces and it has no files to fall back to.
486        let resolved = match self.module_loader.as_ref() {
487            Some(loader) => loader.resolve(specifier, referrer),
488            None => Some(js_parse::normalize_specifier(referrer, specifier)),
489        };
490        if let Some(resolved) = &resolved {
491            if let Some(existing) = self.modules.get(&cache_key(resolved, attributes)) {
492                return Ok(existing.clone());
493            }
494        }
495        let Some(loader) = self.module_loader.take() else {
496            // Not in memory and nothing to read it from. Report it as the missing *file* it
497            // is, which is the reference's message for this case, rather than as an
498            // internal error about the host's setup.
499            let name = resolved.unwrap_or_else(|| specifier.to_string());
500            return Err(Signal::Throw(self.make_error(
501                "ReferenceError",
502                &format!("could not load module filename '{name}'"),
503            )));
504        };
505        // A native module is a record, not bytes: ask before reading anything. The name to
506        // ask about is the one textual resolution produced, so a loader does not have to
507        // repeat that rule.
508        let native_name = resolved.clone().unwrap_or_else(|| specifier.to_string());
509        let native = if attributes.is_empty() {
510            loader.load_native(self, &native_name)
511        } else {
512            // A C module has no `with { type: … }` form; an attribute means the loader
513            // must not treat this name as native.
514            None
515        };
516        let loaded = match native {
517            Some(Ok(record)) => {
518                self.module_loader = Some(loader);
519                let key = cache_key(&record.with(|r| r.name.clone()), attributes);
520                self.modules.insert(key, record.clone());
521                return Ok(record);
522            }
523            Some(Err(message)) => {
524                self.module_loader = Some(loader);
525                return Err(Signal::Throw(self.make_error("ReferenceError", &message)));
526            }
527            None => loader.load(specifier, attributes, referrer),
528        };
529        // Put the loader back whatever happened: it is the host's, and the interpreter
530        // only borrows it so that `&mut self` stays available for compiling.
531        self.module_loader = Some(loader);
532        let mut loaded = match loaded {
533            Ok(loaded) => loaded,
534            Err(message) => {
535                return Err(Signal::Throw(self.make_error("ReferenceError", &message)));
536            }
537        };
538        // A host-supplied name for the entry module wins over the path. Only the entry:
539        // `referrer` is empty for it and for nothing else, so a nested import keeps the name
540        // its specifier resolved to.
541        if referrer.is_empty()
542            && let Some(name) = &self.entry_module_name
543        {
544            loaded.name = name.clone();
545            loaded.url = name.clone();
546        }
547        // One record per *(name, attributes)*, so importing the same file twice runs it
548        // once — but importing it as JSON and as text is two modules with two contents,
549        // which `hello_module.js` does on purpose.
550        let key = cache_key(&loaded.name, attributes);
551        if let Some(existing) = self.modules.get(&key) {
552            return Ok(existing.clone());
553        }
554        let kind = match module_kind(&loaded.name, attributes) {
555            Ok(kind) => kind,
556            Err(message) => {
557                return Err(Signal::Throw(self.make_error("TypeError", &message)));
558            }
559        };
560        let record = match kind {
561            ModuleKind::JavaScript => self.compile_module_record(&loaded)?,
562            _ => self.data_module_record(&loaded, kind)?,
563        };
564        self.modules.insert(key, record.clone());
565        Ok(record)
566    }
567
568    /// Compile a JavaScript module and create its cells.
569    fn compile_module_record(&mut self, loaded: &LoadedModule) -> JsResult<Gc<ModuleRecord>> {
570        let source = match std::str::from_utf8(&loaded.source) {
571            Ok(source) => source,
572            Err(_) => {
573                return Err(Signal::Throw(self.make_error(
574                    "SyntaxError",
575                    &format!("{}: module source is not valid UTF-8", loaded.name),
576                )));
577            }
578        };
579        // Same shape as a script's compile error: the message, then `at <file>:<line>:<col>`
580        // unless the reference reports this one without a position. The file name is *not*
581        // part of the message — it belongs on the `at` line only.
582        let program = match js_parse::parse_module(source) {
583            Ok(program) => program,
584            Err(error) => {
585                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
586            }
587        };
588        let mut code = match js_compile::compile_module_with_source(&program, source) {
589            Ok(code) => code,
590            Err(error) => {
591                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
592            }
593        };
594        code.set_filename(&loaded.name);
595        self.module_record_from_code(&loaded.name, &loaded.url, code)
596    }
597
598    /// Build a module record around bytecode the caller already has.
599    ///
600    /// The one thing that separates this from [`Interp::compile_module_record`] is where
601    /// the bytecode came from — source, or a blob written by an AOT compiler. Everything
602    /// after that point is the same work: one cell per closure variable, a dependency slot
603    /// per request, `import.meta`, and the record itself. Keeping it in one place is what
604    /// makes a precompiled module behave like a compiled one rather than *almost* like one.
605    fn module_record_from_code(
606        &mut self,
607        name: &str,
608        url: &str,
609        code: CompiledFunction,
610    ) -> JsResult<Gc<ModuleRecord>> {
611        let meta = code
612            .module
613            .as_ref()
614            .map(|meta| (**meta).clone())
615            .unwrap_or_default();
616        let closure_vars = code.closure_vars.clone();
617        let compiled = Gc::new(self.heap, CompiledCode::new(code));
618        // One cell per closure variable. A lexical binding starts in its dead zone and a
619        // `var` as `undefined`; an import's cell is *replaced* during linking by the
620        // exporter's, which is what makes it live.
621        let mut cells = Vec::with_capacity(closure_vars.len());
622        for closure_var in &closure_vars {
623            let initial = if closure_var.is_lexical {
624                Value::Uninitialized
625            } else {
626                Value::Undefined
627            };
628            cells.push(self.new_cell(initial));
629        }
630        let dependencies = vec![None; meta.requests.len()];
631        let record = Gc::new(
632            self.heap,
633            ModuleRecord::new(ModuleInner {
634                name: name.to_string(),
635                url: url.to_string(),
636                code: Some(compiled),
637                meta,
638                cells,
639                dependencies,
640                status: ModuleStatus::Unlinked,
641                evaluation_error: None,
642                kind: ModuleKind::JavaScript,
643                namespace: None,
644                deferred_namespace: None,
645                import_meta: None,
646                star_cells: BTreeMap::new(),
647            }),
648        );
649        self.install_import_meta(&record)?;
650        Ok(record)
651    }
652
653    /// A JSON, text or bytes module: one value, exported as `default`.
654    ///
655    /// The value is produced by calling the *builtin* rather than by reaching into the
656    /// JSON parser or the typed-array internals, so a data module behaves exactly like
657    /// `JSON.parse(text)` or `new Uint8Array(bytes)` written out by hand — one
658    /// implementation of each, not two.
659    fn data_module_record(
660        &mut self,
661        loaded: &LoadedModule,
662        kind: ModuleKind,
663    ) -> JsResult<Gc<ModuleRecord>> {
664        let value = match kind {
665            ModuleKind::Json => {
666                let text = String::from_utf8_lossy(&loaded.source).to_string();
667                let Some(json) = self.global_value("JSON") else {
668                    return Err(Signal::Throw(
669                        self.make_error("InternalError", "JSON is not installed"),
670                    ));
671                };
672                let Some(Value::Object(json)) = Some(json) else {
673                    unreachable!()
674                };
675                let Some(parse) = self.get_property(&json, "parse")? else {
676                    return Err(Signal::Throw(
677                        self.make_error("InternalError", "JSON.parse is not installed"),
678                    ));
679                };
680                let text = self.string(&text);
681                match self.call_value(parse, Value::Object(json), vec![text]) {
682                    Ok(value) => value,
683                    Err(Signal::Throw(reason)) => {
684                        let detail = self.describe_exception(&reason);
685                        return Err(Signal::Throw(self.make_error(
686                            "SyntaxError",
687                            &format!("{}: {}", loaded.name, detail),
688                        )));
689                    }
690                    Err(other) => return Err(other),
691                }
692            }
693            ModuleKind::Text => {
694                // Taken as UTF-8 with replacement: a text file that is not valid UTF-8
695                // still has to become a string.
696                let text = String::from_utf8_lossy(&loaded.source).to_string();
697                self.string(&text)
698            }
699            ModuleKind::Bytes => {
700                let numbers: Vec<Value> = loaded
701                    .source
702                    .iter()
703                    .map(|byte| Value::Int(*byte as i32))
704                    .collect();
705                let elements = self.new_array(numbers);
706                let Some(Value::Object(ctor)) = self.global_value("Uint8Array") else {
707                    return Err(Signal::Throw(
708                        self.make_error("InternalError", "Uint8Array is not installed"),
709                    ));
710                };
711                self.construct(
712                    Value::Object(ctor),
713                    Value::Object(elements.clone()),
714                    vec![Value::Object(elements)],
715                )?
716            }
717            ModuleKind::JavaScript | ModuleKind::Native => {
718                unreachable!("handled by `compile_module_record`")
719            }
720        };
721        let cell = self.new_cell(value.clone());
722        let record = Gc::new(
723            self.heap,
724            ModuleRecord::new(ModuleInner {
725                name: loaded.name.clone(),
726                url: loaded.url.clone(),
727                code: None,
728                meta: js_compile::bytecode::ModuleMeta {
729                    requests: Vec::new(),
730                    imports: Vec::new(),
731                    exports: vec![js_compile::bytecode::ExportEntry::Local {
732                        export_name: "default".to_string(),
733                        var_idx: 0,
734                    }],
735                },
736                cells: vec![cell],
737                dependencies: Vec::new(),
738                // Nothing to link and nothing to run: a data module is born evaluated,
739                // which is what lets `import x from "./m.json"` work inside a cycle.
740                status: ModuleStatus::Evaluated,
741                evaluation_error: None,
742                kind,
743                namespace: None,
744                deferred_namespace: None,
745                import_meta: None,
746                star_cells: BTreeMap::new(),
747            }),
748        );
749        Ok(record)
750    }
751
752    /// A binding of the global object, if it exists.
753    fn global_value(&mut self, name: &str) -> Option<Value> {
754        let global = self.realm.global.clone();
755        self.get_property(&global, name).ok().flatten()
756    }
757
758    /// `import.meta` for `record`, built once.
759    fn install_import_meta(&mut self, record: &Gc<ModuleRecord>) -> JsResult<()> {
760        // §16.2.1.10 / HostGetImportMetaProperties: `import.meta` is an **ordinary object
761        // with a null prototype**. That is observable and test262 leans on it —
762        // `dynamic-import/assignment-expression/import-meta` does `import(import.meta)` and
763        // expects the promise to *reject with a `TypeError`*, which only happens if
764        // `ToString` cannot find a `toString` through a prototype. Giving it
765        // `Object.prototype` (as this did) made that conversion succeed and the import ask
766        // for a module named "[object Object]".
767        let meta = self.new_object(None);
768        let url = self.string(record.with(|r| r.url.clone()));
769        // Only the two properties the reference defines; a script can add its own.
770        meta.define_data("url", url);
771        meta.define_data("main", Value::Bool(false));
772        record.with_mut(|r| r.import_meta = Some(meta));
773        Ok(())
774    }
775
776    /// Resolve every import of `module` and validate its exports, depth-first.
777    pub fn link_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
778        match module.with(|r| r.status) {
779            // Already linked, or being linked right now — the latter is a cycle, and it is
780            // exactly why the status is set *before* recursing: a cycle stops here rather
781            // than recursing forever.
782            ModuleStatus::Linking
783            | ModuleStatus::Linked
784            | ModuleStatus::Evaluating
785            | ModuleStatus::Evaluated => {
786                return Ok(());
787            }
788            ModuleStatus::Unlinked => {}
789        }
790        module.with_mut(|r| r.status = ModuleStatus::Linking);
791
792        let requests = module.with(|r| r.meta.requests.clone());
793        for (index, request) in requests.iter().enumerate() {
794            let referrer = module.with(|r| r.name.clone());
795            let dependency =
796                self.load_module(&request.specifier, &request.attributes, &referrer)?;
797            module.with_mut(|r| r.dependencies[index] = Some(dependency.clone()));
798            self.link_module(&dependency)?;
799        }
800
801        // Wire the cells. `import { x } from "m"` makes this module's cell *be* `m`'s, so
802        // a later assignment over there is visible here with no copying.
803        let imports = module.with(|r| r.meta.imports.clone());
804        for entry in &imports {
805            let dependency =
806                module.with(|r| r.dependencies.get(entry.module as usize).cloned().flatten());
807            let Some(dependency) = dependency else {
808                return Err(Signal::Throw(self.make_error(
809                    "InternalError",
810                    "an import names a module that was not loaded",
811                )));
812            };
813            if entry.is_star {
814                // `import defer * as ns` binds the deferred namespace — a different object
815                // from the eager one, and the only way a `defer` request is observable.
816                let namespace = if entry.phase == ImportPhase::Defer {
817                    self.module_deferred_namespace(&dependency)?
818                } else {
819                    self.module_namespace(&dependency)?
820                };
821                let cell = module.with(|r| r.cells[entry.var_idx as usize].clone());
822                cell.set(namespace);
823                continue;
824            }
825            let cell = self.resolve_export(&dependency, &entry.name)?;
826            module.with_mut(|r| r.cells[entry.var_idx as usize] = cell);
827        }
828
829        // Validate: `export { a } from "m"` where `m` has no `a` is a link error, and
830        // saying so now beats an `undefined` that surfaces much later.
831        let exports = module.with(|r| r.meta.exports.clone());
832        for entry in &exports {
833            if let js_compile::bytecode::ExportEntry::Indirect {
834                export_name,
835                module: index,
836                import_name,
837            } = entry
838            {
839                let dependency =
840                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
841                let Some(dependency) = dependency else {
842                    continue;
843                };
844                // A namespace re-export names the dependency's *namespace*, which is not an
845                // export of it and therefore has nothing to validate.
846                if import_name == "*namespace*" {
847                    continue;
848                }
849                if self.resolve_export(&dependency, import_name).is_err() {
850                    let dependency_name = dependency.with(|r| r.name.clone());
851                    return Err(Signal::Throw(self.make_error(
852                        "SyntaxError",
853                        &format!(
854                            "Could not find export '{import_name}' in module '{dependency_name}' (re-exported as '{export_name}')"
855                        ),
856                    )));
857                }
858            }
859        }
860
861        // Create the module's hoisted bindings *now*, while linking — before any body
862        // runs anywhere in the graph.
863        //
864        // This is the whole trick behind cyclic imports. The body's prologue is
865        // `push_this; if_false <body>`, so calling it with a truthy `this` runs only the
866        // hoisted declarations and returns. Doing that for every module during linking
867        // means that when evaluation finally starts, every exported function in the
868        // cycle already exists — which is why `b.js` can see `a`'s function even though
869        // `a.js` has not run yet.
870        self.hoist_module_bindings(module)?;
871
872        module.with_mut(|r| r.status = ModuleStatus::Linked);
873        Ok(())
874    }
875
876    /// Run `module`'s prologue only, creating its hoisted bindings.
877    fn hoist_module_bindings(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
878        let Some(code) = module.with(|r| r.code.clone()) else {
879            // A JSON/text module has nothing to hoist.
880            return Ok(());
881        };
882        let env = self.module_env(module);
883        self.execute(code, env, Value::Bool(true), Vec::new(), Value::Undefined)
884            .map(|_| ())
885    }
886
887    /// The closure environment a module body runs in: one cell per closure variable.
888    fn module_env(&mut self, module: &Gc<ModuleRecord>) -> Gc<ClosureEnv> {
889        let cells = module.with(|r| r.cells.clone());
890        Gc::new(
891            self.heap,
892            ClosureEnv {
893                cells,
894                eval_scope: None,
895                local_vars: None,
896                local_phase: 0,
897            },
898        )
899    }
900
901    /// The cell behind `name` in `module`, following re-exports.
902    pub fn resolve_export(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Gc<Cell>> {
903        match self.resolve_export_inner(module, name, 0)? {
904            Resolution::Cell { cell, .. } => Ok(cell),
905            Resolution::NotFound => Err(self.missing_export(module, name)),
906            Resolution::Ambiguous => Err(self.ambiguous_export(module, name)),
907        }
908    }
909
910    /// The wrapper cell behind a module's *own* namespace, cached so its identity is stable.
911    ///
912    /// Same reason as `star_cells`: the ambiguity test compares `(module, binding)`, and an
913    /// `import * as ns` re-export resolves to `{ m, *namespace* }`, so two paths reaching the
914    /// same module's namespace must agree that they name one binding.
915    fn namespace_cell(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<Cell>> {
916        self.namespace_cell_of_phase(module, false)
917    }
918
919    /// The same, but the wrapper holds the *deferred* namespace.
920    fn deferred_namespace_cell(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<Cell>> {
921        self.namespace_cell_of_phase(module, true)
922    }
923
924    fn namespace_cell_of_phase(
925        &mut self,
926        module: &Gc<ModuleRecord>,
927        deferred: bool,
928    ) -> JsResult<Gc<Cell>> {
929        let key = if deferred {
930            "*deferred-namespace*"
931        } else {
932            "*namespace*"
933        };
934        if let Some(cell) = module.with(|r| r.star_cells.get(key).cloned()) {
935            return Ok(cell);
936        }
937        let namespace = if deferred {
938            self.module_deferred_namespace(module)?
939        } else {
940            self.module_namespace(module)?
941        };
942        let cell = self.new_cell(namespace);
943        module.with_mut(|r| r.star_cells.insert(key.to_string(), cell.clone()));
944        Ok(cell)
945    }
946
947    /// Why a name that two `export *` declarations both provide cannot be resolved.
948    ///
949    /// §16.2.1.6.3 `ResolveExport` returns **ambiguous** rather than picking one, and
950    /// `GetExportedNames`/`ResolveExport` feed link-time validation: a module with an
951    /// ambiguous name fails to link, so `import()` of it rejects with a `SyntaxError`.
952    /// Taking the first success instead — which is what the star loop used to do — made the
953    /// module load fine and hand back a namespace, and test262's `instn-iee-err-ambiguous`
954    /// family checks exactly that rejection.
955    fn ambiguous_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
956        let module_name = module.with(|r| r.name.clone());
957        Signal::Throw(self.make_error(
958            "SyntaxError",
959            &format!("Ambiguous export '{name}' in module '{module_name}'"),
960        ))
961    }
962
963    fn resolve_export_inner(
964        &mut self,
965        module: &Gc<ModuleRecord>,
966        name: &str,
967        depth: usize,
968    ) -> JsResult<Resolution> {
969        // A pathological chain (`a` exports from `b`, `b` from `a`) would otherwise
970        // recurse until the Rust stack gives out.
971        if depth > 64 {
972            return Err(Signal::Throw(
973                self.make_error("SyntaxError", "circular re-export chain"),
974            ));
975        }
976        let exports = module.with(|r| r.meta.exports.clone());
977        // An explicit export wins over any `export *`.
978        for entry in &exports {
979            match entry {
980                js_compile::bytecode::ExportEntry::Local {
981                    export_name,
982                    var_idx,
983                } if export_name == name => {
984                    return Ok(Resolution::Cell {
985                        cell: module.with(|r| r.cells[*var_idx as usize].clone()),
986                        module: module.clone(),
987                        binding: name.to_string(),
988                    });
989                }
990                js_compile::bytecode::ExportEntry::Indirect {
991                    export_name,
992                    module: index,
993                    import_name,
994                } if export_name == name => {
995                    let dependency =
996                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
997                    let Some(dependency) = dependency else {
998                        return Ok(Resolution::NotFound);
999                    };
1000                    // `import * as ns from "m"; export { ns }` — §16.2.1.6.3 step 7 resolves
1001                    // to `{ [[Module]]: m, [[BindingName]]: namespace }`, so the identity is
1002                    // the *target* module and not this one.
1003                    if import_name == "*namespace*" {
1004                        // A `defer` request re-exported this way still hands back the
1005                        // *deferred* namespace: the phase belongs to the request, and
1006                        // reading through the export is what has to trigger evaluation.
1007                        let phase = module.with(|r| {
1008                            r.meta
1009                                .requests
1010                                .get(*index as usize)
1011                                .map(|request| request.phase)
1012                        });
1013                        let cell = if phase == Some(ImportPhase::Defer) {
1014                            self.deferred_namespace_cell(&dependency)?
1015                        } else {
1016                            self.namespace_cell(&dependency)?
1017                        };
1018                        return Ok(Resolution::Cell {
1019                            cell,
1020                            module: dependency,
1021                            binding: "*namespace*".to_string(),
1022                        });
1023                    }
1024                    return self.resolve_export_inner(&dependency, import_name, depth + 1);
1025                }
1026                js_compile::bytecode::ExportEntry::StarAs { export_name, .. }
1027                    if export_name == name =>
1028                {
1029                    // The namespace of the re-exported module, wrapped in a cell so the
1030                    // export table stays uniform. The cell is **cached per name**: the
1031                    // ambiguity test below compares binding identities, and a fresh cell on
1032                    // every lookup made one export look like two.
1033                    let target = module.with(|r| {
1034                        r.meta.exports.iter().find_map(|entry| match entry {
1035                            js_compile::bytecode::ExportEntry::StarAs {
1036                                export_name,
1037                                module: index,
1038                            } if export_name == name => Some(*index),
1039                            _ => None,
1040                        })
1041                    });
1042                    let Some(index) = target else {
1043                        return Ok(Resolution::NotFound);
1044                    };
1045                    let dependency =
1046                        module.with(|r| r.dependencies.get(index as usize).cloned().flatten());
1047                    let Some(dependency) = dependency else {
1048                        return Ok(Resolution::NotFound);
1049                    };
1050                    if let Some(cell) = module.with(|r| r.star_cells.get(name).cloned()) {
1051                        return Ok(Resolution::Cell {
1052                            cell,
1053                            module: dependency,
1054                            binding: "*namespace*".to_string(),
1055                        });
1056                    }
1057                    let namespace = self.star_namespace(module, name)?;
1058                    let cell = self.new_cell(namespace);
1059                    module.with_mut(|r| r.star_cells.insert(name.to_string(), cell.clone()));
1060                    return Ok(Resolution::Cell {
1061                        cell,
1062                        module: dependency,
1063                        binding: "*namespace*".to_string(),
1064                    });
1065                }
1066                _ => {}
1067            }
1068        }
1069        // `export * from "m"`: forwarded names are visible only if nothing above claimed
1070        // them, which is why this is a second pass.
1071        //
1072        // Two stars that reach the **same** binding are not ambiguous — `export * from "a";
1073        // export * from "b"` where both re-export `c`'s `x` resolves to one thing. Two that
1074        // reach different bindings are, and the comparison is on the binding itself (the
1075        // module's cell for that name), not on the name.
1076        let mut found: Option<Resolution> = None;
1077        for entry in &exports {
1078            if let js_compile::bytecode::ExportEntry::Star { module: index } = entry {
1079                let dependency =
1080                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
1081                let Some(dependency) = dependency else {
1082                    continue;
1083                };
1084                match self.resolve_export_inner(&dependency, name, depth + 1)? {
1085                    resolution @ Resolution::Cell { .. } => match &found {
1086                        None => found = Some(resolution),
1087                        Some(previous) if !previous.same_binding(&resolution) => {
1088                            return Ok(Resolution::Ambiguous);
1089                        }
1090                        Some(_) => {}
1091                    },
1092                    Resolution::NotFound => {}
1093                    // A nested ambiguity is not ours to resolve: it makes *this* name
1094                    // ambiguous too, which is what the caller needs to hear.
1095                    Resolution::Ambiguous => return Ok(Resolution::Ambiguous),
1096                }
1097            }
1098        }
1099        Ok(found.unwrap_or(Resolution::NotFound))
1100    }
1101
1102    fn missing_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
1103        let module_name = module.with(|r| r.name.clone());
1104        // The reference's wording, kept verbatim: an error message is part of the
1105        // behaviour a user sees, and `qjs` says "Could not find export".
1106        Signal::Throw(self.make_error(
1107            "SyntaxError",
1108            &format!("Could not find export '{name}' in module '{module_name}'"),
1109        ))
1110    }
1111
1112    /// The namespace behind `export * as ns from "m"`.
1113    fn star_namespace(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Value> {
1114        let exports = module.with(|r| r.meta.exports.clone());
1115        for entry in &exports {
1116            if let js_compile::bytecode::ExportEntry::StarAs {
1117                export_name,
1118                module: index,
1119            } = entry
1120                && export_name == name
1121            {
1122                let dependency =
1123                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
1124                let Some(dependency) = dependency else {
1125                    continue;
1126                };
1127                return self.module_namespace(&dependency);
1128            }
1129        }
1130        Ok(Value::Undefined)
1131    }
1132
1133    /// The names `module` exports, sorted the way §16.2.1.6 requires.
1134    pub fn module_export_names(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Vec<String>> {
1135        let mut names: Vec<String> = Vec::new();
1136        self.collect_export_names(module, &mut names, 0)?;
1137        names.sort();
1138        names.dedup();
1139        Ok(names)
1140    }
1141
1142    fn collect_export_names(
1143        &mut self,
1144        module: &Gc<ModuleRecord>,
1145        out: &mut Vec<String>,
1146        depth: usize,
1147    ) -> JsResult<()> {
1148        if depth > 64 {
1149            return Ok(());
1150        }
1151        let exports = module.with(|r| r.meta.exports.clone());
1152        for entry in &exports {
1153            match entry {
1154                js_compile::bytecode::ExportEntry::Local { export_name, .. }
1155                | js_compile::bytecode::ExportEntry::Indirect { export_name, .. }
1156                | js_compile::bytecode::ExportEntry::StarAs { export_name, .. } => {
1157                    out.push(export_name.clone());
1158                }
1159                js_compile::bytecode::ExportEntry::Star { module: index } => {
1160                    let dependency =
1161                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
1162                    if let Some(dependency) = dependency {
1163                        let mut forwarded = Vec::new();
1164                        self.collect_export_names(&dependency, &mut forwarded, depth + 1)?;
1165                        // `export *` never forwards `default` (§16.2.1.6.2).
1166                        out.extend(forwarded.into_iter().filter(|name| name != "default"));
1167                    }
1168                }
1169            }
1170        }
1171        Ok(())
1172    }
1173
1174    /// The namespace object of `module`, built on first use.
1175    ///
1176    /// An ordinary object with one read-only getter per export, inserted in sorted order.
1177    /// The getter reads the cell, which is what makes the binding live: `export let x`
1178    /// followed by `x = 1` in the exporting module is visible here without copying.
1179    pub fn module_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
1180        self.build_namespace(module, false)
1181    }
1182
1183    /// The *deferred* namespace object of `module`, built on first use.
1184    ///
1185    /// Identical to [`Interp::module_namespace`] in every observable way except one: reading
1186    /// it evaluates the module first. That is import-defer's `[[Deferred]]`, which is a
1187    /// property of the *object*, not of the module — one module can be imported both ways
1188    /// and the two namespaces are distinct objects.
1189    pub fn module_deferred_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
1190        self.build_namespace(module, true)
1191    }
1192
1193    fn build_namespace(&mut self, module: &Gc<ModuleRecord>, deferred: bool) -> JsResult<Value> {
1194        let cached = module.with(|r| {
1195            if deferred {
1196                r.deferred_namespace.clone()
1197            } else {
1198                r.namespace.clone()
1199            }
1200        });
1201        if let Some(namespace) = cached {
1202            return Ok(Value::Object(namespace));
1203        }
1204        let names = self.module_export_names(module)?;
1205        let function_proto = self.realm.function_proto.clone();
1206        // §10.4.6.1: a namespace's `[[Prototype]]` is **null**.
1207        //
1208        // Not `Object.prototype` with things taken away: `Object.getPrototypeOf(ns)` is
1209        // `null` and `ns instanceof Object` is `false`, which test262 asserts directly in
1210        // both namespace families. Handing it `object_proto` also leaked every `Object.prototype`
1211        // member into the namespace, so `ns.hasOwnProperty` answered a function.
1212        let namespace = self.new_object(None);
1213        namespace.set_module_namespace();
1214        for name in &names {
1215            // §16.2.1.5.2 `GetModuleNamespace` keeps only the **unambiguous** names: a name
1216            // that two `export *` provide is left out of the namespace rather than making
1217            // the module unloadable. Importing it is still an error, which is why
1218            // `resolve_export` reports ambiguity — but a namespace is a menu, and a dish two
1219            // suppliers disagree about is simply not on it (`omitted-from-namespace`).
1220            let cell = match self.resolve_export_inner(module, name, 0)? {
1221                Resolution::Cell { cell, .. } => cell,
1222                Resolution::NotFound | Resolution::Ambiguous => continue,
1223            };
1224            let getter = JsObject::function(
1225                self.heap,
1226                Some(function_proto.clone()),
1227                Callable::ModuleBinding { cell },
1228            );
1229            namespace.define(
1230                name,
1231                Property {
1232                    value: None,
1233                    getter: Some(Value::Object(getter)),
1234                    setter: None,
1235                    writable: false,
1236                    enumerable: true,
1237                    configurable: false,
1238                    descriptor_fields: None,
1239                },
1240            );
1241        }
1242        // A namespace reports `[object Module]`, and cannot gain properties. A *deferred*
1243        // one says "Deferred Module" — the one visible difference between the two objects,
1244        // and what a test can use to tell them apart.
1245        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1246        let tag = self.string(if deferred {
1247            "Deferred Module"
1248        } else {
1249            "Module"
1250        });
1251        namespace.define_key(&tag_key, Property::with_attributes(tag, false, false));
1252        self.object_prevent_extensions(&namespace)?;
1253        if deferred {
1254            namespace.set_deferred_namespace_module(module.clone());
1255        }
1256        module.with_mut(|r| {
1257            if deferred {
1258                r.deferred_namespace = Some(namespace.clone());
1259            } else {
1260                r.namespace = Some(namespace.clone());
1261            }
1262        });
1263        Ok(Value::Object(namespace))
1264    }
1265
1266    /// Run `module`'s body, evaluating its dependencies first.
1267    ///
1268    /// Post-order, once each: a module already evaluated — or being evaluated right now —
1269    /// is skipped, which is what §16.2.1.5.3.1's "evaluated or evaluating" guard amounts
1270    /// to, and what makes a cycle terminate instead of recursing.
1271    ///
1272    /// The two states are kept apart because the deferred-import proposal can observe the
1273    /// difference: see [`Interp::trigger_deferred_namespace`].
1274    pub fn evaluate_module_body(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
1275        match module.with(|r| r.status) {
1276            // `Evaluated` here means "finished", including "finished by throwing": the
1277            // completion below is stored, so re-reporting it is the whole of the work.
1278            ModuleStatus::Evaluated => {
1279                return match module.with(|r| r.evaluation_error.clone()) {
1280                    Some(error) => Err(Signal::Throw(error)),
1281                    None => Ok(()),
1282                };
1283            }
1284            ModuleStatus::Evaluating => return Ok(()),
1285            ModuleStatus::Unlinked | ModuleStatus::Linking | ModuleStatus::Linked => {}
1286        }
1287        // Mark before recursing so a cycle stops here.
1288        module.with_mut(|r| r.status = ModuleStatus::Evaluating);
1289
1290        let result = self.evaluate_module_inner(module);
1291        match &result {
1292            Ok(()) => module.with_mut(|r| r.status = ModuleStatus::Evaluated),
1293            Err(Signal::Throw(reason)) => module.with_mut(|r| {
1294                // §16.2.1.5.3.1 step 20: a failed evaluation is recorded on the record and
1295                // the module counts as evaluated. Running the body a second time would
1296                // produce a second, *different* exception object, and the proposal's tests
1297                // compare the two by identity.
1298                r.evaluation_error = Some(reason.clone());
1299                r.status = ModuleStatus::Evaluated;
1300            }),
1301            // `Signal::Yield` and friends are not completions of the body: leave the module
1302            // `Evaluating` so the next attempt starts over.
1303            Err(_) => {}
1304        }
1305        result
1306    }
1307
1308    /// The body of [`Interp::evaluate_module_body`], with the status already set.
1309    fn evaluate_module_inner(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
1310        // Which dependencies this evaluation runs, and in which order.
1311        //
1312        // §16.2.1.5.3.1 asks for one flattened list, and the deferred-import proposal is
1313        // why it is not simply "one entry per request": a request at phase `defer` is
1314        // **not** evaluated, but its *asynchronous* transitive dependencies are, because
1315        // an async module's ordering is decided by the graph that reaches it and not by
1316        // whether some other module happens to read through a deferred namespace first.
1317        // So `import defer * as ns from "./later.js"` whose `./later.js` imports a module
1318        // with top-level await still runs that await, before the importer's body.
1319        let requests = module.with(|r| r.meta.requests.clone());
1320        let mut evaluation_list: Vec<Gc<ModuleRecord>> = Vec::new();
1321        let mut seen: Vec<usize> = Vec::new();
1322        for (index, request) in requests.iter().enumerate() {
1323            let Some(required) = module.with(|r| r.dependencies.get(index).cloned().flatten())
1324            else {
1325                continue;
1326            };
1327            if request.phase == ImportPhase::Defer {
1328                self.gather_asynchronous_transitive_dependencies(
1329                    &required,
1330                    &mut seen,
1331                    &mut evaluation_list,
1332                );
1333            } else if !evaluation_list.iter().any(|m| m.ptr_eq(&required)) {
1334                evaluation_list.push(required);
1335            }
1336        }
1337        for dependency in evaluation_list {
1338            self.evaluate_module_body(&dependency)?;
1339        }
1340
1341        let Some(code) = module.with(|r| r.code.clone()) else {
1342            // A JSON/text module has no body; its value is already in its cell.
1343            return Ok(());
1344        };
1345        let name = module.with(|r| r.name.clone());
1346        let env = self.module_env(module);
1347        // The hoisted bindings already exist: `link_module` ran the prologue pass with a
1348        // truthy `this`, which is what the guard in the compiled prefix detects. Here the
1349        // receiver is `undefined`, so the body itself runs.
1350        //
1351        // A body with top-level `await` is compiled as an async function, so it answers a
1352        // promise instead of a value. The evaluation is then driven to completion here:
1353        // draining the queue is what advances the coroutine, and there is nothing else
1354        // pending at this point, since module evaluation is what started it.
1355        let async_body = code.code.kind.is_async();
1356        self.module_stack.push(name);
1357        let result = if async_body {
1358            self.run_async_body(code, env, Value::Undefined)
1359                .and_then(|promise| self.await_module_promise(promise))
1360        } else {
1361            self.execute(code, env, Value::Undefined, Vec::new(), Value::Undefined)
1362        };
1363        self.module_stack.pop();
1364        result.map(|_| ())
1365    }
1366
1367    /// Evaluate the asynchronous modules a deferred request drags in, and nothing else.
1368    fn evaluate_async_transitive_dependencies(
1369        &mut self,
1370        module: &Gc<ModuleRecord>,
1371    ) -> JsResult<()> {
1372        let mut seen = Vec::new();
1373        let mut list = Vec::new();
1374        self.gather_asynchronous_transitive_dependencies(module, &mut seen, &mut list);
1375        for dependency in list {
1376            self.evaluate_module_body(&dependency)?;
1377        }
1378        Ok(())
1379    }
1380
1381    /// `GatherAsynchronousTransitiveDependencies` — the async modules a deferred request
1382    /// drags into evaluation order without evaluating itself.
1383    ///
1384    /// Walks the request graph and stops at the first `[[HasTLA]]` module on each path,
1385    /// because that module's own dependencies are already part of *its* evaluation. A
1386    /// module that is evaluating or done contributes nothing, and a synthetic (JSON/text/
1387    /// native) module has no requests to follow.
1388    fn gather_asynchronous_transitive_dependencies(
1389        &mut self,
1390        module: &Gc<ModuleRecord>,
1391        seen: &mut Vec<usize>,
1392        out: &mut Vec<Gc<ModuleRecord>>,
1393    ) {
1394        let identity = module.identity();
1395        if seen.contains(&identity) {
1396            return;
1397        }
1398        seen.push(identity);
1399        if !module.with(|r| r.kind == ModuleKind::JavaScript) {
1400            return;
1401        }
1402        match module.with(|r| r.status) {
1403            ModuleStatus::Evaluating | ModuleStatus::Evaluated => return,
1404            _ => {}
1405        }
1406        if module.has_tla() {
1407            if !out.iter().any(|m| m.ptr_eq(module)) {
1408                out.push(module.clone());
1409            }
1410            return;
1411        }
1412        let count = module.with(|r| r.meta.requests.len());
1413        let mut collected: Vec<Gc<ModuleRecord>> = Vec::new();
1414        for index in 0..count {
1415            let Some(required) = module.with(|r| r.dependencies.get(index).cloned().flatten())
1416            else {
1417                continue;
1418            };
1419            self.gather_asynchronous_transitive_dependencies(&required, seen, &mut collected);
1420        }
1421        for candidate in collected {
1422            if !out.iter().any(|m| m.ptr_eq(&candidate)) {
1423                out.push(candidate);
1424            }
1425        }
1426    }
1427
1428    /// `ReadyForSyncExecution` — whether evaluating `module` right now cannot suspend.
1429    ///
1430    /// This engine runs a module body to completion inside [`Interp::evaluate_module_body`],
1431    /// draining the job queue for a top-level `await` as it goes, so there is never a module
1432    /// parked in `~evaluating-async~`: the only two answers here are "already done" and
1433    /// "on the stack right now". Everything else — a body with top-level await anywhere
1434    /// below it, or a cycle back into one that is running — means a deferred namespace
1435    /// cannot be read synchronously, which is the `TypeError` the proposal specifies.
1436    fn ready_for_sync_execution(
1437        &mut self,
1438        module: &Gc<ModuleRecord>,
1439        seen: &mut Vec<usize>,
1440    ) -> bool {
1441        let identity = module.identity();
1442        if seen.contains(&identity) {
1443            return true;
1444        }
1445        seen.push(identity);
1446        match module.with(|r| r.status) {
1447            ModuleStatus::Evaluated => return true,
1448            ModuleStatus::Evaluating => return false,
1449            _ => {}
1450        }
1451        if module.has_tla() {
1452            return false;
1453        }
1454        let count = module.with(|r| r.meta.requests.len());
1455        for index in 0..count {
1456            let Some(required) = module.with(|r| r.dependencies.get(index).cloned().flatten())
1457            else {
1458                continue;
1459            };
1460            if !self.ready_for_sync_execution(&required, seen) {
1461                return false;
1462            }
1463        }
1464        true
1465    }
1466
1467    /// `EnsureDeferredNamespaceEvaluation` — the trigger behind every read of a deferred
1468    /// namespace.
1469    ///
1470    /// `None` for an ordinary namespace, which is what makes this cheap on the hot path: a
1471    /// namespace built by `import * as ns` has no module attached and answers immediately.
1472    pub(crate) fn trigger_deferred_namespace(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
1473        let Some(module) = object.deferred_namespace_module() else {
1474            return Ok(());
1475        };
1476        // Only a module that has *not* finished can be evaluated here, and only such a
1477        // module can be unready: a module that threw is finished too, and re-reporting its
1478        // completion is what `evaluate_module_body` does.
1479        if module.with(|r| r.status) != ModuleStatus::Evaluated {
1480            let mut seen = Vec::new();
1481            if !self.ready_for_sync_execution(&module, &mut seen) {
1482                return Err(self.type_error(
1483                    "cannot read a deferred module namespace while its module is evaluating",
1484                ));
1485            }
1486        }
1487        self.evaluate_module_body(&module)
1488    }
1489
1490    /// Drive a module's own promise to a settled state.
1491    ///
1492    /// `js_execute_sync_module` in the reference does the same thing and calls a pending
1493    /// promise an error ("promise is pending"); draining first is the difference, and it
1494    /// is correct here because nothing else can be waiting: this runs before the host has
1495    /// been given control, and the only queued jobs are the ones this body queued for
1496    /// itself.
1497    fn await_module_promise(&mut self, promise: Value) -> JsResult<Value> {
1498        let Value::Object(promise) = promise else {
1499            return Ok(Value::Undefined);
1500        };
1501        self.drain_jobs()?;
1502        let state = self.promise_state(&promise);
1503        let Some(state) = state else {
1504            return Ok(Value::Undefined);
1505        };
1506        let status = state.borrow().status.clone();
1507        match status {
1508            crate::object::PromiseStatus::Fulfilled(value) => Ok(value),
1509            crate::object::PromiseStatus::Rejected(reason) => Err(Signal::Throw(reason)),
1510            crate::object::PromiseStatus::Pending => Err(Signal::Throw(self.make_error(
1511                "TypeError",
1512                "promise is pending: top-level await never settled",
1513            ))),
1514        }
1515    }
1516
1517    /// `import(specifier)`: load, link, evaluate — asynchronously.
1518    ///
1519    /// The work happens in a job, because §13.3.10.1 makes dynamic import settle through
1520    /// the promise machinery: `import("x").then(f)` must call `f` after the current
1521    /// script finishes, never inside the `import` expression.
1522    pub fn dynamic_import(
1523        &mut self,
1524        specifier: Value,
1525        options: Value,
1526        phase: ImportPhase,
1527    ) -> JsResult<Value> {
1528        let promise = self.new_promise();
1529        // §13.3.10.1 steps 5–7, in this order and with this error handling:
1530        //
1531        //     5. Let promiseCapability be ! NewPromiseCapability(%Promise%).
1532        //     6. Let specifierString be ToString(specifier).
1533        //     7. IfAbruptRejectPromise(specifierString, promiseCapability).
1534        //
1535        // Step 7 is the whole point of the ordering: a throwing `toString` — or a Symbol
1536        // specifier, which `ToString` rejects — must **reject the promise**, not throw out of
1537        // the `import` expression. Throwing here made `import(obj)` with a throwing
1538        // `toString` abort the whole script, so `.catch` could never run and test262's 40-odd
1539        // `specifier-tostring-abrupt-rejects` cases all failed.
1540        //
1541        // `GetValue` (step 4) is a plain `?` and genuinely throws synchronously; the compiler
1542        // has already evaluated the argument by the time this runs, so that distinction is
1543        // kept where it belongs.
1544        let specifier = match self.to_js_string(&specifier) {
1545            Ok(specifier) => specifier,
1546            Err(Signal::Throw(reason)) => {
1547                self.reject_promise(&promise, reason);
1548                return Ok(Value::Object(promise));
1549            }
1550            Err(other) => return Err(other),
1551        };
1552        // §13.3.10.1 steps 9–10: the import-attributes bag.
1553        //
1554        // This loader applies no attributes — `with: { type: 'json' }` parses and is then
1555        // ignored — but the *validation* is not optional, and neither are the observable
1556        // reads it performs. Every abrupt completion below rejects the promise rather than
1557        // throwing, and the order (options is an object, then `with`, then its keys, then
1558        // each value) is what the tests instrument:
1559        //
1560        //     `import(x, null)`            → TypeError rejection (step 10.a)
1561        //     `get with() { throw e }`     → rejection with `e` (step 10.c)
1562        //     `with: 'string'`            → TypeError rejection (step 10.d.i)
1563        //     `with: { type: 23 }`        → TypeError rejection (step 10.d.v.3)
1564        if let Some(rejection) = self.import_attribute_error(&options) {
1565            self.reject_promise(&promise, rejection);
1566            return Ok(Value::Object(promise));
1567        }
1568        // Resolved relative to whatever is running the import — the reference asks
1569        // `JS_GetScriptOrModuleName(ctx, 0)`, which is the innermost frame's file name and
1570        // does not care whether that frame came from a module or a plain script.
1571        //
1572        // Only consulting the module stack (as this did) made every `import('./x.js')` from
1573        // a *script* resolve against the working directory instead of the script's own
1574        // directory, so `await import('./module-code_FIXTURE.js')` in test262's
1575        // `dynamic-import` tests failed with "could not load module filename" for a file
1576        // sitting right next to the test.
1577        let referrer = self.import_referrer();
1578        self.jobs.push_back(crate::interp::Job::Import {
1579            specifier,
1580            referrer,
1581            promise: promise.clone(),
1582            phase,
1583        });
1584        Ok(Value::Object(promise))
1585    }
1586
1587    /// Validate `import(x, options)`'s second argument, answering the reason to reject with.
1588    ///
1589    /// Returns `None` when the bag is acceptable — including when it is absent, which is the
1590    /// overwhelmingly common case and the only one this loader ever acts on.
1591    ///
1592    /// The reads are performed even though their results are discarded, because §13.3.10.1
1593    /// makes them observable: a `with` getter or a `Proxy` that logs is the entire content of
1594    /// the `2nd-param-*` tests. Nothing here throws; every failure becomes a rejection, which
1595    /// is `IfAbruptRejectPromise` spelled out.
1596    fn import_attribute_error(&mut self, options: &Value) -> Option<Value> {
1597        // Step 10: an absent bag is fine, and `undefined` is how "absent" arrives here —
1598        // `import(x)` compiles a literal `undefined` into the slot.
1599        if matches!(options, Value::Undefined) {
1600            return None;
1601        }
1602        // 10.a: any other non-object is a TypeError.
1603        let Value::Object(options) = options else {
1604            return Some(self.type_error_value("import options must be an object"));
1605        };
1606        let options = options.clone();
1607        // 10.b–c: `Get(options, "with")`.
1608        let with = match self.read_field(&Value::Object(options), "with") {
1609            Ok(with) => with,
1610            Err(Signal::Throw(reason)) => return Some(reason),
1611            Err(_) => return None,
1612        };
1613        if matches!(with, Value::Undefined) {
1614            return None;
1615        }
1616        // 10.d.i: `with` has to be an object too.
1617        let Value::Object(with_object) = &with else {
1618            return Some(self.type_error_value("import attributes must be an object"));
1619        };
1620        let with_object = with_object.clone();
1621        // 10.d.ii–iii: `EnumerableOwnPropertyNames`, which can throw from a `Proxy` trap —
1622        // so this goes through `[[OwnPropertyKeys]]` and asks enumerability per key rather
1623        // than reading the object's own table.
1624        let keys = match self.import_attribute_keys(&with) {
1625            Ok(keys) => keys,
1626            Err(Signal::Throw(reason)) => return Some(reason),
1627            Err(_) => return None,
1628        };
1629        // 10.d.v: each value is read (observably) and has to be a string.
1630        for key in keys {
1631            let value = match self.read_field(&Value::Object(with_object.clone()), &key) {
1632                Ok(value) => value,
1633                Err(Signal::Throw(reason)) => return Some(reason),
1634                Err(_) => continue,
1635            };
1636            if !matches!(value, Value::String(_)) {
1637                return Some(self.type_error_value("import attribute values must be strings"));
1638            }
1639        }
1640        None
1641    }
1642
1643    /// A `TypeError` as a value, for the reject paths above.
1644    fn type_error_value(&mut self, message: &str) -> Value {
1645        self.make_error("TypeError", message)
1646    }
1647
1648    /// `EnumerableOwnPropertyNames(value, key)` (§7.3.23), as a list of string keys.
1649    ///
1650    /// The key list is snapshotted first and enumerability is asked per key as the walk
1651    /// reaches it, which is the order the algorithm specifies and the one a `Proxy` can
1652    /// observe. Symbols are dropped: an import attribute name is a String.
1653    fn import_attribute_keys(&mut self, value: &Value) -> JsResult<Vec<String>> {
1654        let Some(object) = value.as_object().cloned() else {
1655            return Ok(Vec::new());
1656        };
1657        let mut out = Vec::new();
1658        for key in self.object_own_property_keys(&object)? {
1659            let Some(name) = key.as_wtf8() else {
1660                // A symbol key is not an import attribute name.
1661                continue;
1662            };
1663            let enumerable = self
1664                .object_get_own_property(&object, &key)?
1665                .is_some_and(|property| property.enumerable);
1666            if enumerable {
1667                out.push(name.to_string_lossy().into_owned());
1668            }
1669        }
1670        Ok(out)
1671    }
1672
1673    /// The module name a dynamic import's specifier is resolved against.
1674    ///
1675    /// The innermost frame that has a *real file* name. `eval` and `std.evalScript` compile
1676    /// their bodies under pseudo-names (`<input>`, `<evalScript>`) because that is what a
1677    /// stack trace should say, and §19.2.1.1's `GetActiveScriptOrModule` makes an eval'd body
1678    /// belong to the script that called it — never to a file named `<input>`. Resolving
1679    /// `import('./x.js')` against `<input>` produced the specifier `x.js` with no directory,
1680    /// which the loader then looked for in the working directory.
1681    ///
1682    /// So frames are walked outermost-last until one names something path-like; a pseudo-name
1683    /// (`<…>`) is skipped for the same reason a `<builtin>` frame is not a referrer.
1684    fn import_referrer(&self) -> String {
1685        self.script_or_module_file_name()
1686            .or_else(|| self.module_stack.last().cloned())
1687            .or_else(|| self.main_module_name.clone())
1688            .unwrap_or_default()
1689    }
1690
1691    /// Evaluate a pending dynamic import and settle its promise.
1692    pub fn run_dynamic_import(
1693        &mut self,
1694        specifier: &str,
1695        referrer: &str,
1696        promise: &Gc<JsObject>,
1697        phase: ImportPhase,
1698    ) {
1699        let outcome = self
1700            .load_module(specifier, &[], referrer)
1701            .and_then(|module| {
1702                self.link_module(&module)?;
1703                // `import.defer(x)` resolves once the module is *loaded and linked*, and
1704                // hands back the namespace object without evaluating anything — that is
1705                // the entire difference from `import(x)`, and it is why the promise still
1706                // rejects for a missing or unparsable module.
1707                if phase == ImportPhase::Defer {
1708                    // The async part of the graph still runs: `InnerModuleEvaluation` would
1709                    // gather a deferred request's asynchronous transitive dependencies, and a
1710                    // dynamic import has no importer to do it for it. So the module's own
1711                    // top-level-await dependencies are evaluated here, and the promise
1712                    // resolves with an unevaluated module either way.
1713                    self.evaluate_async_transitive_dependencies(&module)?;
1714                    return self.module_deferred_namespace(&module);
1715                }
1716                if phase == ImportPhase::Source {
1717                    // §16.2.1.7.2 `GetModuleSource`: a Source Text Module Record — which is
1718                    // the only kind this engine has — always answers with a `SyntaxError`,
1719                    // "a source phase import is not available". The *load* still happens
1720                    // first, which is why a missing file rejects with the loader's error
1721                    // instead: the promise settles one step later than the resolution.
1722                    return Err(Signal::Throw(self.make_error(
1723                        "SyntaxError",
1724                        "a source phase import is not available for this module",
1725                    )));
1726                }
1727                let name = module.with(|r| r.name.clone());
1728                self.module_stack.push(name);
1729                let evaluated = self.evaluate_module_body(&module);
1730                self.module_stack.pop();
1731                evaluated?;
1732                self.module_namespace(&module)
1733            });
1734        match outcome {
1735            Ok(namespace) => self.fulfill_promise(promise, namespace),
1736            Err(Signal::Throw(reason)) => self.reject_promise(promise, reason),
1737            Err(other) => {
1738                let _ = other;
1739            }
1740        }
1741    }
1742}
1743
1744/// The registry key for a module: its canonical name plus the attributes that decided
1745/// what it means.
1746///
1747/// Without the attributes, `import m from "./x.json"` and
1748/// `import m from "./x.json" with { type: "text" }` would collide on one record and the
1749/// second import would silently receive the first one's value.
1750fn cache_key(name: &str, attributes: &[(String, String)]) -> String {
1751    if attributes.is_empty() {
1752        return name.to_string();
1753    }
1754    let mut key = name.to_string();
1755    for (key_name, value) in attributes {
1756        key.push('\u{0}');
1757        key.push_str(key_name);
1758        key.push('=');
1759        key.push_str(value);
1760    }
1761    key
1762}
1763
1764/// Which kind of module `name` and `attributes` describe.
1765///
1766/// A `type` attribute wins; the `.json` suffix only decides when no attribute was given.
1767/// That is what makes `import m from "./m.json" with { type: "text" }` a string while
1768/// `import m from "./m.json"` is an object.
1769fn module_kind(name: &str, attributes: &[(String, String)]) -> Result<ModuleKind, String> {
1770    let declared = attributes
1771        .iter()
1772        .find(|(key, _)| key == "type")
1773        .map(|(_, value)| value.as_str());
1774    let kind = match declared {
1775        // `json5` is accepted by the reference as an alias for a dialect that permits
1776        // comments and trailing commas; this parser is strict JSON, so a document that
1777        // needs the extension fails loudly rather than silently parsing differently.
1778        Some("json") | Some("json5") => ModuleKind::Json,
1779        Some("text") => ModuleKind::Text,
1780        Some("bytes") => ModuleKind::Bytes,
1781        // An unknown type is an error rather than a fallback to JavaScript: silently
1782        // evaluating `with { type: "cbor" }` as code would run a data file.
1783        Some(other) => return Err(format!("unsupported module type: '{other}'")),
1784        None => {
1785            if name.ends_with(".json") {
1786                ModuleKind::Json
1787            } else {
1788                ModuleKind::JavaScript
1789            }
1790        }
1791    };
1792    Ok(kind)
1793}