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