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