From bc5b1f3229734cad2d44e95eee4902bfe5500355 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:29:17 -0800 Subject: [PATCH] Correct module namespace bindings and export resolution limits --- crates/js/src/interp.rs | 17 ++++++--- crates/js/src/module.rs | 67 +++++++++++++++++++++++++++++----- crates/js/src/module_tests.rs | 47 ++++++++++++++++++++++++ crates/js/src/parser/module.rs | 55 +++++++++++++++++++++++++--- crates/js/src/realm.rs | 18 +++++---- docs/target-app-parity.md | 2 +- 6 files changed, 178 insertions(+), 28 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 5355f26704..7d3797396c 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1545,12 +1545,13 @@ impl Interp { _ => return internal("not a declarative environment"), }, Resolved::Obj { object, with_this } => { + let owned = !with_this && object == self.global && self.get_own_property(object, &name)?.is_some(); let deleted = self.delete(object, &name, false)?; // A deleted global variable no longer stops a `let` or `const` of its name: the // global environment's DeleteBinding drops it from its var names (ECMA-262 2015 // section 8.1.1.4.7). Deleting the global object's property by any other route // leaves the name recorded. - if deleted && !with_this && object == self.global { + if deleted && owned { self.global_vars.remove(&name); } deleted @@ -3767,10 +3768,14 @@ impl Interp { /// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit /// order and distinct. pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult { - let bytes = exports.iter().map(|(k, _)| binding_bytes(k.len()).saturating_mul(2)).sum::(); - self.reserve_heap(OBJECT_BYTES.saturating_add(bytes).saturating_add(PROP_BYTES))?; + let names = exports.iter().map(|(name, _)| string_bytes(name.len())).sum::(); + let bindings = PROP_BYTES.saturating_mul(exports.len()); + let tag = self.well_known(|symbols| &symbols.to_string_tag); + let tagged = if tag.is_some() { PROP_BYTES.saturating_add(string_bytes(6)) } else { 0 }; + let extra = bindings.saturating_add(names).saturating_add(tagged); + self.reserve_heap(OBJECT_BYTES.saturating_add(bindings).saturating_add(extra))?; let mut object = Object::new(Class::ModuleNamespace(Box::default()), None); - if let Some(tag) = self.well_known(|symbols| &symbols.to_string_tag) { + if let Some(tag) = tag { object.syms.get_or_insert_with(Default::default).insert(tag, Prop::Data { value: Value::str("Module"), flags: 0 }); } object.extensible = false; @@ -3780,7 +3785,9 @@ impl Interp { object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE }); } object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports })); - Ok(self.heap.alloc_object(object)) + let namespace = self.heap.alloc_object(object); + self.heap.bytes = self.heap.bytes.saturating_add(extra); + Ok(namespace) } /// Pushes the frames of a run of modules: `modules` in the order they run, each with its code, diff --git a/crates/js/src/module.rs b/crates/js/src/module.rs index 63fa656041..454a357870 100644 --- a/crates/js/src/module.rs +++ b/crates/js/src/module.rs @@ -22,7 +22,7 @@ use std::rc::Rc; use crate::ast::{ExportEntry, ImportName, ModuleInfo}; use crate::bytecode::Code; -use crate::heap::{Binding, EnvId, ObjId, Prop, key}; +use crate::heap::{Binding, Env, EnvId, ObjId, Prop, key}; use crate::interp::{Abrupt, CompileError, ErrorType, Interp}; use crate::value::Value; @@ -73,9 +73,38 @@ const MAX_MODULES: usize = 1024; /// The most `(module, name)` pairs one export's resolution visits. const MAX_RESOLVE_STEPS: usize = 1024; +#[derive(Default)] +struct ResolveSeen { + pairs: HashSet, + count: usize, +} + +struct ResolveKey { + module: usize, + name: String, +} + +impl PartialEq for ResolveKey { + fn eq(&self, other: &Self) -> bool { + #[cfg(test)] + RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(count.get() + 1)); + self.module == other.module && self.name == other.name + } +} + +impl Eq for ResolveKey {} + +impl std::hash::Hash for ResolveKey { + fn hash(&self, state: &mut H) { + std::hash::Hash::hash(&(self.module, &self.name), state); + } +} + #[cfg(test)] thread_local! { pub(crate) static RESOLVED_STAR_EDGES: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static RESOLVE_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static RESOLVE_MEMBERSHIP_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// A loaded module. @@ -267,6 +296,11 @@ impl Graph<'_, '_> { let code = self.records[i].code.clone(); let envs = self.interp.instantiate_module(&code).map_err(LinkFail::Run)?; self.records[i].envs = Some(envs); + for import in &self.records[i].info.imports { + if matches!(&import.import, ImportName::Namespace) { + self.interp.add_import(envs.1, key(&import.local.name), Binding::lexical(true)).map_err(LinkFail::Run)?; + } + } } Ok(()) } @@ -283,16 +317,20 @@ impl Graph<'_, '_> { /// ResolveExport (section 15.2.1.16.3): where the export `name` of module `m` comes from, /// `None` when the module has no such export (or only through a cycle). - fn resolve_export(&mut self, m: usize, name: &str, seen: &mut Vec<(usize, String)>) -> Result, Ambiguous>, LinkFail> { - if seen.iter().any(|(sm, sn)| *sm == m && sn == name) { + fn resolve_export(&mut self, m: usize, name: &str, seen: &mut ResolveSeen) -> Result, Ambiguous>, LinkFail> { + #[cfg(test)] + RESOLVE_CALLS.with(|count| count.set(count.get() + 1)); + let visit = ResolveKey { module: m, name: name.to_string() }; + if seen.pairs.contains(&visit) { return Ok(Ok(None)); } - if seen.len() >= MAX_RESOLVE_STEPS { + if seen.count >= MAX_RESOLVE_STEPS { let message = format!("export resolution limit ({MAX_RESOLVE_STEPS} steps) reached for '{name}'"); return Err(LinkFail::Run(self.interp.throw(ErrorType::Range, &message))); } self.interp.use_fuel().map_err(LinkFail::Run)?; - seen.push((m, name.to_string())); + seen.pairs.insert(visit); + seen.count += 1; let Some(record) = self.records.get(m) else { return Ok(Ok(None)) }; // The module's own export of the name, looked up in its index, comes before any `export *`. let explicit = record.explicit.get(name).and_then(|&i| record.info.exports.get(i)); @@ -381,7 +419,7 @@ impl Graph<'_, '_> { self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?; let mut resolved = Vec::new(); for name in names { - if let Ok(Some(r)) = self.resolve_export(m, &name, &mut Vec::new())? { + if let Ok(Some(r)) = self.resolve_export(m, &name, &mut ResolveSeen::default())? { resolved.push((key(&name), r)); } } @@ -424,7 +462,7 @@ impl Graph<'_, '_> { if self.target(m, *request).is_none() { continue; } - match self.resolve_export(m, export_name, &mut Vec::new())? { + match self.resolve_export(m, export_name, &mut ResolveSeen::default())? { Ok(Some(_)) => {} Ok(None) => { let message = format!("the module '{}' has no export to give as '{export_name}'", self.specifier(m, *request)); @@ -443,7 +481,7 @@ impl Graph<'_, '_> { let local = key(&imp.local.name); let binding = match &imp.import { ImportName::Namespace => self.namespace_binding(t)?, - ImportName::Name(n) => match self.resolve_export(t, n, &mut Vec::new())? { + ImportName::Name(n) => match self.resolve_export(t, n, &mut ResolveSeen::default())? { Ok(Some(Resolution::Binding { module, name })) => match self.binding_of(module, &name) { Some((target_env, target_name)) => Binding::import(target_env, target_name), None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))), @@ -459,7 +497,18 @@ impl Graph<'_, '_> { } }, }; - self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?; + if matches!(&imp.import, ImportName::Namespace) { + self.interp.use_fuel().map_err(LinkFail::Run)?; + let Some(Env::Decl { bindings, .. }) = self.interp.heap.env_mut(env) else { + return Err(LinkFail::Run(Abrupt::Internal("namespace import environment not found".into()))); + }; + let Some(slot) = bindings.get_mut(&local) else { + return Err(LinkFail::Run(Abrupt::Internal("namespace import binding not found".into()))); + }; + *slot = binding; + } else { + self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?; + } } } Ok(()) diff --git a/crates/js/src/module_tests.rs b/crates/js/src/module_tests.rs index 23eae8ce67..487140836f 100644 --- a/crates/js/src/module_tests.rs +++ b/crates/js/src/module_tests.rs @@ -11,6 +11,53 @@ fn es() -> Realm { realm } +#[test] +fn global_var_records_survive_deleting_only_an_inherited_property() { + let mut realm = es(); + realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap(); + assert_eq!(realm.run("var w; delete this.w; Object.prototype.w = 7; delete w;"), Ok(JsValue::Bool(true))); + let error = realm.run("let w = 2; w;").unwrap_err(); + assert!(matches!(error.kind, RunErrorKind::Syntax | RunErrorKind::Thrown), "{error:?}"); + + let mut realm = es(); + realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap(); + assert_eq!(realm.run("var w; delete w;"), Ok(JsValue::Bool(true))); + assert_eq!(realm.run("let w = 2; w;"), Ok(JsValue::Number(2.0))); +} + +#[test] +fn namespace_allocations_charge_binding_tables_and_symbols() { + use crate::heap::{OBJECT_BYTES, PROP_BYTES, key}; + let mut realm = es(); + let interp = realm.interp(); + let before = interp.heap.bytes; + let exports = (0..128).map(|n| (key(&format!("v{n}")), None)).collect(); + let namespace = interp.module_namespace(exports, &[]).unwrap(); + let symbols = interp.heap.object(namespace).unwrap().syms.as_ref().map_or(0, |symbols| symbols.len()); + let required = OBJECT_BYTES + PROP_BYTES * (128 * 2 + symbols); + assert!(interp.heap.bytes - before >= required, "namespace charged {} bytes, needs at least {required}", interp.heap.bytes - before); +} + +#[test] +fn export_resolution_membership_work_is_bounded_per_visit() { + let mut files: Vec<(String, String)> = (0..31).map(|n| (format!("./m{n}.mjs"), format!("export * from './m{}.mjs';", n + 1))).collect(); + let source = (0..32).map(|n| format!("export var v{n} = {n};")).collect(); + files.push(("./m31.mjs".into(), source)); + let references: Vec<_> = files.iter().map(|(name, source)| (name.as_str(), source.as_str())).collect(); + let mut load = loader(&references); + let mut realm = es(); + crate::module::RESOLVE_CALLS.with(|count| count.set(0)); + crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(0)); + realm + .run_module("main.mjs", "import * as ns from './m0.mjs'; out.push(ns.v0, ns.v31);", ModuleLimits { modules: 64, depth: 64 }, &mut load) + .unwrap(); + let visits = crate::module::RESOLVE_CALLS.with(std::cell::Cell::get); + let checks = crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(std::cell::Cell::get); + assert!(visits > 32); + assert!(checks <= visits * 4, "{checks} membership checks for {visits} export visits"); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("0|31".into()))); +} + #[test] fn star_aliases_resolve_each_canonical_target_once_per_name() { let exports: String = (0..100).map(|n| format!("export var v{n} = {n};")).collect(); diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index bccea717a1..353668f1a9 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -322,8 +322,8 @@ impl Parser<'_> { /// The early errors of the exports as a whole (section 15.2.1.1): no name exported twice, and /// each name an `export { … }` list takes from the module itself declared or imported there. An - /// exported import becomes a re-export of what it imports (section 15.2.1.16.1; a namespace - /// import as ECMA-262 2020 reads `export * as ns from`). + /// exported named import becomes a re-export of its imported binding (section 15.2.1.16.1). + /// A namespace import keeps its local binding. fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec) -> Result<()> { #[cfg(test)] EXPORT_SEARCH_STEPS.with(|steps| steps.set(0)); @@ -339,8 +339,10 @@ impl Parser<'_> { } let imported = imports.get(&ImportLocal(&c.local)); let entry = match imported { - Some(i) => ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }, - None => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span }, + Some(i) if matches!(&i.import, ImportName::Name(_)) => { + ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span } + } + _ => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span }, }; info.exports.push(entry); } @@ -363,6 +365,49 @@ mod tests { use super::{EXPORT_SEARCH_STEPS, REQUEST_SEARCH_STEPS}; use crate::{Options, parse_module}; + fn run_namespace_modules(main: &str, files: &[(&str, &str)]) -> (Result, crate::Realm) { + let mut realm = crate::Realm::with_options(Options { es2015: true, ..Options::default() }, crate::Limits::default()); + realm.run("var out = [];").unwrap(); + let mut load = |_: &str, specifier: &str| { + files.iter().find(|(name, _)| *name == specifier).map_or_else( + || Err(crate::LoadError::Other(format!("missing module {specifier}"))), + |(_, source)| Ok(crate::LoadedModule { key: specifier.into(), source: Some((*source).into()) }), + ) + }; + let result = realm.run_module("main.mjs", main, crate::ModuleLimits::default(), &mut load); + (result, realm) + } + + #[test] + fn namespace_reexport_bindings_keep_their_origin() { + let files = [ + ("./a.mjs", "import * as ns from './shared.mjs'; export {ns};"), + ("./b.mjs", "import * as ns from './shared.mjs'; export {ns};"), + ("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"), + ("./shared.mjs", "export var value = 7;"), + ]; + let (result, _) = run_namespace_modules("import {ns} from './barrel.mjs'; out.push(ns.value);", &files); + assert!(result.as_ref().is_err_and(|error| error.message.contains("ambiguous")), "{result:?}"); + let files = [ + ("./a.mjs", "import {value} from './shared.mjs'; export {value};"), + ("./b.mjs", "import {value} from './shared.mjs'; export {value};"), + ("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"), + ("./shared.mjs", "export var value = 7; export function change() { value = 9; }"), + ]; + let (result, mut realm) = + run_namespace_modules("import {value} from './barrel.mjs'; import {change} from './shared.mjs'; change(); out.push(value);", &files); + assert!(result.is_ok(), "{result:?}"); + assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("9".into()))); + } + + #[test] + fn namespace_reexports_link_through_cycles() { + let files = [("./a.mjs", "import * as ns from './b.mjs'; export {ns};"), ("./b.mjs", "import * as ns from './a.mjs'; export {ns};")]; + let (result, mut realm) = run_namespace_modules("import * as a from './a.mjs'; out.push(a.ns.ns === a);", &files); + assert!(result.is_ok(), "{result:?}"); + assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into()))); + } + #[test] fn module_specifiers_reject_legacy_octal_escapes() { for source in @@ -417,7 +462,7 @@ mod tests { assert!(matches!(export, crate::ExportEntry::Indirect { export_name, request: 0, import: crate::ast::ImportName::Name(name), .. } if export_name == &format!("exported{index}") && name == "value")); } - assert!(matches!(info.exports[count], crate::ExportEntry::Indirect { request: 1, import: crate::ast::ImportName::Namespace, .. })); + assert!(matches!(&info.exports[count], crate::ExportEntry::Local { export_name, local, .. } if export_name == "namespace" && local == "ns")); assert!( matches!(&info.exports[count + 1], crate::ExportEntry::Indirect { request: 0, import: crate::ast::ImportName::Name(name), .. } if name == "value") ); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 522597f7ae..ad8b0bb020 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -605,16 +605,17 @@ impl Realm { self.interp.script_name = name; } - /// Which source the last error's `line` and `column` are in: 0 for the script last given to - /// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a - /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which - /// includes code from an earlier script and from the sources given during its run. + /// Which source the last error's `line` and `column` are in: 0 for the most recent script or + /// module entry source. Later sources are numbered from 1 as tags are assigned: modules in + /// load order, then sources a [`crate::HostItem::Evaluator`] gives. Module execution order + /// can differ from load order. A script run without modules numbers only evaluator sources. + /// [`UNKNOWN_SOURCE`] includes code from earlier runs and their module or evaluator sources. pub fn error_source(&self) -> u32 { self.source_of(self.interp.error_tag) } /// The source tag of the code the last error's `line` and `column` are in, which stays the same - /// from run to run: each script given to [`Realm::run`] or [`Realm::start`] and each source a + /// from run to run: each script or module entry, each dependency loaded, and each source a /// [`crate::HostItem::Evaluator`] gives gets the next tag, so a function an earlier script /// defined has its script's tag. [`UNKNOWN_SOURCE`] for code that `eval` or `Function` /// compiled, an error with no place, and sources given once the tags are used up. @@ -622,9 +623,10 @@ impl Realm { self.interp.error_tag } - /// The source tag ([`Realm::error_tag`]) of the script the last [`Realm::run`] or - /// [`Realm::start`] compiled; the `n`th source an evaluator gave during that run has this tag - /// plus `n`. [`UNKNOWN_SOURCE`] when that call compiled nothing. + /// The source tag ([`Realm::error_tag`]) of the most recent script or module entry source. + /// Dependency modules receive subsequent tags in load order, followed by evaluator sources + /// as they are given. A script run without modules assigns subsequent tags only to evaluator + /// sources. [`UNKNOWN_SOURCE`] when no entry tag has been assigned or the tags are used up. pub fn script_tag(&self) -> u32 { self.script_tag } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0262881cce..ec9aca2491 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1120,7 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1 when run as scripts. With `module: true`, they run as modules and accept these ECMAScript 2015 forms. Classes and generators are still syntax errors, and so are `import` and `export` outside a module (the modules entry below). `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files and modules read them and `.jsx` files and `source` strings that run as scripts do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.