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