JavaScript: a .mjs script runs as an ECMAScript 2015 module

script.run, File > Scripts and Other Script... run a file ending in .mjs as a
module: strict code with import and export declarations at its top level.
parse_module reads the module grammar and its early errors, and
Realm::start_module and Realm::run_module load the module graph through the
host, link every import before any module runs, and run each module once,
after the modules it imports. Imports read the exporting binding each time;
a read before initialization is a ReferenceError and an assignment is a
TypeError. import * as ns gives a namespace object that is not extensible,
and Object.isSealed and Object.isFrozen on it throw a ReferenceError for an
export its module has not initialized.

Specifiers are ./ and ../ paths to .mjs and .js files, resolved against the
importing file and read only through the script's file scope, so a module
can import only from the script's folder and the folders below it. Bare
names, URLs and absolute paths are a SyntaxError that names the specifier.
Module files count against the #include limits: 64 files besides the
script, 16 imports deep. import and export stay syntax errors in .js and
.jsx scripts; import() is not read. script.listInstalled lists .mjs files.

The test262 runner also runs the module tests under language/module-code,
import and export, reading the fixture files they import from the suite.
This commit is contained in:
dotCooCoo committed 2026-11-22 12:16:11 -08:00
1 parent 69be58d0d4
commit 7615aed3ee
52 files changed
+2270 -110

No files matched your search

+125 -4
View File
@@ -37,11 +37,21 @@
//!
//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of
//! the file it is in.
//!
//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules
//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing
//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL
//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would
//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`],
//! so a link that leads out of the script's folder is refused as well. Module files count against
//! the same limits as included files, and the paths of one file (two spellings, a link, or names
//! that differ only in letter case on Windows) give one module.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use vectorcraft_js::{DirectiveName, Options};
use vectorcraft_js::{DirectiveName, LoadError, Options};
use crate::file_access::{ScriptRead, ScriptScope};
@@ -219,13 +229,57 @@ pub(crate) struct Files {
frames: Vec<Frame>,
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
es2015: bool,
/// The modules a module run has read, by key ([`module_key`]): the names of the folders each
/// is in, below the script's folder.
module_dirs: HashMap<String, Vec<String>>,
/// The key of each module path read, below the script's folder.
module_paths: HashMap<String, String>,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
/// ECMAScript 5.1 with the ExtendScript extensions.
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
/// run as ECMAScript 5.1 with the ExtendScript extensions.
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
}
/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case).
pub(crate) fn module_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs"))
}
/// What names the file at the real path `real` among a run's modules: on Unix its device and file
/// number, so two paths to one file give one module; elsewhere its path, in lowercase on Windows,
/// whose file names ignore letter case.
fn module_key(real: &Path) -> String {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let Ok(m) = std::fs::metadata(real) {
return format!("{}:{}", m.dev(), m.ino());
}
}
let shown = display(real).to_string();
if cfg!(windows) { shown.to_lowercase() } else { shown }
}
/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between
/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error.
fn specifier_names(specifier: &str) -> Result<Vec<&str>, LoadError> {
let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}")));
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
return wrong("must start with './' or '../'");
}
if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) {
return wrong("must not contain \\, : or control characters");
}
let names: Vec<&str> = specifier.split('/').collect();
let file = names.last().copied().unwrap_or_default();
let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default();
if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) {
return wrong("must name a .mjs or .js file");
}
Ok(names)
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -321,9 +375,76 @@ impl Files {
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
es2015: es2015_script(path),
module_dirs: HashMap::new(),
module_paths: HashMap::new(),
}
}
/// The module `text`, the script's own, as a source of one file. → its key and the source.
pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> {
self.bytes = self.bytes.saturating_add(text.len());
let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default();
self.module_dirs.insert(key.clone(), Vec::new());
let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None }))
}
/// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or
/// this function gave). → the module's key, with its text and source map the first time the
/// run reads it.
pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> {
let names = specifier_names(specifier)?;
let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?;
for name in names {
match name {
"" | "." => {}
".." => {
if path.pop().is_none() {
return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'")));
}
}
name => path.push(name.to_string()),
}
}
let relative = path.join("/");
if let Some(key) = self.module_paths.get(&relative) {
return Ok((key.clone(), None));
}
let root =
self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?;
self.probes += 1;
if self.probes > MAX_PROBES {
return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached")));
}
let candidate = path.iter().fold(root, |p, name| p.join(name));
let (real, bytes) = match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) {
Ok(found) => found,
Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))),
Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))),
Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))),
Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))),
};
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
return Err(LoadError::Range("script source limit reached (32 MiB)".to_string()));
}
self.bytes += bytes.len();
let key = module_key(&real);
self.module_paths.insert(relative, key.clone());
if self.module_dirs.contains_key(&key) {
return Ok((key, None));
}
if self.files >= MAX_FILES {
return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached")));
}
self.files += 1;
let text = decode(&bytes, specifier).map_err(LoadError::Other)?;
path.pop();
self.module_dirs.insert(key.clone(), path);
let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
Ok((key, Some((text, map))))
}
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }