Merge pull request #9132 from dotCooCoo/feat/js-es2015-modules

JavaScript: a .mjs script runs as an ECMAScript 2015 module
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-28 20:44:58 -08:00
commit 2255484d45
58 files changed
+3438 -188

No files matched your search

+7 -4
View File
@@ -18,7 +18,7 @@ use crate::script;
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
/// The extensions of the scripts `script.run` takes as a file, in any case.
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"];
/// Does `path` name a file `script.run` takes?
pub fn runs(path: &str) -> bool {
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event Line truncated
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler Line truncated
always,
run
),
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Installed Scripts",
[],
None,
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
"{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
always,
list_installed
),
@@ -198,6 +198,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
let fuel = max_fuel(p)?;
let installed = switch_or(p, "installed", false, "script.run")?;
let module = switch_or(p, "module", script::include::module_script(path), "script.run")?;
let mut checked_real = None;
let text = match (path, source) {
(Some(""), None) => return Err(param("`path` is empty")),
@@ -213,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
return Err(EngineError::Other(COMPILED.to_string()));
}
if !runs(path) {
return Err(param("`path` must name a .js or .jsx file"));
return Err(param("`path` must name a .js, .mjs or .jsx file"));
}
// One byte more than a script may have shows that the file is too large.
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
@@ -242,6 +243,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
fuel,
locale,
answers,
module,
actions,
})
}
@@ -444,6 +446,7 @@ impl Session {
fuel,
locale,
answers: vec![],
module: script::include::module_script(path.to_str()),
actions: vec![],
};
let runs = self.script_runs;
+28 -1
View File
@@ -715,6 +715,15 @@ impl ScriptScope {
/// The real path of the file at `path` and its first `max` bytes, at most.
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
match self.read_unless(path, max, |_| false)? {
(real, Some(bytes)) => Ok((real, bytes)),
(_, None) => Err(ScriptRead::Failed("the file was not read".to_string())),
}
}
/// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened:
/// → its real path and no bytes.
pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option<Vec<u8>>), ScriptRead> {
use std::io::Read;
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
return Err(ScriptRead::Refused);
@@ -730,6 +739,9 @@ impl ScriptScope {
if !self.allows(&real) {
return Err(ScriptRead::Refused);
}
if known(&real) {
return Ok((real, None));
}
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?;
if !meta.is_file() {
@@ -747,7 +759,7 @@ impl ScriptScope {
if std::fs::canonicalize(path).ok().as_ref() != Some(&real) {
return Err(ScriptRead::Refused);
}
Ok((real, bytes))
Ok((real, Some(bytes)))
}
/// The first granted folder, as people read it (`None` for a script given as text).
@@ -966,6 +978,21 @@ mod tests {
p.to_string_lossy().into_owned()
}
/// A file the caller already has is not opened: its size is not checked and no byte is read.
#[test]
fn a_known_script_file_is_not_read_again() {
let (base, _) = folders("known");
std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap();
let scope = ScriptScope::of_folder(&base.join("in"));
let path = base.join("in/big.js");
assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge));
let real = std::fs::canonicalize(&path).unwrap();
assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None)));
assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64)));
assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused));
let _ = std::fs::remove_dir_all(base);
}
/// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind
/// only one grants is not granted.
#[test]
+2 -2
View File
@@ -1,4 +1,4 @@
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
//!
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
@@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
}
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
pub fn holds(root: &Path, path: &Path) -> bool {
+166 -8
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,65 @@ 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>,
/// The key [`Files::module_entry`] gave the script, in a module run.
entry_key: Option<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 real path, which on Windows
/// spells each name in the letter case the folder stores it in, so two spellings of one file in a
/// folder that ignores case give one module and two files in a folder that does not stay two.
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());
}
}
display(real).to_string()
}
/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is
/// not `root` or below it, or has a name that is not Unicode.
fn names_below(root: &Path, dir: &Path) -> Option<Vec<String>> {
dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect()
}
/// 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 +383,91 @@ 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(),
entry_key: None,
}
}
/// Makes the run's files read ECMAScript 2015, as a module run given as text does.
pub(crate) fn read_es2015(&mut self) {
self.es2015 = true;
}
/// 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());
self.entry_key = Some(key.clone());
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.clone(), |p, name| p.join(name));
// Another path to a module already read gives that module: the file is not read again, and
// its text is not counted again.
let loaded = &self.module_dirs;
let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real)));
let (real, bytes) = match read {
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}"))),
};
let key = module_key(&real);
let Some(bytes) = bytes else {
self.module_paths.insert(relative, key.clone());
return Ok((key, None));
};
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
return Err(LoadError::Range("script source limit reached (32 MiB)".to_string()));
}
if self.files >= MAX_FILES {
return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached")));
}
let text = decode(&bytes, specifier).map_err(LoadError::Other)?;
self.bytes += bytes.len();
self.files += 1;
self.module_paths.insert(relative, key.clone());
// The module's relative imports start from the folder the file is in, whichever path to it
// was read first; the path as written stands in when that folder is not below the script's.
path.pop();
let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path);
self.module_dirs.insert(key.clone(), dir);
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, e4x: true, ..Options::default() }
@@ -362,12 +506,26 @@ impl Files {
self.expand(shown, dir, text, true)
}
/// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its
/// preprocessor lines read. It becomes the file being run until [`Files::end_eval`].
pub(crate) fn eval_file(&mut self, path: &str) -> Result<Expanded, Failure> {
/// The folder of the module `key` ([`Files::module`] gave it), from the script's folder.
pub(crate) fn module_dir(&self, key: &str) -> Option<PathBuf> {
let names = self.module_dirs.get(key)?;
let root = self.frames.first().and_then(|f| f.dir.clone())?;
Some(names.iter().fold(root, |p, name| p.join(name)))
}
/// The script's folder when the run is a module run ([`Files::module_entry`] read the script),
/// or `None` for a script run.
pub(crate) fn entry_module_dir(&self) -> Option<PathBuf> {
self.module_dir(self.entry_key.as_deref()?)
}
/// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder
/// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It
/// becomes the file being run until [`Files::end_eval`].
pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option<PathBuf>) -> Result<Expanded, Failure> {
let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 };
let dir = self.frames.last().and_then(|f| f.dir.clone());
let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone()));
let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?;
let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?;
let shown = display(&real);
+75 -10
View File
@@ -66,7 +66,8 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind,
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress,
Realm, RunError, RunErrorKind,
};
use crate::{
@@ -207,6 +208,8 @@ pub(crate) struct Request {
pub locale: String,
/// The answers to the dialogs of a run with nobody to ask, in order.
pub answers: Vec<DialogAnswer>,
/// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]).
pub module: bool,
/// The actions `app.doScript` can play.
pub actions: Vec<actions::Playable>,
}
@@ -784,6 +787,9 @@ struct Host {
script_map: RefCell<include::SourceMap>,
/// The same for each source `$.evalFile` gave, in order.
eval_maps: RefCell<Vec<include::SourceMap>>,
/// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a
/// module's, by its index there.
module_maps: RefCell<HashMap<usize, String>>,
/// The file, line and column of each error `$.evalFile` raised for a file it could not run, in
/// order: the error's mark ([`HostError::Marked`]) is its index.
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
@@ -979,6 +985,22 @@ impl Host {
}
}
/// The folder of the module whose source has `tag`, when it is a module of a module run: the
/// script itself or a module it imported (not a file `$.evalFile` gave, or code from another
/// run).
fn module_dir_at(&self, tag: u32) -> Option<std::path::PathBuf> {
let script = self.script_tag.get();
if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE {
return None;
}
let n = tag.checked_sub(script)?;
if n == 0 {
return self.files.borrow().entry_module_dir();
}
let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?;
self.files.borrow().module_dir(&key)
}
/// Adds a line to the run's console and, during a slice, to the session's.
fn line(&self, entry: console::Entry, cut: bool) {
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
@@ -1596,6 +1618,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
}),
strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())),
site: true,
}
};
let mut items = vec![
@@ -1610,9 +1633,17 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in
/// milliseconds, is taken and not waited on: the file is read at once.
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
/// run (for a call in a module the script imported, that module's file), with its preprocessor
/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not
/// waited on: the file is read at once. `args` starts with the call's place, as
/// [`HostItem::Evaluator`] gives it with `site`.
fn eval_file(host: &Host, mut args: Vec<Data>) -> std::result::Result<Data, HostError> {
let tag = match args.first() {
Some(Data::Number(n)) if args.len() >= 3 => *n as u32,
_ => vectorcraft_js::UNKNOWN_SOURCE,
};
args.drain(..3.min(args.len()));
let module_dir = host.module_dir_at(tag);
let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else {
return Err(HostError::Type(EVAL_NO_PATH.to_string()));
};
@@ -1626,7 +1657,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
}
host.charge_call(path.len() as u64 + 2)?;
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
let expanded = host.files.borrow_mut().eval_file(path, module_dir).map_err(|f| {
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
let error = match f.kind {
include::FailKind::Limit => HostError::Abort(message),
@@ -1736,6 +1767,22 @@ fn explained(e: &RunError) -> String {
}
}
/// The module `specifier` names for the module `referrer` of the run of `host`, read through the
/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order
/// the modules are read, which is the order of their sources' tags.
fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result<LoadedModule, LoadError> {
let (key, read) = host.files.borrow_mut().module(referrer, specifier)?;
let source = read.map(|(text, map)| {
let mut maps = host.eval_maps.borrow_mut();
host.module_maps.borrow_mut().insert(maps.len(), key.clone());
maps.push(map);
drop(maps);
host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::<Vec<u16>>());
text
});
Ok(LoadedModule { key, source })
}
/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own.
fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
let (kind, message) = match f.kind {
@@ -2153,7 +2200,19 @@ impl Session {
self.script_stop.clear();
self.script_report = None;
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
let expanded = files.expand_script(&request.source);
if request.module {
files.read_es2015();
}
// A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines;
// `module_key` names it among the modules it imports.
let (expanded, module_key) = if request.module {
match files.module_entry(&request.source) {
Ok((key, expanded)) => (Ok(expanded), Some(key)),
Err(f) => (Err(f), None),
}
} else {
(files.expand_script(&request.source), None)
};
let name = match &expanded {
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
_ => request.name,
@@ -2184,9 +2243,8 @@ impl Session {
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
// `.js` run that names it, and keeps it as it keeps its globals.
let es2015 = include::es2015_script(request.file.as_deref());
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
let es2015 = request.module || include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
@@ -2255,6 +2313,7 @@ impl Session {
files: RefCell::new(files),
script_map: RefCell::default(),
eval_maps: RefCell::default(),
module_maps: RefCell::default(),
eval_failures: RefCell::default(),
script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE),
report_name: Arc::from(name.as_str()),
@@ -2319,7 +2378,13 @@ impl Session {
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
.and_then(|()| {
let r = realm.start(&expanded.source);
let r = match &module_key {
None => realm.start(&expanded.source),
Some(key) => {
let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH };
realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier))
}
};
// Source that does not compile defines no code, so its map is not kept.
if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) {
host.script_tag.set(realm.script_tag());
+1
View File
@@ -184,6 +184,7 @@ mod script_engines;
mod script_folder;
mod script_include;
mod script_io;
mod script_modules;
mod script_run;
mod script_scriptui;
mod script_styles;
+1
View File
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
fuel: script::DEFAULT_FUEL,
locale: "en_US".into(),
answers: Vec::new(),
module: false,
actions: Vec::new(),
};
s.script_start(request).unwrap();
+315
View File
@@ -0,0 +1,315 @@
//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of
//! specifiers and paths, the run's limits, and errors at the file they are in.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::*;
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
base
}
fn write(path: &Path, text: &str) {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(path, text).unwrap();
}
/// Runs `main/<file>` in `base`, with the text `text`.
fn run_file(base: &Path, file: &str, text: &str) -> (Result<Value>, Session) {
let main = base.join("main").join(file);
write(&main, text);
let mut s = Session::new();
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()}));
(r, s)
}
fn run(base: &Path, text: &str) -> Result<Value> {
run_file(base, "main.mjs", text).0
}
/// The report of the run of `main/main.mjs` that failed.
fn failed(base: &Path, text: &str) -> Value {
let (r, s) = run_file(base, "main.mjs", text);
assert!(r.is_err(), "the run failed: {r:?}");
s.script_report().unwrap().clone()
}
fn message(report: &Value) -> &str {
report["message"].as_str().unwrap_or_default()
}
#[test]
fn script_module_imports_from_its_folder_and_below() {
let base = folder("imports");
write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';");
write(
&base.join("main/lib/use.mjs"),
"import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();",
);
let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);";
let r = run(&base, text).unwrap();
// count.mjs ran once: use.mjs and the script share its binding.
assert_eq!(r["log"], json!([[2, "lib", true, true]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_two_modules_import_each_other() {
let base = folder("cycle");
write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }");
write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();");
let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap();
assert_eq!(r["log"], json!([["ab", "ab"]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_path_above_the_script_folder_is_refused() {
let base = folder("above");
write(&base.join("outside.mjs"), "export var leaked = 1;");
let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';");
assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}");
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}");
// `..` names that stay inside are read by name.
write(&base.join("main/sub/x.mjs"), "export var x = 'x';");
let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap();
assert_eq!(r["log"], json!(["x"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_missing_file_is_named() {
let base = folder("missing");
write(&base.join("main/a.mjs"), "import './nope.mjs';");
let report = failed(&base, "import './a.mjs';");
assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}");
assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}");
assert_eq!(report["line"], 1);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() {
let base = folder("specifiers");
// The specifier as the script writes it, as the error names it, and why it is refused.
for (written, shown, why) in [
("lib", "lib", "must start with './' or '../'"),
("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"),
("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"),
("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"),
("./C:x.mjs", "./C:x.mjs", "must not contain"),
("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"),
("./x.txt", "./x.txt", "must name a .mjs or .js file"),
("./x", "./x", "must name a .mjs or .js file"),
] {
let report = failed(&base, &format!("import '{written}';"));
let expected = format!("SyntaxError: module specifier '{shown}' {why}");
assert!(message(&report).starts_with(&expected), "{written}: {report}");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_errors_are_at_the_file_they_are_in() {
let base = folder("errors");
write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;");
let report = failed(&base, "import { a } from './bad.mjs';");
assert_eq!(report["kind"], "syntax", "{report}");
assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}");
assert_eq!(report["line"], 2);
write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');");
let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);");
assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}");
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}");
let report = failed(&base, "import { b } from './thrower.mjs';");
assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_preprocessor_lines_and_scripts_differ_by_extension() {
let base = folder("kinds");
write(&base.join("main/lib.jsxinc"), "var included = 1;");
// A module has no preprocessor lines.
let report = failed(&base, "#include \"lib.jsxinc\"\n");
assert_eq!(report["kind"], "syntax", "{report}");
// A .js or .jsx script does not read import or export.
for file in ["main.js", "main.jsx"] {
let (r, s) = run_file(&base, file, "import { a } from './a.mjs';");
assert!(r.is_err(), "{file}");
assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_files_count_against_the_include_limits() {
let base = folder("limits");
for i in 0..70 {
write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1));
}
let report = failed(&base, "import './m0.mjs';");
assert!(message(&report).contains("limit"), "{report}");
assert_eq!(report["log"], json!([]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_paths_of_one_file_give_one_module() {
let base = folder("same");
write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;");
let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string();
// Windows file names ignore letter case.
if cfg!(windows) {
text.push_str("import { v as u } from './ONCE.mjs';\n");
}
let r = run(&base, &text).unwrap();
assert_eq!(r["log"], json!(["ran"]));
let _ = std::fs::remove_dir_all(base);
}
/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere.
/// `false` when the system does not allow it here.
fn link_folder(target: &Path, link: &Path) -> bool {
#[cfg(windows)]
{
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success());
made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok()
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, link).is_ok()
}
#[cfg(not(any(unix, windows)))]
{
let _ = (target, link);
false
}
}
#[test]
fn script_module_link_out_of_the_folder_is_refused() {
let base = folder("link");
write(&base.join("outside/x.mjs"), "export var leaked = 1;");
if !link_folder(&base.join("outside"), &base.join("main").join("away")) {
eprintln!("skipped: a folder link can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);");
assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_is_listed_and_taken_by_path() {
assert!(cmd::scripts::runs("tool.MJS"));
let base = folder("text");
let root = base.join("Scripts");
write(&root.join("tool.mjs"), "export var a = 1;");
let mut s = Session::new();
s.attach_scripts_dir(root.clone());
let listed = s.execute("script.listInstalled", &json!({})).unwrap();
assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}]));
// A script given as text is not a module, whatever its name.
let mut s = Session::new();
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"}));
assert!(r.is_err());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_is_chosen_by_the_module_param() {
let mut s = Session::new();
let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap();
assert_eq!(r["log"], json!([[1, true]]));
// A source run as a module imports no files.
let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true}));
assert!(r.is_err());
assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report());
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
// `module: false` runs a .mjs file as a script, where `export` is a syntax error.
let base = folder("param");
let main = base.join("main").join("main.mjs");
write(&main, "export var a = 1;");
let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false}));
assert!(r.is_err());
assert_eq!(s.script_report().unwrap()["kind"], "syntax");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_read_again_through_another_path_is_not_counted_again() {
let base = folder("budget");
// 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run.
let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024));
write(&base.join("main/lib/big.mjs"), &big);
let mut text = String::new();
for i in 0..5 {
if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) {
eprintln!("skipped: a folder link can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n"));
}
text.push_str("vc.log(v0 + v4);");
let r = run(&base, &text);
assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2])));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_imports_are_read_from_the_folder_the_file_is_in() {
let base = folder("realdir");
write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;");
write(&base.join("main/real/dep.mjs"), "export const d = 'real';");
write(&base.join("main/other/dep.mjs"), "export const d = 'other';");
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
#[cfg(not(any(unix, windows)))]
let linked = false;
if !linked {
eprintln!("skipped: a file link can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap();
assert_eq!(r["log"], json!(["real"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_eval_file_reads_beside_the_module_that_calls_it() {
let base = folder("evalfile");
write(&base.join("main/helper.jsx"), "'top'");
write(&base.join("main/sub/helper.jsx"), "'sub'");
write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');");
let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap();
assert_eq!(r["log"], json!([["sub", "top"]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() {
let base = folder("evalfile-entry");
write(&base.join("main/helper.jsx"), "'top'");
write(&base.join("main/sub/helper.jsx"), "'sub'");
// The file in `sub` calls the script's function while it is the file being run.
write(&base.join("main/sub/caller.jsx"), "$.global.load()");
let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));";
let r = run(&base, text).unwrap();
assert_eq!(r["log"], json!(["top"]));
let _ = std::fs::remove_dir_all(base);
}
+1 -1
View File
@@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() {
let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []}));
assert_eq!(r["started"], false);
assert_eq!(r["ok"], false);
assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}");
assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}");
}
#[test]
+56
View File
@@ -619,6 +619,62 @@ pub struct Program {
pub(crate) supers: crate::parser::SuperRules,
}
/// The name an import takes from the module it names, or an export from a module it re-exports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImportName {
/// The export of this name (`default` for a default import).
Name(String),
/// The module's namespace object (`* as ns`).
Namespace,
}
/// A module a module imports or re-exports from: the specifier as written and where it stands.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ModuleRequest {
/// The specifier as text, with each unpaired surrogate written as U+FFFD.
pub specifier: String,
/// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16,
/// ModuleRequests). It may hold an unpaired surrogate, which no host path can name.
pub units: Vec<u16>,
pub span: Span,
}
/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImportEntry {
/// The index of the module in [`ModuleInfo::requests`].
pub request: usize,
pub import: ImportName,
/// The name bound in the importing module.
pub local: Name,
}
/// One name a module exports (ExportEntry).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExportEntry {
/// `export_name` is the module's own binding `local` (`*default*` for a default export of an
/// expression or an anonymous function).
Local { export_name: String, local: String, span: Span },
/// `export_name` is the export `import` of the module `request` (`export { a as b } from`,
/// `export * as ns from`, or an exported import).
Indirect { export_name: String, request: usize, import: ImportName, span: Span },
/// Every export of the module `request` but `default` (`export * from`).
Star { request: usize, span: Span },
}
/// What a module imports and exports, read by [`crate::parse_module`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ModuleInfo {
/// The modules it names, each specifier once, in the order they first appear.
pub requests: Vec<ModuleRequest>,
pub imports: Vec<ImportEntry>,
pub exports: Vec<ExportEntry>,
}
/// The binding name of a default export that has no name of its own (ECMA-262 2015 section
/// 15.2.3.5); no identifier can name it.
pub const DEFAULT_BINDING: &str = "*default*";
impl Program {
/// The line and column (both from 1, the column in UTF-16 code units) of a source offset.
pub fn line_column(&self, offset: u32) -> (u32, u32) {
+2 -2
View File
@@ -591,7 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_prop_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
}
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
@@ -610,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_prop_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
}
// ---- Function ----
+3 -3
View File
@@ -139,7 +139,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _:
let o = interp.to_object(&arg(args, 0))?;
interp.rooted(&[Value::Object(o)], |interp| {
let k = interp.to_prop_key(&arg(args, 1))?;
match interp.get_own_pk(o, &k)? {
match interp.own_pk(o, &k)? {
Some(p) => from_prop(interp, &p),
None => Ok(Value::Undefined),
}
@@ -282,7 +282,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
let o = *o;
for k in own_prop_keys(interp, o)? {
interp.use_fuel()?;
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
let Some(prop) = interp.own_pk(o, &k)? else { continue };
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
return Ok(Value::Bool(false));
}
@@ -311,7 +311,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
let mut names = Vec::new();
for k in interp.own_keys(o)? {
interp.use_fuel()?;
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
names.push(k);
}
}
+67 -23
View File
@@ -98,6 +98,8 @@ struct FnCompiler<'a> {
recursion: u32,
/// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own.
es2015: bool,
/// The code is a module's ([`compile_module`]), which has no completion value.
module: bool,
scopes: Vec<BlockScope>,
templates: Vec<Template>,
uses_this: bool,
@@ -156,6 +158,7 @@ impl<'a> FnCompiler<'a> {
uses_arguments: false,
recursion,
es2015: false,
module: false,
scopes: Vec::new(),
templates: Vec::new(),
uses_this: false,
@@ -169,6 +172,12 @@ impl<'a> FnCompiler<'a> {
}
}
/// Script and eval code keep the value of the last expression statement as their
/// completion value; function and module code do not.
fn keeps_completion(&self) -> bool {
self.kind != CodeKind::Function && !self.module
}
// ---- emitting ----
fn emit(&mut self, op: Op) {
@@ -270,8 +279,10 @@ impl<'a> FnCompiler<'a> {
let mut seen = HashSet::new();
// The `let` and `const` names and the block functions of each statement list and loop the
// walk enters, with the index of the one around it; the body's are first, and its
// functions are var-scoped.
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, self.lexical_names(body), HashSet::new())];
// functions are var-scoped. Only Annex B's block functions read them, so without
// [`crate::Options::es2015`] none is collected.
let top = if self.es2015 { self.lexical_names(body) } else { HashSet::new() };
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, top, HashSet::new())];
let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
let mut add_var = |out: &mut Hoisted, k: Key| {
if seen.insert(k.clone()) {
@@ -306,7 +317,7 @@ impl<'a> FnCompiler<'a> {
}
}
Stmt::Block(list) => {
let s = enter(self.lexical_names(list), self.block_function_names(list));
let s = if inner { enter(self.lexical_names(list), self.block_function_names(list)) } else { scope };
work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
}
Stmt::If { consequent, alternate, .. } => {
@@ -314,7 +325,7 @@ impl<'a> FnCompiler<'a> {
// (Annex B.3.4).
for &branch in alternate.iter().chain(std::iter::once(consequent)) {
let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_)));
let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope };
let s = if alone && inner { enter(HashSet::new(), HashSet::new()) } else { scope };
work.push((branch, nested || inner, s));
}
}
@@ -347,30 +358,38 @@ impl<'a> FnCompiler<'a> {
work.push((*body, nested || inner, s));
}
Stmt::Switch { cases, .. } => {
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
let s = enter(names, funcs);
let s = if inner {
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
enter(names, funcs)
} else {
scope
};
for case in cases.iter().rev() {
work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
}
}
Stmt::Try { block, handler, finalizer } => {
if let Some(f) = finalizer {
let s = enter(self.lexical_names(f), self.block_function_names(f));
let s = if inner { enter(self.lexical_names(f), self.block_function_names(f)) } else { scope };
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
}
if let Some(h) = handler {
// A `var` cannot redeclare a destructured catch parameter's names
// (ECMA-262 11th edition section B.3.5), so a block function of that name
// in the body is not also made a `var` (section B.3.3).
let mut names = self.lexical_names(&h.body);
if matches!(h.param, Binding::Pattern(_)) {
names.extend(self.bound_keys(&h.param));
}
let s = enter(names, self.block_function_names(&h.body));
let s = if inner {
// A `var` cannot redeclare a destructured catch parameter's names
// (ECMA-262 11th edition section B.3.5), so a block function of that
// name in the body is not also made a `var` (section B.3.3).
let mut names = self.lexical_names(&h.body);
if matches!(h.param, Binding::Pattern(_)) {
names.extend(self.bound_keys(&h.param));
}
enter(names, self.block_function_names(&h.body))
} else {
scope
};
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
}
let s = enter(self.lexical_names(block), self.block_function_names(block));
let s = if inner { enter(self.lexical_names(block), self.block_function_names(block)) } else { scope };
work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
}
Stmt::Expr(_)
@@ -493,7 +512,10 @@ impl<'a> FnCompiler<'a> {
fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
for d in decls {
match (d.init, &d.target) {
(Some(init), Binding::Name(name)) => self.named_expr(init, &name.name)?,
(Some(init), Binding::Name(name)) => {
let public_name = if name.name == crate::ast::DEFAULT_BINDING { "default" } else { &name.name };
self.named_expr(init, public_name)?;
}
(Some(init), Binding::Pattern(_)) => self.expr(init)?,
(None, Binding::Name(_)) => self.emit(Op::Undefined),
(None, Binding::Pattern(_)) => return internal("a destructuring declaration without an initializer"),
@@ -552,7 +574,7 @@ impl<'a> FnCompiler<'a> {
Stmt::Empty | Stmt::Debugger => Ok(()),
Stmt::Expr(e) => {
self.expr(*e)?;
self.emit(if self.kind == CodeKind::Function { Op::Pop } else { Op::SetCompletion });
self.emit(if self.keeps_completion() { Op::SetCompletion } else { Op::Pop });
Ok(())
}
Stmt::Block(list) => self.block(list),
@@ -1016,8 +1038,12 @@ impl<'a> FnCompiler<'a> {
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
self.statement_completion_start();
self.expr(*discriminant)?;
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
let scope = self.list_scope(&all, true)?;
let scope = if self.es2015 {
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
self.list_scope(&all, true)?
} else {
None
};
if let Some(scope) = scope {
self.emit(Op::PushBlock(scope));
self.env_depth += 1;
@@ -1247,7 +1273,7 @@ impl<'a> FnCompiler<'a> {
self.bind(fin_entry);
// In script and eval code the finally block keeps the completion value of the try or
// catch block when it ends normally (ECMA-262 5.1 section 12.14).
let keeps_completion = self.kind != CodeKind::Function;
let keeps_completion = self.keeps_completion();
if keeps_completion {
self.emit(Op::GetCompletion);
}
@@ -2519,7 +2545,10 @@ pub(crate) fn compile_function(
class_ctor: f.is_class_constructor(),
derived: f.kind == FunctionKind::DerivedConstructor,
pattern_names,
own_name: es2015.then(|| key_of(f.name.as_ref().map_or("", |n| n.name.as_str()))),
own_name: es2015.then(|| {
let name = f.name.as_ref().map_or("", |n| n.name.as_str());
key_of(if f.kind == FunctionKind::Declaration && name == crate::ast::DEFAULT_BINDING { "default" } else { name })
}),
method: (f.home && !f.is_class_constructor())
|| (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)),
};
@@ -2539,6 +2568,21 @@ pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kin
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
}
/// Compiles a module's statements ([`crate::parse_module`]): strict code that runs in an
/// environment of its own, as strict eval code does, and returns `undefined`.
pub(crate) fn compile_module(program: &crate::Program, source: &Rc<Source>) -> CResult<Rc<Code>> {
let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0);
c.es2015 = true;
c.module = true;
let hoisted = c.hoist(&program.body, &[])?;
let top_scope = c.list_scope(&program.body, false)?;
c.stmts(&program.body)?;
c.emit(Op::Undefined);
c.emit(Op::Return);
let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX);
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
}
/// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program
/// must be that one parenthesized function expression and nothing else. The name `anonymous` is
/// not bound inside the function (section 15.3.2.1).
+27 -2
View File
@@ -119,8 +119,16 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
syntax("'use strict'; { function f() {} function f() {} }");
syntax("for (let x = 1 in {}) {}");
syntax("if (1) let x = 1;");
// No statement starts with `let [`, in a statement list or in the body of an `if` or a loop.
for body in ["if (true) let[0];", "if (false) ; else let[0];", "while (false) let[0];", "for (;false;) let[0];", "lbl: let[0];"] {
syntax(&format!("var let = [1]; {body}"));
}
// Outside strict mode code `let` is still a name where no declaration can start.
truth("var let = 3; let === 3");
truth("var let = [1]; var r; if (true) (let[0]); if (true) r = let[0]; r === 1");
truth("var let = [2]; if (true) let\n; let.length === 1");
// ECMAScript 5.1 reads it as a property read.
assert_eq!(Realm::new().run("var let = [1]; if (true) let[0];"), Ok(JsValue::Number(1.0)));
truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
// A labeled function in a block declares its name in the block.
syntax("{ let f; label: function f() {} }");
@@ -202,7 +210,7 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}");
assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0)));
let restricted = realm.run("let undefined = 1;");
assert!(restricted.is_err(), "{restricted:?}");
assert!(is_thrown(&restricted, "SyntaxError"), "{restricted:?}");
}
#[test]
@@ -388,8 +396,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() {
assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0)));
// Deleting the property itself, not through the global environment, keeps the record
// (ECMA-262 2015 sections 12.5.3.2 and 8.1.1.4.7).
// Deleting the global object's property, not the variable, leaves the name declared
// (ECMA-262 2015 section 8.1.1.4.7 runs only for `delete w`).
assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true)));
assert!(is_thrown(&realm.run("let w = 4;"), "SyntaxError"));
let after_property = realm.run("let w = 4; w");
assert!(is_thrown(&after_property, "SyntaxError"), "{after_property:?}");
assert_eq!(realm.run("(0, eval)('var v = 1'); with (this) delete v"), Ok(JsValue::Bool(true)));
let after_with = realm.run("let v = 4; v");
assert!(is_thrown(&after_with, "SyntaxError"), "{after_with:?}");
assert_eq!(realm.run("(0, eval)('var u = 1'); with (this) { delete u; }"), Ok(JsValue::Bool(true)));
assert!(is_thrown(&realm.run("let u = 5;"), "SyntaxError"));
// Deleting a name the global object only inherits deletes no variable.
@@ -525,6 +539,17 @@ fn arrow_functions_cannot_be_constructed() {
truth("((a, b) => 0).length === 2");
}
#[test]
fn an_arrow_functions_length_is_configurable_and_read_only() {
truth(
"var d = Object.getOwnPropertyDescriptor((a) => a, 'length'); \
d.configurable && !d.writable && !d.enumerable && d.value === 1",
);
truth("var f = (a, b) => 0; delete f.length && !f.hasOwnProperty('length')");
// In ECMAScript 2015 code the other functions' `length` is configurable too (section 19.2.4.1).
truth("var d = Object.getOwnPropertyDescriptor(function (a) {}, 'length'); d.configurable && !d.writable && !d.enumerable");
}
#[test]
fn bad_arrow_functions_are_syntax_errors() {
syntax("var f = x\n=> x;");
+2
View File
@@ -305,6 +305,8 @@ impl Interp {
completion,
boundary,
generator: Some(generator),
chained: false,
pending_module: false,
});
Ok(())
}
+54 -3
View File
@@ -199,7 +199,7 @@ pub(crate) enum Func {
Pausable { f: crate::interp::PausableFn, name: &'static str },
Host { f: Rc<HostFn>, name: Rc<str> },
Data { f: DataFn, name: Rc<str>, read: crate::host::ArgRead },
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str> },
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str>, site: bool },
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
}
@@ -272,6 +272,9 @@ pub(crate) enum Class {
Xmp(Box<crate::xmp::Meta>),
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
XmpFile(Box<PropMap<Value>>),
/// A module namespace object (ECMA-262 2015 section 9.4.6): its own properties are the
/// module's exports, read live from the bindings they name.
ModuleNamespace(Box<ModuleExports>),
/// An object of a class a host defined ([`crate::host_classes`]).
Host(crate::host_classes::HostObj),
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
@@ -598,6 +601,8 @@ impl Class {
Class::String(_) => "String",
Class::RegExp(_) => "RegExp",
Class::Date(_) => "Date",
// The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1).
Class::ModuleNamespace(_) => "Module",
Class::UnitValue(_) => "UnitValue",
Class::Map(_) => "Map",
Class::Set(_) => "Set",
@@ -644,17 +649,49 @@ pub(crate) struct Binding {
/// A `let` or `const` binding, or a function declared in a block: a `var` that eval code
/// declares cannot take its name.
pub(crate) lexical: bool,
/// A module's import of another module's binding (ECMA-262 2015 section 8.1.1.5.5,
/// CreateImportBinding): reading it reads the binding of that name in that environment, and
/// writing it is a `TypeError`. `value` is unused.
pub(crate) import: Option<(EnvId, Key)>,
}
impl Binding {
/// An initialized binding.
pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self {
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false }
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false, import: None }
}
/// A `let` (or with `constant`, a `const`) binding not yet initialized.
pub(crate) fn lexical(constant: bool) -> Self {
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true }
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true, import: None }
}
/// An import of the binding `name` of the environment `env`.
pub(crate) fn import(env: EnvId, name: Key) -> Self {
Self {
value: Value::Undefined,
mutable: false,
deletable: false,
uninitialized: false,
constant: true,
lexical: true,
import: Some((env, name)),
}
}
}
/// A module namespace object's exports (ECMA-262 2015 section 9.4.6): each exported name, in
/// code unit order, with the environment and name of the binding it reads, or `None` for an export
/// whose value is fixed (another module's namespace object), kept in the object's own property.
#[derive(Clone, Debug, Default)]
pub(crate) struct ModuleExports {
pub(crate) bindings: Vec<(Key, Option<(EnvId, Key)>)>,
}
impl ModuleExports {
/// The binding the export `name` reads, when it reads one.
pub(crate) fn binding(&self, name: &[u16]) -> Option<&(EnvId, Key)> {
self.bindings.binary_search_by(|(k, _)| (**k).cmp(name)).ok().and_then(|i| self.bindings.get(i)).and_then(|(_, b)| b.as_ref())
}
}
@@ -1103,6 +1140,16 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
work.push(map.env.0);
extra = ARG_NAME_BYTES * map.names.len();
}
Class::ModuleNamespace(exports) => {
for (k, b) in &exports.bindings {
strings.add_key(k);
if let Some((env, name)) = b {
work.push(env.0);
strings.add_key(name);
}
}
extra = PROP_BYTES * exports.bindings.len();
}
Class::String(s) => strings.add(s),
Class::RegExp(re) => {
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
@@ -1233,6 +1280,10 @@ fn trace_env(e: &Env, work: &mut Vec<u32>, strings: &mut StringSizes) -> usize {
for (k, b) in bindings.iter() {
strings.add_key(k);
mark_value(&b.value, work, strings);
if let Some((env, name)) = &b.import {
work.push(env.0);
strings.add_key(name);
}
}
ENV_BYTES + PROP_BYTES * bindings.len()
}
+14 -5
View File
@@ -160,11 +160,14 @@ pub enum HostItem {
/// that is not a string is the call's result. `end` is called when the source has run,
/// normally or not. Each source given has the next tag of [`crate::Realm::error_source`],
/// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`]
/// for that source alone; with `None` it takes the calling code's.
/// for that source alone; with `None` it takes the calling code's. With `site`, `source` is
/// given the [`CallSite`] of the code that calls it first, as the three numbers its source
/// tag, line and column, and the arguments after them.
Evaluator {
source: HostFunction,
end: Rc<dyn Fn()>,
strict_writes: Rc<dyn Fn() -> Option<bool>>,
site: bool,
},
/// A read-only property that reads the interpreter's own state.
Script(ScriptItem),
@@ -466,7 +469,8 @@ impl Interp {
/// source it gives as global code, as an indirect `eval` does, giving that code's completion
/// value. A result that is not a string is given to the script as it is. `end` is called once
/// the source has run, normally or not. `strict_writes` gives the source's
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's.
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. With `site`,
/// `f` is given the calling code's [`CallSite`] before the arguments.
pub(crate) fn call_evaluator(
&mut self,
f: &crate::heap::DataFn,
@@ -474,8 +478,13 @@ impl Interp {
strict_writes: &Rc<dyn Fn() -> Option<bool>>,
name: &Rc<str>,
args: &[Value],
site: bool,
) -> JsResult<Value> {
let data = self.read_args(name, None, args, &ArgRead::Data)?;
let caller = site.then(|| self.call_site());
let mut data = self.read_args(name, None, args, &ArgRead::Data)?;
if let Some(caller) = caller {
data.splice(0..0, site_data(caller));
}
let source = match f(data) {
Ok(Data::String(source)) => source,
Ok(d) => return self.write_data(d, 0, false),
@@ -689,9 +698,9 @@ impl Interp {
HostItem::Converted(list, f) => {
Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE }
}
HostItem::Evaluator { source, end, strict_writes } => {
HostItem::Evaluator { source, end, strict_writes, site } => {
let proto = self.intrinsics.function_proto;
let func = Func::Eval { f: source, end, strict_writes, name: full.into() };
let func = Func::Eval { f: source, end, strict_writes, name: full.into(), site };
let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto)));
Prop::Data { value: Value::Object(f), flags: ENUMERABLE }
}
+31 -6
View File
@@ -433,7 +433,7 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
Ok(Data::Number(f64::from(s.line)))
});
let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap();
r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap();
let first = r.script_tag();
@@ -455,6 +455,31 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag()));
}
/// An evaluator made with `site` is given the place of the code that calls it before its
/// arguments; one made without it is given only the arguments.
#[test]
fn an_evaluator_with_site_is_told_where_it_is_called() {
let mut r = realm(10_000_000);
let given: Rc<RefCell<Vec<Vec<Data>>>> = Rc::default();
let evaluator = |site: bool| {
let log = given.clone();
let source: HostFunction = Rc::new(move |a| {
log.borrow_mut().push(a);
Ok(Data::String("1".into()))
});
HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site }
};
r.define_host_object("host", vec![("at".into(), evaluator(true)), ("plain".into(), evaluator(false))]).unwrap();
r.run("\n\n host.at('x');\nhost.plain('y');").unwrap();
let tag = f64::from(r.script_tag());
let given = given.borrow();
assert_eq!(given.len(), 2, "{given:?}");
assert_eq!(given[0].len(), 4, "{given:?}");
assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}");
assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}");
assert_eq!(given[1], vec![Data::String("y".into())]);
}
#[test]
fn a_text_function_takes_each_argument_as_string_gives_it() {
let mut r = realm(1_000_000);
@@ -978,7 +1003,7 @@ fn a_converted_function_reads_each_argument_as_its_list_says() {
fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() {
let mut r = realm(10_000_000);
let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
r.run("function late() { throw new Error('late'); }").unwrap();
assert!(r.run("host.load()").is_err());
@@ -1000,7 +1025,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
let s = seen.clone();
r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units)));
let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap();
assert_eq!(out, JsValue::Number(49.0));
@@ -1015,7 +1040,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() {
let mut r = realm(10_000_000);
let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet");
r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap();
@@ -1048,7 +1073,7 @@ fn an_evaluators_source_takes_fuel_before_it_is_parsed() {
let ends = Rc::new(Cell::new(0));
let ended = ends.clone();
let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17)))));
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) };
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None), site: false };
let mut r = realm(10_000);
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
let e = r.run("host.evaluate()").unwrap_err();
@@ -1069,7 +1094,7 @@ fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() {
// The source does not parse, so a parse would throw a syntax error instead.
let n = (1 << 17) + 1;
let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1)))));
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
let mut r = realm(1_000_000);
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
r.interp().collect_for_room();
+296 -18
View File
@@ -26,8 +26,8 @@ use crate::ast::BinaryOp;
use crate::bytecode::{Code, CodeKind, NamePrefix, Op, Source};
use crate::compiler::{CompileFail, compile_program};
use crate::heap::{
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES,
OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
};
use crate::parser::SuperRules;
use crate::string_builtins::flat_charged;
@@ -231,6 +231,11 @@ pub(crate) struct Frame {
pub(crate) boundary: bool,
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
pub(crate) generator: Option<ObjId>,
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
pub(crate) chained: bool,
pub(crate) pending_module: bool,
}
/// Where the exception being thrown was raised: the code and the instruction.
@@ -275,6 +280,7 @@ pub(crate) struct Interp {
pub(crate) heap: Heap,
pub(crate) stack: Vec<Value>,
pub(crate) frames: Vec<Frame>,
pending_module_frames: usize,
/// Values native code holds while it may run JavaScript.
pub(crate) temp_roots: Vec<Value>,
/// Environments native code is still building.
@@ -637,6 +643,7 @@ impl Interp {
heap,
stack: Vec::new(),
frames: Vec::new(),
pending_module_frames: 0,
temp_roots: Vec::new(),
temp_envs: Vec::new(),
temp_codes: Vec::new(),
@@ -1032,7 +1039,11 @@ impl Interp {
self.push(v)?;
return Ok(None);
}
if self.frames.last().is_some_and(|frame| frame.pending_module) {
self.pending_module_frames -= 1;
}
let frame = self.frame_mut()?;
frame.pending_module = false;
let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") };
frame.pc += 1;
match op {
@@ -1101,10 +1112,14 @@ impl Interp {
}
return Ok(());
}
let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) };
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.boundary {
if frame.chained {
// The modules under it have not started, so no handler of theirs takes it.
self.abort_to_boundary();
}
if frame.boundary || frame.chained {
self.passing = v.clone();
return Err(Abrupt::Throw(v));
}
@@ -1114,11 +1129,24 @@ impl Interp {
/// Each running frame of script code, outermost first: its code, the index of its next
/// instruction, and whether it runs a function (not global or eval code).
pub(crate) fn script_frames(&self) -> impl Iterator<Item = (&Rc<Code>, usize, bool)> {
self.frames.iter().map(|f| (&f.code, f.pc, f.callee.is_some()))
self.frames.iter().filter(|f| !f.pending_module).map(|f| (&f.code, f.pc, f.callee.is_some()))
}
pub(crate) fn clear_frames(&mut self) {
self.frames.clear();
self.pending_module_frames = 0;
}
fn pop_frame(&mut self) -> Option<Frame> {
let frame = self.frames.pop()?;
if frame.pending_module {
self.pending_module_frames -= 1;
}
Some(frame)
}
fn abort_to_boundary(&mut self) {
while let Some(frame) = self.frames.pop() {
while let Some(frame) = self.pop_frame() {
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.boundary {
@@ -1148,7 +1176,7 @@ impl Interp {
Some(_) => crate::builtins::iterator::iter_result(self, v, true)?,
None => v,
};
let Some(frame) = self.frames.pop() else { return internal("return without a frame") };
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
@@ -1160,6 +1188,9 @@ impl Interp {
if frame.boundary {
return Ok(Some(v));
}
if frame.chained {
return Ok(None);
}
self.push(v)?;
Ok(None)
}
@@ -1490,6 +1521,15 @@ impl Interp {
matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
}
/// The binding the binding `name` of the declarative environment `env` imports, when it is a
/// module's import.
fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> {
match self.heap.env(env) {
Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()),
_ => None,
}
}
fn not_initialized(&mut self, name: &[u16]) -> Abrupt {
let ident = String::from_utf16_lossy(name);
self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized"))
@@ -1502,6 +1542,14 @@ impl Interp {
/// GetValue of a reference whose base was resolved earlier (section 8.7.1).
fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> {
if let Resolved::Decl(e) = r
&& let Some((target, target_name)) = self.import_of(e, name)
{
if self.uninitialized(target, &target_name) {
return Err(self.not_initialized(name));
}
return Ok((self.binding_value(target, &target_name)?, Value::Undefined));
}
match r {
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
@@ -1521,6 +1569,12 @@ impl Interp {
/// PutValue of a reference whose base was resolved earlier (section 8.7.2).
fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> {
let strict = self.strict();
if let Resolved::Decl(e) = r
&& self.import_of(e, name).is_some()
{
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("assignment to the import '{ident}'")));
}
match r {
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => {
@@ -1726,18 +1780,59 @@ impl Interp {
return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN }));
}
}
Class::ModuleNamespace(exports) => {
if let Some((env, name)) = exports.binding(k)
&& let Some(Prop::Data { flags, .. }) = o.props.get(k)
{
return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags }));
}
}
_ => {}
}
Ok(o.props.get(k).cloned())
}
/// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like):
/// [`Self::get_own_property`], except that an export of a module namespace object read before
/// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5).
pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
self.check_namespace_export(id, k)?;
self.get_own_property(id, k)
}
/// [`Self::own_property`] for a name or a Symbol: [`Self::get_own_pk`], with the same
/// `ReferenceError` for a namespace export read before its module initialized it.
pub(crate) fn own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
if let PropKey::Str(name) = k {
self.check_namespace_export(id, name)?;
}
self.get_own_pk(id, k)
}
/// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module
/// has not initialized yet.
fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> {
if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class)
&& let Some((env, name)) = exports.binding(k)
&& self.uninitialized(*env, name)
{
return Err(self.not_initialized(k));
}
Ok(())
}
/// [[GetProperty]]: the property found on the object or its prototype chain.
pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
Ok(self.find_property_on(id, k)?.map(|(_, p)| p))
}
/// [`Self::find_property`], with the object on the prototype chain that has the property.
fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult<Option<(ObjId, Prop)>> {
let mut cur = Some(id);
let mut steps = 0usize;
while let Some(o) = cur {
if let Some(p) = self.get_own_property(o, k)? {
return Ok(Some(p));
return Ok(Some((o, p)));
}
// A typed array's prototypes are not searched for a numeric name (section 9.4.5.4).
if crate::builtins::binary::typed_key(self, o, k).is_some() {
@@ -1764,7 +1859,14 @@ impl Interp {
{
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
}
match self.find_property(start, k)? {
let found = self.find_property_on(start, k)?;
// A module's export read before the module ran is in its temporal dead zone (ECMA-262
// 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it
// through a prototype chain.
if let Some((holder, _)) = &found {
self.check_namespace_export(*holder, k)?;
}
match found.map(|(_, p)| p) {
// A name the object and its prototypes lack is the indexer's answer too.
None => match self.host_indexer(start)? {
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
@@ -1780,7 +1882,11 @@ impl Interp {
/// class: a name the object and its prototypes lack is `undefined`. For names the engine looks
/// up itself, such as `toJSON`, which a collection's indexer would answer with an error.
pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
match self.find_property(start, k)? {
let found = self.find_property_on(start, k)?;
if let Some((holder, _)) = &found {
self.check_namespace_export(*holder, k)?;
}
match found.map(|(_, p)| p) {
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
Some(Prop::Data { value, .. }) => Ok(value),
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
@@ -1892,10 +1998,26 @@ impl Interp {
}
Ok(true)
}
Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw),
_ => self.define_ordinary(id, k, desc, throw),
}
}
/// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.5): only a
/// descriptor that leaves an export as it is (enumerable, writable, not configurable, its
/// current value) succeeds.
fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult<bool> {
let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else {
return self.reject_bool(throw, k, "a module namespace object is not extensible");
};
let unchanged = desc.configurable != Some(true)
&& desc.enumerable != Some(false)
&& !desc.is_accessor()
&& desc.writable != Some(false)
&& desc.value.as_ref().is_none_or(|v| same_value(v, &value));
if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") }
}
pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
if throw {
let key = String::from_utf16_lossy(k);
@@ -2068,6 +2190,10 @@ impl Interp {
if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) {
return crate::builtins::binary::set_element(self, id, n, &v);
}
// A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9).
if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) {
return self.reject(throw, &k, "a module namespace object is read-only");
}
match self.get_own_property(id, &k)? {
Some(Prop::Data { flags, .. }) => {
if flags & WRITABLE == 0 {
@@ -2079,8 +2205,25 @@ impl Interp {
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
None => {}
}
let proto = self.object(id)?.proto;
let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten();
let mut inherited = None;
let mut cur = self.object(id)?.proto;
let mut steps = 0usize;
while let Some(o) = cur {
// A write that reaches a module namespace object on the prototype chain is refused
// there too: its [[Set]] returns false for every key.
if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) {
return self.reject(throw, &k, "a module namespace object is read-only");
}
if let Some(p) = self.get_own_property(o, &k)? {
inherited = Some(p);
break;
}
cur = self.object(o)?.proto;
steps += 1;
if steps > 1_000_000 {
return internal("prototype chain too long");
}
}
match inherited {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
@@ -2953,6 +3096,8 @@ impl Interp {
// listed or their bytes reserved must not free it.
let saved = self.temp_roots.len();
self.temp_roots.push(Value::Object(o));
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
let keys = self.enumerable_keys(o).and_then(|keys| {
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
self.reserve_heap(bytes)?;
@@ -3067,8 +3212,8 @@ impl Interp {
// keeps itself reachable.
return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?));
}
Func::Eval { f, end, strict_writes, name } => {
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?));
Func::Eval { f, end, strict_writes, name, site } => {
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?));
}
Func::Host { f: host, .. } => {
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
@@ -3157,9 +3302,7 @@ impl Interp {
/// the stack.
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
let Entry { callee, code, env, this, args, new_target } = entry;
if self.frames.len() >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
}
self.check_frame_room()?;
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
// An arrow function reads the `arguments` object of the function around it.
let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 };
@@ -3220,6 +3363,8 @@ impl Interp {
completion: Value::Undefined,
boundary,
generator: None,
chained: false,
pending_module: false,
});
Ok(())
};
@@ -3563,6 +3708,22 @@ impl Interp {
})
}
/// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the
/// source limit, with [`Self::source_tag`] as its source's tag.
pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc<Code>, crate::ModuleInfo), CompileError> {
self.source_units = self.source_units.saturating_add(units.len());
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
let options = Options { max_source_units: remaining, ..self.options.clone() };
let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?;
let writes = self.writes_mode();
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e {
CompileFail::Syntax(s) => CompileError::Syntax(s),
CompileFail::Internal(m) => CompileError::Internal(m),
})?;
Ok((code, info))
}
/// Turns a compile failure inside a running script into what it throws.
pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt {
match e {
@@ -3751,7 +3912,7 @@ impl Interp {
/// A [`LimitKind::Frames`] error when no other frame fits under the frame limit.
fn check_frame_room(&self) -> JsResult<()> {
if self.frames.len() >= self.limits.frames {
if self.frames.len() - self.pending_module_frames >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
}
Ok(())
@@ -3777,10 +3938,127 @@ impl Interp {
completion: Value::Undefined,
boundary,
generator: None,
chained: false,
pending_module: false,
});
Ok(())
}
/// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4,
/// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global
/// scope holds its variables and functions, and one inside that its `let` and `const` names,
/// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary
/// roots for the caller to remove.
pub(crate) fn instantiate_module(&mut self, code: &Rc<Code>) -> JsResult<(EnvId, EnvId)> {
// The code itself was counted when the module was loaded ([`Self::hold_module_code`]).
self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?;
let scope = self.global_lex;
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
self.temp_envs.push(env);
let lex = self.instantiate_global(code, env, env, true)?;
self.temp_envs.push(lex);
Ok((lex, env))
}
/// Adds `binding` (an import) to the module environment `env`, which must not have `name`.
pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> {
self.use_fuel()?;
// The binding's value (a namespace object) stays reachable while room is made.
self.temp_roots.push(binding.value.clone());
let reserved = self.reserve_heap(binding_bytes(name.len()));
self.temp_roots.pop();
reserved?;
self.env_insert(env, name, binding)
}
/// The environment that holds `name` of a module whose code runs in `lex` inside `env`.
pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option<EnvId> {
[lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name)))
}
/// A module namespace object for the exports `exports`, each `(name, binding)` with the
/// 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<ObjId> {
let names = exports.iter().map(|(name, _)| string_bytes(name.len())).sum::<usize>();
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) = tag {
object.syms.get_or_insert_with(Default::default).insert(tag, Prop::Data { value: Value::str("Module"), flags: 0 });
}
object.extensible = false;
for (name, _) in &exports {
self.use_fuel()?;
let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone());
object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE });
}
object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports }));
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,
/// the environment it runs in and the outer one. The last is the boundary frame, pushed first;
/// each of the others is pushed above the one that runs after it, so the first to run is on
/// top.
pub(crate) fn push_module_frames(&mut self, modules: &[(Rc<Code>, EnvId, EnvId)]) -> JsResult<()> {
for (i, (code, env, var_env)) in modules.iter().enumerate().rev() {
let last = i + 1 == modules.len();
self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?;
if let Some(frame) = self.frames.last_mut() {
frame.chained = !last;
frame.pending_module = true;
}
self.pending_module_frames += 1;
}
Ok(())
}
/// Ends module linking: drops the temporary roots from `mark` on.
pub(crate) fn drop_temp_envs(&mut self, mark: usize) {
self.temp_envs.truncate(mark);
}
pub(crate) fn temp_envs_mark(&self) -> usize {
self.temp_envs.len()
}
/// Counts a loaded module's code against the heap once, when the module is loaded, and keeps
/// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules
/// load counts it too.
pub(crate) fn hold_module_code(&mut self, code: &Rc<Code>) -> JsResult<()> {
self.charge_code(code, 0)?;
self.temp_codes.push(code.clone());
Ok(())
}
pub(crate) fn temp_codes_mark(&self) -> usize {
self.temp_codes.len()
}
/// Ends module linking: drops the modules' code held from `mark` on.
pub(crate) fn drop_temp_codes(&mut self, mark: usize) {
self.temp_codes.truncate(mark);
}
/// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it.
pub(crate) fn hold(&mut self, v: Value) {
self.temp_roots.push(v);
}
pub(crate) fn temp_roots_mark(&self) -> usize {
self.temp_roots.len()
}
pub(crate) fn drop_temp_roots(&mut self, mark: usize) {
self.temp_roots.truncate(mark);
}
/// Declaration binding instantiation for global and eval code (section 10.5). The caller has
/// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel.
///
+46 -4
View File
@@ -63,7 +63,17 @@
//! closes its iterator. In a realm made without the option and later given it with
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
//! by index and strings by code point, and throw a `TypeError` for other values.
//! Object rest properties (`{ a, ...rest }`) and modules stay syntax errors.
//! Object rest properties (`{ a, ...rest }`) stay syntax errors, and so do `import` and `export`
//! in a script.
//!
//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import`
//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a
//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module
//! once, after the modules it imports, with each import reading the exporting module's binding. In
//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does
//! not wait for a module that is still waiting for its own imports, and reading a binding of that
//! module before it is initialized throws a `ReferenceError`.
//! Dynamic `import()` is a syntax error.
//!
//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition,
//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in
@@ -129,6 +139,7 @@ mod host_classes;
mod interp;
mod iteration;
mod lexer;
mod module;
mod number;
mod number_builtins;
mod parser;
@@ -151,15 +162,16 @@ mod xmp_classes;
mod xpath;
pub use ast::{
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId,
FunctionKind, LexKind, LogicalOp, MethodKind, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece,
UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget,
ForInit, Function, FunctionId, FunctionKind, ImportEntry, ImportName, LexKind, LogicalOp, MethodKind, ModuleInfo, ModuleRequest, Name, Program,
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
};
pub use builtins::extensions::Localization;
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
pub use lexer::{Goal, Lexer};
pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader};
pub use number::to_string as number_to_string;
pub use realm::{
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
@@ -222,6 +234,34 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
}
/// Parses `source` as a module (ECMA-262 2015 section 15.2): strict mode code with
/// [`Options::es2015`]'s forms, `import` and `export` declarations at its top, and no preprocessor
/// lines, whatever `options` says about those three. Gives its statements and what it imports and
/// exports.
pub fn parse_module(source: &str, options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
let units = to_utf16(source, options)?;
parse_module_utf16(&units, options)
}
/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]).
pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
check_length(source.len(), options)?;
parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info))
}
/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module
/// ([`parse_module`]). The source must be a valid module.
pub fn tokenize_module(source: &str, options: &Options) -> Result<Vec<Token>, SyntaxError> {
let units = to_utf16(source, options)?;
check_length(units.len(), options)?;
parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens)
}
/// `options` as a module is read with them.
pub(crate) fn module_options(options: &Options) -> Options {
Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() }
}
/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the
/// code that calls it may (ECMA-262 2015 section 18.2.1.1).
pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result<Program, SyntaxError> {
@@ -324,6 +364,8 @@ mod host_tests;
#[cfg(test)]
mod interp_tests;
#[cfg(test)]
mod module_tests;
#[cfg(test)]
mod promise_tests;
#[cfg(test)]
mod reflect_tests;
+553
View File
@@ -0,0 +1,553 @@
//! Running modules (ECMA-262 2015 section 15.2.1): loading a module and the modules it imports,
//! linking their imports to the bindings their exports name, and readying them to run, each once,
//! the modules a module imports before it.
//!
//! The host maps each specifier to a module ([`ModuleLoader`], the role of section 15.2.1.17,
//! HostResolveImportedModule): it gives a key that names the module, and its source the first time
//! it gives that key. Every module is parsed and compiled before any runs, and every import is
//! linked before any runs, so a syntax error, a missing or ambiguous export, or a module the host
//! cannot give ends the run before any of its code runs. The run's [`ModuleLimits`] bound how many
//! modules it loads and how deep its imports go; parsing takes fuel for each code unit, and each
//! binding made in linking takes a unit.
//!
//! An import reads the exporting module's binding itself, so it sees each later assignment, and a
//! read before that binding is initialized (a module that imports one that imports it back) is a
//! `ReferenceError`. A module namespace object (`import * as ns`) is not extensible, has no
//! prototype, takes no writes and has the module's export names, in code unit order, as its
//! properties. `export *` passes on every name but `default`; a name two `export *` give from
//! different bindings is left out of a namespace and is a `SyntaxError` to import.
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use crate::ast::{ExportEntry, ImportName, ModuleInfo};
use crate::bytecode::Code;
use crate::heap::{Binding, Env, EnvId, ObjId, Prop, key};
use crate::interp::{Abrupt, CompileError, ErrorType, Interp};
use crate::value::Value;
/// What the host gives for a module a run imports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoadedModule {
/// What names the module: two specifiers that give one key import one module, which runs once.
pub key: String,
/// The module's source, given the first time the host gives its key in a run. `None` for a key
/// the host gave before in the same run.
pub source: Option<String>,
}
/// Why the host cannot give a module, which ends the run before any module runs: the error the
/// `import` raises, with its message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LoadError {
/// A specifier the host does not read: a `SyntaxError`.
Syntax(String),
/// A limit of the host's: a `RangeError`.
Range(String),
/// A module that is missing, refused or unreadable: an `Error`.
Other(String),
}
/// The host's map from a specifier to a module: called with the key of the importing module and
/// the specifier as written.
pub type ModuleLoader<'a> = dyn FnMut(&str, &str) -> Result<LoadedModule, LoadError> + 'a;
/// Bounds on the modules of one run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModuleLimits {
/// The most modules a run loads, the first included.
pub modules: usize,
/// The most imports from the first module to any other, along the shortest chain.
pub depth: usize,
}
impl Default for ModuleLimits {
fn default() -> Self {
Self { modules: 64, depth: 16 }
}
}
/// The most modules a run loads, whatever its limits say: [`resolve_export`] and
/// [`exported_names`] recurse once for each module at most.
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<ResolveKey>,
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<H: std::hash::Hasher>(&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<usize> = const { std::cell::Cell::new(0) };
pub(crate) static RESOLVE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static RESOLVE_MEMBERSHIP_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// A loaded module.
struct Record {
key: String,
info: ModuleInfo,
code: Rc<Code>,
tag: u32,
/// The module each of `info.requests` names, by index.
requested: Vec<usize>,
/// The environment its code runs in and the outer one, once instantiated.
envs: Option<(EnvId, EnvId)>,
namespace: Option<ObjId>,
/// Each name the module exports itself or re-exports by name, with its entry in
/// `info.exports`.
explicit: HashMap<String, usize>,
/// Each `export *` request, replaced by distinct canonical targets after loading, in order.
stars: Vec<usize>,
}
/// Why a module run could not start.
pub(crate) enum LinkFail {
/// A module does not parse; `tag` is its source's.
Syntax { tag: u32, error: crate::SyntaxError },
/// An exception, raised at `line` and `column` of the module whose source has `tag`.
At { tag: u32, line: u32, column: u32, abrupt: Abrupt },
/// A limit or an internal error, not at any place.
Run(Abrupt),
}
/// Where an export resolves to (ResolvedBinding).
#[derive(Clone, PartialEq, Eq)]
enum Resolution {
/// The binding `name` of module `module`.
Binding { module: usize, name: String },
/// The namespace object of module `module` (`export * as ns from`).
Namespace(usize),
}
/// An export that two `export *` declarations give from different places.
struct Ambiguous;
/// The modules of a run, loaded and linked.
struct Graph<'a, 'l> {
interp: &'a mut Interp,
records: Vec<Record>,
by_key: HashMap<String, usize>,
load: &'a mut ModuleLoader<'l>,
}
/// Loads the module `key` with `source` and every module it imports, instantiates and links them,
/// and gives them in the order they run, each with its code, the environment it runs in and the
/// outer one. The first module's source has tag `entry_tag`; each module loaded after it takes
/// the next tag. The environments stay in the interpreter's temporary roots for the caller to
/// remove once their frames are pushed.
pub(crate) fn link(
interp: &mut Interp,
key_name: &str,
source: &str,
entry_tag: u32,
limits: ModuleLimits,
load: &mut ModuleLoader<'_>,
) -> Result<Vec<(Rc<Code>, EnvId, EnvId)>, LinkFail> {
let mut graph = Graph { interp, records: Vec::new(), by_key: HashMap::new(), load };
if limits.modules == 0 {
return Err(graph.fail_at(0, 0, ErrorType::Range, "module limit (0) reached"));
}
graph.add(key_name.to_string(), source, entry_tag)?;
graph.load_imports(limits)?;
graph.instantiate()?;
graph.link_imports()?;
Ok(graph.evaluation_order())
}
impl Graph<'_, '_> {
/// Parses and compiles a module's source under `tag`.
fn add(&mut self, key_name: String, source: &str, tag: u32) -> Result<usize, LinkFail> {
let interp = &mut *self.interp;
let minimum_units = source.len().div_ceil(3);
if u64::try_from(minimum_units).unwrap_or(u64::MAX) > interp.fuel {
interp.prepare_source(minimum_units).map_err(LinkFail::Run)?;
}
interp.prepare_source(0).map_err(LinkFail::Run)?;
interp.prepare_source(source.encode_utf16().count()).map_err(LinkFail::Run)?;
let saved = std::mem::replace(&mut interp.source_tag, tag);
let compiled = interp.encode_source(source).and_then(|units| interp.compile_module_source(&units));
interp.source_tag = saved;
let (code, info) = match compiled {
Ok(c) => c,
Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }),
Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))),
};
// The record keeps the code from here on, so the heap counts it from here on.
self.interp.hold_module_code(&code).map_err(LinkFail::Run)?;
let mut explicit = HashMap::new();
let mut stars = Vec::new();
for (i, e) in info.exports.iter().enumerate() {
match e {
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
explicit.entry(export_name.clone()).or_insert(i);
}
ExportEntry::Star { request, .. } => stars.push(*request),
}
}
self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None, explicit, stars });
let index = self.records.len() - 1;
self.by_key.insert(key_name, index);
Ok(index)
}
/// An exception of type `t` with `message`, at the source offset `offset` of module `m`.
fn fail_at(&mut self, m: usize, offset: u32, t: ErrorType, message: &str) -> LinkFail {
let (tag, (line, column)) = match self.records.get(m) {
Some(r) => (r.tag, r.code.source.lines.line_column(offset)),
None => (crate::realm::UNKNOWN_SOURCE, (0, 0)),
};
LinkFail::At { tag, line, column, abrupt: self.interp.throw(t, message) }
}
/// Loads the modules each loaded module imports, breadth first, so a module's depth is the
/// length of the shortest chain of imports to it.
fn load_imports(&mut self, limits: ModuleLimits) -> Result<(), LinkFail> {
let max_modules = limits.modules.min(MAX_MODULES);
let mut depths = vec![0usize];
let mut i = 0;
while i < self.records.len() {
let requests: Vec<(String, bool, u32)> = self.records[i]
.info
.requests
.iter()
.map(|r| (r.specifier.clone(), char::decode_utf16(r.units.iter().copied()).all(|c| c.is_ok()), r.span.start))
.collect();
let depth = depths.get(i).copied().unwrap_or(0);
for (specifier, text, offset) in requests {
self.interp.use_fuel().map_err(LinkFail::Run)?;
// The host maps text to modules, and a specifier with an unpaired surrogate is not
// text, so it is refused here, as a host refuses a specifier it does not read.
if !text {
let message = format!("module specifier '{specifier}' is not valid text: it has an unpaired surrogate");
return Err(self.fail_at(i, offset, ErrorType::Syntax, &message));
}
let referrer = self.records[i].key.clone();
let loaded = match (self.load)(&referrer, &specifier) {
Ok(loaded) => loaded,
Err(LoadError::Syntax(why)) => return Err(self.fail_at(i, offset, ErrorType::Syntax, &why)),
Err(LoadError::Range(why)) => return Err(self.fail_at(i, offset, ErrorType::Range, &why)),
Err(LoadError::Other(why)) => return Err(self.fail_at(i, offset, ErrorType::Error, &why)),
};
let target = match (self.by_key.get(&loaded.key), loaded.source) {
(Some(&j), _) => j,
(None, None) => {
let message = format!("the module '{specifier}' was given without its source");
return Err(self.fail_at(i, offset, ErrorType::Error, &message));
}
(None, Some(source)) => {
if depth >= limits.depth {
let message = format!("import depth limit ({}) reached at '{specifier}'", limits.depth);
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
}
if self.records.len() >= max_modules {
let message = format!("module limit ({max_modules}) reached at '{specifier}'");
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
}
let tag = crate::realm::next_tag(self.records.last().map_or(0, |r| r.tag));
self.interp.evaluated = tag;
depths.push(depth + 1);
self.add(loaded.key, &source, tag)?
}
};
self.records[i].requested.push(target);
}
let mut seen_targets = HashSet::new();
let targets: Vec<usize> = self.records[i]
.stars
.iter()
.filter_map(|&request| self.records[i].requested.get(request).copied())
.filter(|target| seen_targets.insert(*target))
.collect();
self.records[i].stars = targets;
i += 1;
}
Ok(())
}
/// Makes each module's environments, with its variables, functions and `let` and `const`
/// names.
fn instantiate(&mut self) -> Result<(), LinkFail> {
for i in 0..self.records.len() {
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(())
}
/// The module the request `request` of module `m` names.
fn target(&self, m: usize, request: usize) -> Option<usize> {
self.records.get(m).and_then(|r| r.requested.get(request)).copied()
}
/// The specifier of request `request` of module `m`, as written.
fn specifier(&self, m: usize, request: usize) -> String {
self.records.get(m).and_then(|r| r.info.requests.get(request)).map(|r| r.specifier.clone()).unwrap_or_default()
}
/// 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 ResolveSeen) -> Result<Result<Option<Resolution>, 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.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.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));
match explicit {
Some(ExportEntry::Local { local, .. }) => return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))),
Some(ExportEntry::Indirect { request, import, .. }) => {
let (request, import) = (*request, import.clone());
let Some(t) = self.target(m, request) else { return Ok(Ok(None)) };
return match import {
ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))),
ImportName::Name(n) => self.resolve_export(t, &n, seen),
};
}
_ => {}
}
if name == "default" {
return Ok(Ok(None));
}
let mut star = None;
let stars = record.stars.clone();
for t in stars {
#[cfg(test)]
RESOLVED_STAR_EDGES.with(|count| count.set(count.get() + 1));
self.interp.use_fuel().map_err(LinkFail::Run)?;
match self.resolve_export(t, name, seen)? {
Err(Ambiguous) => return Ok(Err(Ambiguous)),
Ok(None) => {}
Ok(Some(r)) => match &star {
None => star = Some(r),
Some(s) if *s == r => {}
Some(_) => return Ok(Err(Ambiguous)),
},
}
}
Ok(Ok(star))
}
/// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its
/// `export *` modules but `default` included, each once.
fn exported_names(
&mut self,
m: usize,
star: bool,
visited: &mut Vec<usize>,
names: &mut Vec<String>,
seen: &mut HashSet<String>,
) -> Result<(), LinkFail> {
if visited.contains(&m) {
return Ok(());
}
visited.push(m);
let count = self.records.get(m).map_or(0, |r| r.info.exports.len());
for i in 0..count {
self.interp.use_fuel().map_err(LinkFail::Run)?;
let Some(e) = self.records.get(m).and_then(|r| r.info.exports.get(i)) else { break };
match e {
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
if !(star && export_name == "default") && !seen.contains(export_name) {
seen.insert(export_name.clone());
names.push(export_name.clone());
}
}
ExportEntry::Star { request, .. } => {
if let Some(t) = self.target(m, *request) {
self.exported_names(t, true, visited, names, seen)?;
}
}
}
}
Ok(())
}
/// The environment and name of the binding `name` of module `m`.
fn binding_of(&self, m: usize, name: &str) -> Option<(EnvId, crate::heap::Key)> {
let (lex, env) = self.records.get(m)?.envs?;
let k = key(name);
self.interp.module_binding(lex, env, &k).map(|e| (e, k))
}
/// GetModuleNamespace (section 15.2.1.18): module `m`'s namespace object, made the first time.
fn namespace(&mut self, m: usize) -> Result<ObjId, LinkFail> {
if let Some(ns) = self.records.get(m).and_then(|r| r.namespace) {
return Ok(ns);
}
let mut names = Vec::new();
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 ResolveSeen::default())? {
resolved.push((key(&name), r));
}
}
resolved.sort_by(|(a, _), (b, _)| a.cmp(b));
let mut exports = Vec::new();
let mut later = Vec::new();
for (k, r) in resolved {
match r {
Resolution::Binding { module, name } => match self.binding_of(module, &name) {
Some(b) => exports.push((k, Some(b))),
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
},
Resolution::Namespace(module) => {
exports.push((k.clone(), None));
later.push((k, module));
}
}
}
let ns = self.interp.module_namespace(exports, &[]).map_err(LinkFail::Run)?;
self.interp.hold(Value::Object(ns));
if let Some(r) = self.records.get_mut(m) {
r.namespace = Some(ns);
}
// A namespace that holds another is made first, so two that hold each other end.
for (k, module) in later {
let inner = self.namespace(module)?;
let flags = crate::heap::WRITABLE | crate::heap::ENUMERABLE;
self.interp.define(ns, k, Prop::Data { value: Value::Object(inner), flags }).map_err(LinkFail::Run)?;
}
Ok(ns)
}
/// Binds each module's imports (section 15.2.1.16.4, steps 9 and 12), after checking that
/// each re-export resolves.
fn link_imports(&mut self) -> Result<(), LinkFail> {
for m in 0..self.records.len() {
let exports = self.records[m].info.exports.clone();
for e in &exports {
let ExportEntry::Indirect { export_name, request, span, .. } = e else { continue };
if self.target(m, *request).is_none() {
continue;
}
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));
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
}
Err(Ambiguous) => {
let message = format!("the export '{export_name}' is ambiguous");
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
}
}
}
let imports = self.records[m].info.imports.clone();
let Some((_, env)) = self.records[m].envs else { return Err(LinkFail::Run(Abrupt::Internal("module not instantiated".into()))) };
for imp in imports {
let Some(t) = self.target(m, imp.request) else { continue };
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 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")))),
},
Ok(Some(Resolution::Namespace(module))) => self.namespace_binding(module)?,
Ok(None) => {
let message = format!("the module '{}' has no export named '{n}'", self.specifier(m, imp.request));
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
}
Err(Ambiguous) => {
let message = format!("the export '{n}' of the module '{}' is ambiguous", self.specifier(m, imp.request));
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
}
},
};
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(())
}
/// An immutable binding of module `m`'s namespace object.
fn namespace_binding(&mut self, m: usize) -> Result<Binding, LinkFail> {
let ns = self.namespace(m)?;
Ok(Binding { constant: true, lexical: true, ..Binding::new(Value::Object(ns), false, false) })
}
/// The modules in the order they run (section 15.2.1.16.5, ModuleEvaluation): each module
/// after the modules it imports, in the order it imports them, and each once; a module an
/// import cycle reaches again while it waits is not waited for.
fn evaluation_order(&self) -> Vec<(Rc<Code>, EnvId, EnvId)> {
let mut state = vec![0u8; self.records.len()];
let mut order = Vec::new();
let mut stack = vec![(0usize, 0usize)];
if let Some(s) = state.first_mut() {
*s = 1;
}
while let Some(top) = stack.last_mut() {
let m = top.0;
let requested = self.records.get(m).map_or(&[][..], |r| r.requested.as_slice());
if let Some(&t) = requested.get(top.1) {
top.1 += 1;
if let Some(s @ 0) = state.get_mut(t) {
*s = 1;
stack.push((t, 0));
}
continue;
}
stack.pop();
if let Some(r) = self.records.get(m)
&& let Some((lex, env)) = r.envs
{
order.push((r.code.clone(), lex, env));
}
}
order
}
}
+759
View File
@@ -0,0 +1,759 @@
use std::collections::{HashMap, HashSet};
use crate::{
JsValue, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Realm, RunError, RunErrorKind, parse, parse_module,
};
fn es() -> Realm {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
// Modules declare no globals, so they report through this array.
assert!(realm.run("var out = [];").is_ok());
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();
let stars: String = (0..100).map(|n| format!("export * from './alias{n}.mjs';")).collect();
let mut supplied = HashSet::new();
let mut load = |_: &str, specifier: &str| {
let (key, source) = if specifier == "./stars.mjs" { ("stars", &stars) } else { ("canonical", &exports) };
Ok(LoadedModule { key: key.into(), source: supplied.insert(key).then(|| source.clone()) })
};
let mut realm = es();
crate::module::RESOLVED_STAR_EDGES.with(|count| count.set(0));
realm
.run_module("main.mjs", "import * as ns from './stars.mjs'; out.push(ns.v99, Object.keys(ns).length);", ModuleLimits::default(), &mut load)
.unwrap();
let steps = crate::module::RESOLVED_STAR_EDGES.with(|count| count.get());
assert!(steps <= 200, "{steps} star edges inspected");
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("99|100".into()));
}
#[test]
fn ending_a_module_queue_restores_normal_frame_accounting() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
let mut load = loader(&[("./m.mjs", "for (var i = 0; i < 1000; i++) {}")]);
realm.start_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load).unwrap();
assert!(matches!(realm.advance(1), Ok(Progress::Paused)));
realm.end();
assert_eq!(realm.run("function f() { return 1; } f();"), Ok(JsValue::Number(1.0)));
}
#[test]
fn pending_module_bodies_do_not_consume_active_call_frames() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "function f() { return 1; } f();")];
let mut load = loader(&files);
let result = realm.run_module("main.mjs", "import './a.mjs';", ModuleLimits::default(), &mut load);
assert_eq!(result, Ok(JsValue::Undefined));
let mut load = loader(&[]);
let result = realm.run_module("main.mjs", "function f() { return f(); } f();", ModuleLimits::default(), &mut load);
assert_eq!(result.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Frames)));
}
#[test]
fn module_stack_excludes_bodies_waiting_to_run() {
let mut realm = es();
realm.define_host_object("$", [("stack".to_string(), crate::HostItem::Script(crate::ScriptItem::Stack))].into_iter().collect()).unwrap();
let (result, out) = run_with(
&mut realm,
"import './m.mjs';",
&[("./m.mjs", "function trace() { var s = $.stack; out.push(s.split('[global]').length - 1, s.indexOf('trace:') >= 0); } trace();")],
ModuleLimits::default(),
);
assert_eq!(result, Ok(JsValue::Undefined));
assert_eq!(out, "1|true");
}
#[test]
fn module_sources_charge_utf16_units_instead_of_utf8_bytes() {
let mut remaining = Vec::new();
for character in ['a', 'é', '界'] {
let source = format!("/*{}*/ export var value = 1;", character.to_string().repeat(1000));
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
let mut load = loader(&[]);
realm.start_module("main.mjs", &source, ModuleLimits::default(), &mut load).unwrap();
remaining.push(realm.fuel_left());
}
assert!(remaining.windows(2).all(|pair| pair[0] == pair[1]), "{remaining:?}");
}
#[test]
fn default_exported_functions_keep_their_public_names() {
for (source, name) in [
("export default function () {}", "default"),
("export default () => {};", "default"),
("export default (function () {});", "default"),
("export default function named() {}", "named"),
] {
let out = run("import value from './m.mjs'; out.push(value.name);", &[("./m.mjs", source)]);
assert_eq!(out, name, "{source}");
}
}
#[test]
fn symbol_writes_through_namespace_prototypes_are_refused() {
let out = run(
"import * as ns from './m.mjs'; var k = Symbol('new'), child = Object.create(ns); \
try { child[k] = 1; } catch (e) { out.push(e.name); } \
out.push(Object.getOwnPropertySymbols(child).length); \
Object.defineProperty(child, k, {value: 3, writable: true}); child[k] = 4; out.push(child[k]);",
&[("./m.mjs", "export var value = 1;")],
);
assert_eq!(out, "TypeError|0|4");
}
#[test]
fn a_namespace_exposes_its_own_immutable_symbol_tag() {
let out = run(
"import * as ns from './m.mjs'; \
var d = Object.getOwnPropertyDescriptor(ns, Symbol.toStringTag); \
out.push(ns[Symbol.toStringTag], Object.getOwnPropertySymbols(ns).length, \
d && d.writable, d && d.enumerable, d && d.configurable);",
&[("./m.mjs", "export var value = 1;")],
);
assert_eq!(out, "Module|1|false|false|false");
}
#[test]
fn modules_reject_await_identifiers_before_running_dependencies() {
for source in ["export const await = 1;", "var aw\\u0061it = 1;", "await;", "function await() {}"] {
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
}
let mut realm = es();
let mut load = loader(&[("./effect.mjs", "out.push('dependency');")]);
let result = realm.run_module("main.mjs", "import './effect.mjs'; export const await = 1;", ModuleLimits::default(), &mut load);
assert!(result.is_err());
assert_eq!(realm.run("out.length").unwrap(), JsValue::Number(0.0));
assert!(realm.run("var await = 1; await").is_ok());
}
#[test]
fn synchronous_and_sliced_modules_drain_promise_jobs() {
let source = "out.push('body'); Promise.resolve().then(function () { out.push('resolved'); }); \
Promise.reject('rejected').catch(function (e) { out.push(e); });";
for sliced in [false, true] {
let mut realm = es();
let mut load = loader(&[]);
if sliced {
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
loop {
match realm.advance(100).unwrap() {
Progress::Paused => {}
Progress::Done(value) => {
assert_eq!(value, JsValue::Undefined);
break;
}
}
}
} else {
assert_eq!(realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap(), JsValue::Undefined);
}
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("body|resolved|rejected".into()), "sliced={sliced}");
}
}
#[test]
fn starting_a_module_discards_a_paused_script() {
for (sliced, invalid) in [(false, false), (true, false), (false, true), (true, true)] {
let mut realm = es();
realm.start("out.push('old');").unwrap();
assert_eq!(realm.advance(1).unwrap(), Progress::Paused);
let mut load = loader(&[]);
let source = if invalid { "var = ;" } else { "out.push('new');" };
if invalid {
let result = if sliced {
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load)
} else {
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).map(drop)
};
assert!(result.is_err());
assert!(!realm.is_running(), "sliced={sliced}");
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String(String::new()));
continue;
}
if sliced {
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
loop {
if let Progress::Done(_) = realm.advance(100).unwrap() {
break;
}
}
} else {
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
}
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("new".into()), "sliced={sliced}");
}
}
/// A loader over `files`: each specifier is its own key, given with its source the first time.
fn loader(files: &[(&str, &str)]) -> impl FnMut(&str, &str) -> Result<LoadedModule, LoadError> + use<> {
let map: HashMap<String, String> = files.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
let mut given = HashSet::new();
move |_, specifier| {
if !specifier.starts_with('.') && specifier != "main" {
return Err(LoadError::Syntax(format!("bare specifier: {specifier}")));
}
let source = map.get(specifier).ok_or_else(|| LoadError::Other(format!("module not found: {specifier}")))?;
let first = given.insert(specifier.to_string());
Ok(LoadedModule { key: specifier.to_string(), source: first.then(|| source.clone()) })
}
}
/// Runs `entry` with the modules `files`. → the result and `out` joined with `|`.
fn run_with(realm: &mut Realm, entry: &str, files: &[(&str, &str)], limits: ModuleLimits) -> (Result<JsValue, RunError>, String) {
let mut load = loader(files);
let result = realm.run_module("main.mjs", entry, limits, &mut load);
let out = match realm.run("out.join('|')") {
Ok(JsValue::String(s)) => s,
other => panic!("{other:?}"),
};
(result, out)
}
fn run(entry: &str, files: &[(&str, &str)]) -> String {
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
(Ok(v), out) => {
assert_eq!(v, JsValue::Undefined);
out
}
(Err(e), _) => panic!("{entry}\n{e:?}"),
}
}
/// The run ends with an error whose message starts with `start`, and `out` holds `ran`.
fn fails(entry: &str, files: &[(&str, &str)], start: &str, ran: &str) -> RunError {
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
(Err(e), out) => {
assert!(e.message.starts_with(start), "{entry}: {e:?}");
assert_eq!(out, ran, "{entry}");
e
}
(Ok(_), out) => panic!("{entry}: completed with {out}"),
}
}
fn syntax(src: &str) {
assert!(parse_module(src, &Options::default()).is_err(), "{src}");
}
#[test]
fn an_import_reads_the_exporting_binding_each_time() {
let counter = "export let count = 0; export function inc() { count++; }";
let out = run("import { count, inc } from './c.mjs'; out.push(count); inc(); inc(); out.push(count);", &[("./c.mjs", counter)]);
assert_eq!(out, "0|2");
}
#[test]
fn imports_can_be_renamed_and_combined() {
let m = "export default 'd'; export var a = 1; export const b = 2;";
let out = run("import d, { a as x, b } from './m.mjs'; out.push(d, x, b);", &[("./m.mjs", m)]);
assert_eq!(out, "d|1|2");
let out = run("import d, * as ns from './m.mjs'; out.push(d, ns.a, ns['default']);", &[("./m.mjs", m)]);
assert_eq!(out, "d|1|d");
}
#[test]
fn a_destructuring_declaration_exports_every_name_it_binds() {
let m = "export const { a, b: [c, ...d] } = { a: 1, b: [2, 3, 4] }; export var [e = 5] = [];";
let out = run("import { a, c, d, e } from './m.mjs'; out.push(a, c, d.join('+'), e);", &[("./m.mjs", m)]);
assert_eq!(out, "1|2|3+4|5");
}
#[test]
fn default_exports_of_expressions_and_functions() {
let out = run("import v from './v.mjs'; out.push(v * 2);", &[("./v.mjs", "export default 20 + 1;")]);
assert_eq!(out, "42");
let out = run("import f from './f.mjs'; out.push(f());", &[("./f.mjs", "export default function () { return 'anon'; }")]);
assert_eq!(out, "anon");
// A named default function is a declaration: hoisted, and its name is bound in the module.
let f = "out.push(typeof g); export default function g() { return 'g'; }";
let out = run("import h from './f.mjs'; out.push(h());", &[("./f.mjs", f)]);
assert_eq!(out, "function|g");
}
#[test]
fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() {
let m = "export var zeta = 1; export let alpha = 2; export function mid() {} export default 3;";
let out = run(
"import * as ns from './m.mjs';
out.push(Object.keys(ns).join(','), Object.prototype.toString.call(ns), Object.isExtensible(ns), Object.getPrototypeOf(ns) === null);
try { ns.alpha = 5; } catch (e) { out.push(e.name); }
try { ns.added = 5; } catch (e) { out.push(e.name); }
try { delete ns.alpha; } catch (e) { out.push(e.name); }
out.push(ns.alpha, Object.getOwnPropertyDescriptor(ns, 'zeta').writable);",
&[("./m.mjs", m)],
);
assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true");
}
#[test]
fn a_write_that_reaches_a_namespace_through_a_prototype_is_refused() {
let m = "export var alpha = 1;";
let out = run(
"import * as ns from './m.mjs';
var o = Object.create(ns);
Object.defineProperty(o, 'own', { value: 1, writable: true });
o.own = 2;
try { o.alpha = 5; } catch (e) { out.push(e.name); }
try { o.fresh = 5; } catch (e) { out.push(e.name); }
try { Object.create(o).alpha = 5; } catch (e) { out.push(e.name); }
out.push(o.own, Object.getOwnPropertyNames(o).join(), ns.alpha, o.alpha);",
&[("./m.mjs", m)],
);
assert_eq!(out, "TypeError|TypeError|TypeError|2|own|1|1");
// A script's sloppy write is ignored.
let mut realm = es();
let out = run_with(&mut realm, "import * as ns from './m.mjs'; out.ns = ns;", &[("./m.mjs", m)], ModuleLimits::default());
assert_eq!(out, (Ok(JsValue::Undefined), String::new()));
// A namespace has no prototype, so `hasOwnProperty` is called from `Object.prototype`.
let sloppy = "var o = Object.create(out.ns), own = Object.prototype.hasOwnProperty; o.alpha = 5; o.fresh = 5; \
[own.call(o, 'alpha'), own.call(o, 'fresh'), o.alpha].join()";
assert_eq!(realm.run(sloppy), Ok(JsValue::String("false,false,1".into())));
}
#[test]
fn a_namespace_takes_only_definitions_that_change_nothing() {
let m = "export var a = 1;";
let out = run(
"import * as ns from './m.mjs';
out.push(Object.seal(ns) === ns, Object.isSealed(ns), Object.isFrozen(ns));
out.push(Object.defineProperty(ns, 'a', { value: 1, writable: true, enumerable: true, configurable: false }) === ns);
var ds = [{ value: 2 }, { writable: false }, { enumerable: false }, { configurable: true }, { get: function () {} }];
for (var i = 0; i < ds.length; i++) {
try { Object.defineProperty(ns, 'a', ds[i]); out.push('defined'); } catch (e) { out.push(e.name); }
}
try { Object.defineProperty(ns, 'b', { value: 1 }); } catch (e) { out.push(e.name); }
try { Object.freeze(ns); } catch (e) { out.push(e.name); }
out.push(ns.a);",
&[("./m.mjs", m)],
);
assert_eq!(out, "true|true|false|true|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|1");
}
#[test]
fn a_namespace_reads_live_values() {
let m = "export var n = 1; export function bump() { n = n + 1; }";
let out = run("import * as ns from './m.mjs'; ns.bump(); out.push(ns.n);", &[("./m.mjs", m)]);
assert_eq!(out, "2");
}
#[test]
fn assigning_to_an_import_is_a_type_error() {
let m = "export var a = 1;";
let out = run("import { a } from './m.mjs'; try { a = 2; } catch (e) { out.push(e.name); } out.push(a);", &[("./m.mjs", m)]);
assert_eq!(out, "TypeError|1");
let out = run("import * as ns from './m.mjs'; try { ns = 2; } catch (e) { out.push(e.name); }", &[("./m.mjs", m)]);
assert_eq!(out, "TypeError");
}
#[test]
fn a_cycle_of_two_modules_runs_each_once_dependency_first() {
// main imports b, b imports main back: b runs first and sees main's hoisted function.
let b = "import { fa } from 'main'; out.push('b ' + fa()); export const b = 'B';";
let mut realm = es();
let mut load = loader(&[("./b.mjs", b), ("main", "")]);
let mut load = |referrer: &str, specifier: &str| {
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { load(referrer, specifier) }
};
let entry = "import { b } from './b.mjs'; export function fa() { return 'fa'; } out.push('a ' + b);";
let r = realm.run_module("main.mjs", entry, ModuleLimits::default(), &mut load);
assert_eq!(r, Ok(JsValue::Undefined));
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b fa|a B".into())));
}
#[test]
fn reading_an_import_before_its_module_ran_is_a_reference_error() {
let b = "import { a } from 'main'; out.push('b'); out.push(a);";
let mut realm = es();
let mut inner = loader(&[("./b.mjs", b)]);
let mut load = |referrer: &str, specifier: &str| {
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
};
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
match r {
Err(e) => assert!(e.message.starts_with("ReferenceError"), "{e:?}"),
other => panic!("{other:?}"),
}
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b".into())));
}
#[test]
fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() {
let b = "import * as ns from 'main';
var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'),
() => Object.getOwnPropertyDescriptor(ns, 'a'), () => Object.isSealed(ns), () => Object.isFrozen(ns),
() => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns),
() => Object.create(ns).a, () => Object.create(Object.create(ns)).a];
tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } });
// Listing the export names reads none of them.
var names = [];
for (var k in ns) names.push(k);
out.push(names.join(), 'a' in ns, 'a' in Object.create(ns), Object.getOwnPropertyNames(ns).join());";
let mut realm = es();
let mut inner = loader(&[("./b.mjs", b)]);
let mut load = |referrer: &str, specifier: &str| {
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
};
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
assert_eq!(r, Ok(JsValue::Undefined));
let errors = "ReferenceError|".repeat(13);
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a"))));
}
#[test]
fn a_module_two_modules_import_runs_once() {
let shared = "out.push('shared'); export var s = 1;";
let a = "import { s } from './shared.mjs'; out.push('a' + s);";
let b = "import { s } from './shared.mjs'; out.push('b' + s);";
let out = run("import './a.mjs'; import './b.mjs'; out.push('main');", &[("./shared.mjs", shared), ("./a.mjs", a), ("./b.mjs", b)]);
assert_eq!(out, "shared|a1|b1|main");
}
#[test]
fn re_exports_pass_names_on() {
let base = "export var x = 1, y = 2; export default 'base';";
let mid = "export { x as renamed } from './base.mjs'; export * from './base.mjs'; export * as all from './base.mjs';";
let out = run(
"import { renamed, x, y, all } from './mid.mjs'; import * as m from './mid.mjs'; out.push(renamed, x, y, all['default'], Object.keys(m).join(','));",
&[("./base.mjs", base), ("./mid.mjs", mid)],
);
// `export *` does not pass `default` on.
assert_eq!(out, "1|1|2|base|all,renamed,x,y");
}
#[test]
fn an_exported_import_is_a_re_export() {
let base = "export var v = 'v';";
let mid = "import { v } from './base.mjs'; import * as ns from './base.mjs'; export { v as w, ns };";
let out = run("import { w, ns } from './mid.mjs'; out.push(w, ns.v);", &[("./base.mjs", base), ("./mid.mjs", mid)]);
assert_eq!(out, "v|v");
}
#[test]
fn a_name_two_stars_give_is_ambiguous() {
let files =
[("./a.mjs", "export var n = 1;"), ("./b.mjs", "export var n = 2;"), ("./both.mjs", "export * from './a.mjs'; export * from './b.mjs';")];
fails("import { n } from './both.mjs'; out.push('ran');", &files, "SyntaxError: the export 'n'", "");
// The namespace leaves the name out.
let out = run("import * as ns from './both.mjs'; out.push(Object.keys(ns).length);", &files);
assert_eq!(out, "0");
}
#[test]
fn a_missing_export_ends_the_run_before_any_module_runs() {
let files = [("./m.mjs", "out.push('m'); export var a = 1;")];
let e = fails("import { nope } from './m.mjs';\nout.push('main');", &files, "SyntaxError: the module './m.mjs' has no export named 'nope'", "");
assert_eq!((e.line, e.column), (1, 10));
let files = [("./m.mjs", "export { nothing as gone } from './n.mjs';"), ("./n.mjs", "")];
fails("import './m.mjs';", &files, "SyntaxError: the module './n.mjs' has no export to give as 'gone'", "");
}
#[test]
fn a_module_the_loader_cannot_give_is_named_in_the_error() {
let e = fails("out.push(1);\nimport { a } from './missing.mjs';", &[], "Error: module not found: ./missing.mjs", "");
assert_eq!(e.line, 2);
fails("import x from 'lib';", &[], "SyntaxError: bare specifier: lib", "");
}
#[test]
fn a_syntax_error_in_an_imported_module_names_its_source() {
let mut realm = es();
let mut load = loader(&[("./a.mjs", "out.push('a');"), ("./bad.mjs", "\nvar = ;")]);
let r = realm.run_module("main.mjs", "import './a.mjs'; import './bad.mjs';", ModuleLimits::default(), &mut load);
let e = r.err().unwrap_or_else(|| panic!("ran"));
assert_eq!((e.kind, e.line), (RunErrorKind::Syntax, 2));
// The entry is source 0, then each module in the order it was loaded.
assert_eq!(realm.error_source(), 2);
assert_eq!(realm.run("out.length"), Ok(JsValue::Number(0.0)));
}
#[test]
fn module_code_is_strict_and_its_this_is_undefined() {
let out = run("out.push(this === undefined, (() => this)() === undefined); try { undeclared = 1; } catch (e) { out.push(e.name); }", &[]);
assert_eq!(out, "true|true|ReferenceError");
// Its declarations stay in the module.
let mut realm = es();
let (r, _) = run_with(&mut realm, "var hidden = 1; function also() {}", &[], ModuleLimits::default());
assert_eq!(r, Ok(JsValue::Undefined));
assert_eq!(realm.run("typeof hidden + typeof also"), Ok(JsValue::String("undefinedundefined".into())));
}
#[test]
fn an_exception_in_a_module_ends_the_run_and_the_modules_after_it_do_not_run() {
let files = [("./a.mjs", "out.push('a'); throw new TypeError('stop');"), ("./b.mjs", "try { out.push('b'); } catch (e) { out.push('caught'); }")];
fails("import './a.mjs'; import './b.mjs'; try { out.push('main'); } catch (e) {}", &files, "TypeError: stop", "a");
}
#[test]
fn the_module_count_and_import_depth_are_limited() {
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "out.push('c');")];
let mut realm = es();
let (r, out) = run_with(&mut realm, "import './a.mjs';", &files, ModuleLimits { modules: 3, depth: 16 });
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (3) reached at './c.mjs'")), "{r:?}");
assert_eq!(out, "");
let (r, _) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: import depth limit (2) reached at './c.mjs'")), "{r:?}");
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 4, depth: 3 });
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "c"));
}
#[test]
fn a_module_at_the_depth_limit_may_import_a_module_already_loaded() {
let files = [("./a.mjs", "import './b.mjs'; out.push('a');"), ("./b.mjs", "import './a.mjs'; out.push('b');")];
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "b|a"));
}
#[test]
fn a_module_limit_of_zero_runs_no_module() {
let (r, out) = run_with(&mut es(), "out.push('main');", &[], ModuleLimits { modules: 0, depth: 16 });
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (0) reached")), "{r:?}");
assert_eq!(out, "");
}
#[test]
fn a_module_run_is_held_to_the_fuel_limit() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 50, ..Limits::default() });
let mut load = loader(&[("./m.mjs", &"var a = 1;\n".repeat(20))]);
let r = realm.run_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load);
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)));
}
#[test]
fn a_module_run_advances_in_slices_and_runs_each_module_in_turn() {
let mut realm = es();
let mut load = loader(&[("./a.mjs", "for (var i = 0; i < 200; i++) {} out.push('a');")]);
let entry = "import './a.mjs'; for (var j = 0; j < 200; j++) {} out.push('main');";
assert_eq!(realm.start_module("main.mjs", entry, ModuleLimits::default(), &mut load), Ok(()));
let mut slices = 0;
loop {
match realm.advance(10) {
Ok(Progress::Paused) => slices += 1,
Ok(Progress::Done(v)) => {
assert_eq!(v, JsValue::Undefined);
break;
}
Err(e) => panic!("{e:?}"),
}
}
assert!(slices > 20, "{slices}");
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("a|main".into())));
}
#[test]
fn an_es5_realm_runs_no_module() {
let mut realm = Realm::new();
let mut load = loader(&[]);
let r = realm.run_module("main.mjs", "export var a = 1;", ModuleLimits::default(), &mut load);
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Syntax));
}
#[test]
fn a_script_does_not_read_import_or_export() {
for src in ["import a from './a.mjs';", "export var a = 1;", "import './a.mjs';"] {
assert!(parse(src, &Options { es2015: true, ..Options::default() }).is_err(), "{src}");
assert!(es().run(src).is_err_and(|e| e.kind == RunErrorKind::Syntax), "{src}");
}
}
#[test]
fn module_early_errors() {
for src in [
"export var a; export { a };",
"export { undeclared };",
"export default 1; export default 2;",
"import { a } from './x.mjs'; var a;",
"var a; import a from './x.mjs';",
"import { a, a } from './x.mjs';",
"function f() { import a from './x.mjs'; }",
"{ export var a; }",
"import { default } from './x.mjs';",
"export { default };",
"import a from x;",
"import * from './x.mjs';",
"with (a) {}",
"export default class {}",
"import('./x.mjs');",
"#include 'x.js'\n",
// Top-level functions are lexical declarations in a module.
"function f() {} function f() {}",
"var f; function f() {}",
"function f() {} var f;",
"let f; function f() {}",
] {
syntax(src);
}
for src in [
"import { default as d, if as i } from './x.mjs'; export { d as default, i as if };",
"import {} from './x.mjs'; export {};",
"export function f() {} export { f as g };",
"var as = 1, from = 2; export { as, from };",
"export * as default from './x.mjs';",
"function f() {} { function f() {} } function g() { var g; function h() {} var h; }",
] {
assert!(parse_module(src, &Options::default()).is_ok(), "{src}");
}
}
#[test]
fn a_module_lists_what_it_imports_and_exports() {
let (_, info) =
match parse_module("import a, { b as c } from './x.mjs'; export { c as d }; export * from './y.mjs'; import './x.mjs';", &Options::default())
{
Ok(p) => p,
Err(e) => panic!("{e:?}"),
};
let specifiers: Vec<&str> = info.requests.iter().map(|r| r.specifier.as_str()).collect();
assert_eq!(specifiers, ["./x.mjs", "./y.mjs"]);
assert_eq!(info.imports.len(), 2);
assert!(
matches!(&info.exports[..], [crate::ExportEntry::Star { request: 1, .. }, crate::ExportEntry::Indirect { export_name, request: 0, .. }] if export_name == "d")
);
}
#[test]
fn a_specifier_with_an_unpaired_surrogate_parses_and_no_module_has_it() {
let src = "import './\\uD800.mjs'; import './\\uFFFD.mjs'; import './\\uDC00.mjs'; import './\\uD800.mjs';";
let (_, info) = match parse_module(src, &Options::default()) {
Ok(p) => p,
Err(e) => panic!("{e:?}"),
};
let units: Vec<&[u16]> = info.requests.iter().map(|r| r.units.as_slice()).collect();
let dot = [u16::from(b'.'), u16::from(b'/')];
let ext: Vec<u16> = ".mjs".encode_utf16().collect();
let with = |u: u16| [&dot[..], &[u], &ext[..]].concat();
assert_eq!(units, [with(0xD800).as_slice(), with(0xFFFD).as_slice(), with(0xDC00).as_slice()]);
assert_eq!(info.requests[0].specifier, "./\u{FFFD}.mjs");
// The run stops when the module is to be loaded, before any module runs, and the loader is
// not asked for it.
let e = fails("out.push('ran'); import './\\uD800.mjs';", &[], "SyntaxError: module specifier './\u{FFFD}.mjs' is not valid text", "");
assert_eq!(e.line, 1);
}
#[test]
fn a_namespace_of_many_exports_lists_each_once_in_order() {
let names: Vec<String> = (0..3000).rev().map(|i| format!("e{i}")).collect();
let m: String = names.iter().map(|n| format!("export var {n} = '{n}';")).collect();
let star = "export * from './m.mjs'; export var e5 = 'own';";
let out = run(
"import * as ns from './star.mjs'; var k = Object.keys(ns); out.push(k.length, k[0], k[k.length - 1], ns.e5, ns.e2999);",
&[("./m.mjs", m.as_str()), ("./star.mjs", star)],
);
assert_eq!(out, "3000|e0|e999|own|e2999");
}
#[test]
fn modules_survive_a_collection_while_they_link() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() });
assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok());
let m = "export var v = 'kept'; export function f() { return v; }";
let mut load = loader(&[("./m.mjs", m)]);
// A collection runs at every heap reservation while the modules load and link, before any
// of their code runs.
let before = realm.interp().heap.collections;
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
let started = realm.start_module(
"main.mjs",
"import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());",
ModuleLimits::default(),
&mut load,
);
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
assert_eq!(started, Ok(()));
assert!(realm.interp().heap.collections > before);
assert!(matches!(realm.advance(1_000_000), Ok(Progress::Done(JsValue::Undefined))));
realm.collect_garbage();
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into())));
}
#[test]
fn the_heap_counts_each_module_from_when_it_loads() {
// Each module holds about 4 MB of code (its text and its string). The heap holds one of them,
// and not two, so the run stops while the second loads and never asks for the third.
let body = format!("export var v = '{}';", "x".repeat(1_000_000));
let limits = || Limits { heap_bytes: 7 << 20, ..Limits::default() };
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
assert!(realm.run("var out = [];").is_ok());
let one = run_with(&mut realm, "import { v } from './a.mjs'; out.push(v.length);", &[("./a.mjs", body.as_str())], ModuleLimits::default());
assert_eq!(one, (Ok(JsValue::Undefined), "1000000".to_string()));
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
let asked = std::cell::RefCell::new(Vec::new());
let mut inner = loader(&[("./a.mjs", body.as_str()), ("./b.mjs", body.as_str()), ("./c.mjs", "")]);
let mut load = |referrer: &str, specifier: &str| {
asked.borrow_mut().push(specifier.to_string());
inner(referrer, specifier)
};
let r = realm.run_module("main.mjs", "import './a.mjs'; import './b.mjs'; import './c.mjs';", ModuleLimits::default(), &mut load);
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. })), "{r:?}");
assert_eq!(*asked.borrow(), ["./a.mjs", "./b.mjs"]);
}
#[test]
fn a_module_keeps_no_expression_value_alive_after_its_statement() {
// The heap holds one of these arrays and not two, so each must be collectable once the
// expression statement that made it ends.
let big = "function big() { var a = []; for (var i = 0; i < 50000; i++) a[i] = { i: i }; return a; }";
let mut realm = es();
assert!(realm.run(&format!("{big} var held = big();")).is_ok());
let with_one = realm.collect_garbage();
assert!(realm.run("held = null;").is_ok());
let without = realm.collect_garbage();
let one = with_one - without;
realm.set_limits(Limits { heap_bytes: without + one * 3 / 2, ..Limits::default() });
let entry = format!("{big} big(); big(); try {{ big(); }} finally {{ big(); }} out.push('done');");
let (r, out) = run_with(&mut realm, &entry, &[], ModuleLimits::default());
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "done"));
// Script and eval code still complete with the value of their last expression statement.
assert_eq!(realm.run("1; 2;"), Ok(JsValue::Number(2.0)));
assert_eq!(realm.run("eval('3; 4;')"), Ok(JsValue::Number(4.0)));
assert_eq!(realm.run("try { 5; } finally { 6; }"), Ok(JsValue::Number(5.0)));
}
+11
View File
@@ -7,6 +7,7 @@
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
//! runs of them do not nest at all.
mod module;
mod pattern;
mod xml;
@@ -134,6 +135,9 @@ pub(crate) struct Parser<'s> {
scopes: Vec<Scope>,
/// What `super` and `new.target` may do in the function being read.
supers: SuperRules,
/// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical
/// declarations (ECMA-262 2015 section 15.2.1.11).
module: bool,
/// Where each shorthand property with an initializer (`{a = 1}`) not yet read as part of a
/// destructuring pattern starts; one left when its expression ends is a `SyntaxError`.
cover_inits: Vec<u32>,
@@ -175,6 +179,7 @@ impl<'s> Parser<'s> {
es2015: options.es2015,
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
supers: SuperRules::default(),
module: false,
cover_inits: Vec::new(),
cover_ok: false,
rest_commas: HashSet::new(),
@@ -332,6 +337,9 @@ impl<'s> Parser<'s> {
/// Checks a name used as an identifier: not a reserved word written with escapes, and not a
/// strict-mode reserved word in strict code.
fn check_identifier(&self, token: &Token, name: &str) -> Result<()> {
if self.module && name == "await" {
return Err(self.error_at_token(token, "'await' is a reserved word in modules"));
}
if token.escaped && Keyword::from_word(name).is_some() {
return Err(self.error_at_token(token, format!("keyword '{name}' must not contain escaped characters")));
}
@@ -431,6 +439,9 @@ impl<'s> Parser<'s> {
/// body or the script, lexical in a block.
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
if self.module && self.scopes.len() == 1 {
return self.declare_lexical(&name, true);
}
match self.scopes.last_mut() {
Some(scope) if scope.function => {
if scope.lexical.contains_key(&name.name) {
+481
View File
@@ -0,0 +1,481 @@
//! Module code (ECMA-262 2015 section 15.2): the import and export declarations at the top of a
//! module, read into a [`ModuleInfo`], and their early errors (section 15.2.1.1).
//!
//! A module is strict mode code throughout. An import binds its names as lexical declarations at
//! the top of the module, so a `var`, `let`, `const`, function or another import of the same name
//! is a redeclaration. An exported declaration is kept as the declaration; `export default` of an
//! expression or an anonymous function binds [`DEFAULT_BINDING`]. Each exported name may be
//! exported once, and a name an `export { … }` list exports from the module itself must be one it
//! declares or imports.
use std::collections::{HashMap, HashSet};
use super::{Parser, Result, describe};
use crate::ast::{
Binding, DEFAULT_BINDING, ExportEntry, FunctionKind, ImportEntry, ImportName, LexKind, ModuleInfo, ModuleRequest, Name, Program, Stmt, StmtId,
VarDecl,
};
use crate::token::{Keyword, Punct, Span, Token, TokenKind};
/// A name an `export { … }` list without `from` exports: the module's own binding (or import)
/// `local`, exported as `export_name`.
struct ClauseExport {
export_name: String,
local: String,
span: Span,
}
#[derive(Eq)]
struct RequestUnits(Vec<u16>);
impl std::hash::Hash for RequestUnits {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(&self.0, state);
}
}
impl PartialEq for RequestUnits {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
REQUEST_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
self.0 == other.0
}
}
#[derive(Eq)]
struct ImportLocal<'a>(&'a str);
impl std::hash::Hash for ImportLocal<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(self.0, state);
}
}
impl PartialEq for ImportLocal<'_> {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
EXPORT_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
self.0 == other.0
}
}
#[cfg(test)]
thread_local! {
static REQUEST_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static EXPORT_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Parser<'_> {
/// Reads the source as a module: its statements, without its import and export declarations
/// but with the declarations they export, and what it imports and exports.
pub(crate) fn parse_module(mut self) -> Result<(Program, ModuleInfo, Vec<Token>)> {
self.module = true;
#[cfg(test)]
REQUEST_SEARCH_STEPS.with(|steps| steps.set(0));
let mut info = ModuleInfo::default();
let mut requests = HashMap::new();
let mut clause = Vec::new();
let mut body = Vec::new();
while self.tok.kind != TokenKind::Eof {
if self.at_keyword(Keyword::Import) {
self.import_declaration(&mut info, &mut requests)?;
} else if self.at_keyword(Keyword::Export) {
if let Some(stmt) = self.export_declaration(&mut info, &mut clause, &mut requests)? {
body.push(stmt);
}
} else {
body.push(self.parse_statement_item()?);
}
}
self.finish_exports(&mut info, clause)?;
if let Some(tokens) = &mut self.tokens {
tokens.push(self.tok.clone());
}
let program =
Program { ast: self.ast, body, strict: true, directives: self.directives, lines: self.lines, es2015: self.es2015, supers: self.supers };
Ok((program, info, self.tokens.unwrap_or_default()))
}
/// The current token is the contextual keyword `word` (`as` or `from`), written without escapes.
fn at_contextual(&self, word: &str) -> bool {
self.tok.ident() == Some(word) && !self.tok.escaped
}
fn expect_contextual(&mut self, word: &str) -> Result<()> {
if self.at_contextual(word) {
self.bump()?;
return Ok(());
}
Err(self.error_at_token(&self.tok, format!("expected '{word}' but found {}", describe(&self.tok))))
}
/// A module specifier: a string literal, added to the module's requests once. → its index.
/// Any string value is a specifier here; the host decides which it can load.
fn module_specifier(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<usize> {
let TokenKind::String(units) = &self.tok.kind else {
return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok))));
};
if self.tok.legacy_octal {
return Err(self.error_at_token(&self.tok, "octal escape sequences are not allowed in strict mode"));
}
let units = RequestUnits(units.to_vec());
let span = self.bump()?.span;
if let Some(index) = requests.get(&units) {
return Ok(*index);
}
let specifier = String::from_utf16_lossy(&units.0);
let index = info.requests.len();
info.requests.push(ModuleRequest { specifier, units: units.0.clone(), span });
requests.insert(units, index);
Ok(info.requests.len() - 1)
}
/// A name as an import or export list gives it: any identifier name, keywords included. → the
/// name and whether it was an identifier (not a keyword).
fn list_name(&mut self) -> Result<(Name, bool)> {
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
return Err(self.error_at_token(&self.tok, format!("expected a name but found {}", describe(&self.tok))));
};
let ident = matches!(self.tok.kind, TokenKind::Ident(_));
let token = self.bump()?;
Ok((Name { name, span: token.span }, ident))
}
/// `import …;` (section 15.2.2). Each name it binds is declared in the module's scope.
fn import_declaration(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<()> {
let import = self.bump()?;
if self.at(Punct::LParen) {
return Err(self.error_at_token(&import, "import() is not supported"));
}
if matches!(self.tok.kind, TokenKind::String(_)) {
self.module_specifier(info, requests)?;
return self.semicolon();
}
let mut bound: Vec<(ImportName, Name)> = Vec::new();
let mut list = true;
if matches!(self.tok.kind, TokenKind::Ident(_)) {
let local = self.binding_identifier()?;
bound.push((ImportName::Name("default".into()), local));
list = self.eat(Punct::Comma)?;
}
if list {
if self.eat(Punct::Star)? {
self.expect_contextual("as")?;
let local = self.binding_identifier()?;
bound.push((ImportName::Namespace, local));
} else {
self.expect(Punct::LBrace)?;
while !self.at(Punct::RBrace) {
if matches!(self.tok.kind, TokenKind::Ident(_)) && !self.next_is_as() {
// A name without `as` binds itself, so it must be one a declaration may bind.
let local = self.binding_identifier()?;
bound.push((ImportName::Name(local.name.clone()), local));
} else {
let (imported, _) = self.list_name()?;
self.expect_contextual("as")?;
let local = self.binding_identifier()?;
bound.push((ImportName::Name(imported.name), local));
}
if !self.eat(Punct::Comma)? {
break;
}
}
self.expect(Punct::RBrace)?;
}
}
self.expect_contextual("from")?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
for (import, local) in bound {
self.declare_lexical(&local, false)?;
info.imports.push(ImportEntry { request, import, local });
}
Ok(())
}
/// The token after the current one is the contextual keyword `as`.
fn next_is_as(&self) -> bool {
self.peek().is_some_and(|t| !t.escaped && t.ident() == Some("as"))
}
/// `export …` (section 15.2.3). → the declaration it exports, which runs in place.
fn export_declaration(
&mut self,
info: &mut ModuleInfo,
clause: &mut Vec<ClauseExport>,
requests: &mut HashMap<RequestUnits, usize>,
) -> Result<Option<StmtId>> {
let export = self.bump()?;
let span = export.span;
if self.eat(Punct::Star)? {
if self.at_contextual("as") {
self.bump()?;
let (name, _) = self.list_name()?;
self.expect_contextual("from")?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
info.exports.push(ExportEntry::Indirect { export_name: name.name, request, import: ImportName::Namespace, span: name.span });
return Ok(None);
}
self.expect_contextual("from")?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
info.exports.push(ExportEntry::Star { request, span });
return Ok(None);
}
if self.at(Punct::LBrace) {
self.bump()?;
// Each name: the name it refers to (and whether that was an identifier) and the name it
// is exported as.
let mut names: Vec<(Name, bool, Name)> = Vec::new();
while !self.at(Punct::RBrace) {
let (local, ident) = self.list_name()?;
let exported = if self.at_contextual("as") {
self.bump()?;
self.list_name()?.0
} else {
local.clone()
};
names.push((local, ident, exported));
if !self.eat(Punct::Comma)? {
break;
}
}
self.expect(Punct::RBrace)?;
if self.at_contextual("from") {
self.bump()?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
for (local, _, exported) in names {
let import = ImportName::Name(local.name);
info.exports.push(ExportEntry::Indirect { export_name: exported.name, request, import, span: exported.span });
}
return Ok(None);
}
self.semicolon()?;
for (local, ident, exported) in names {
// Without `from`, each name refers to a binding of the module (section 15.2.3.1).
if !ident || crate::token::strict_reserved(&local.name) {
return Err(self.error_at_offset(local.span.start, format!("'{}' cannot be exported as a binding", local.name)));
}
clause.push(ClauseExport { export_name: exported.name, local: local.name, span: local.span });
}
return Ok(None);
}
if self.at_keyword(Keyword::Default) {
self.bump()?;
return self.export_default(info, span).map(Some);
}
let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some();
if !exportable {
return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok))));
}
let stmt = self.parse_statement_item()?;
let names: Vec<Name> = match self.ast.stmt(stmt) {
Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).collect(),
Some(Stmt::FunctionDecl(fid)) => self.ast.function(*fid).and_then(|f| f.name.clone()).into_iter().collect(),
_ => return Err(self.error_at_offset(span.start, "expected a declaration after 'export'")),
};
for name in names {
info.exports.push(ExportEntry::Local { export_name: name.name.clone(), local: name.name, span: name.span });
}
Ok(Some(stmt))
}
/// `export default …` after `default`: a function declaration (named or not) or an expression.
fn export_default(&mut self, info: &mut ModuleInfo, span: Span) -> Result<StmtId> {
if self.at_keyword(Keyword::Class) {
return Err(self.error_at_token(&self.tok, "classes are not supported"));
}
if self.at_keyword(Keyword::Function) {
self.enter()?;
let result = self.default_function();
self.leave();
let (stmt, fid, local) = result?;
self.declare_function(fid)?;
info.exports.push(ExportEntry::Local { export_name: "default".into(), local, span });
return Ok(stmt);
}
let start = self.tok.span;
let value = self.parse_assignment(false)?;
self.semicolon()?;
let target = Binding::Name(Name { name: DEFAULT_BINDING.into(), span: start });
let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { target, init: Some(value) }]), self.span_from(start));
info.exports.push(ExportEntry::Local { export_name: "default".into(), local: DEFAULT_BINDING.into(), span });
Ok(stmt)
}
/// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of
/// `name`, or of [`DEFAULT_BINDING`] for a function without one.
fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> {
let keyword = self.expect_keyword(Keyword::Function)?;
let start = keyword.span;
let generator = self.es2015 && self.eat(Punct::Star)?;
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) {
self.function_name()?
} else {
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
};
let local = name.0.name.clone();
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
Ok((stmt, fid, local))
}
/// 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 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<ClauseExport>) -> Result<()> {
#[cfg(test)]
EXPORT_SEARCH_STEPS.with(|steps| steps.set(0));
let mut imports = HashMap::with_capacity(info.imports.len());
for import in &info.imports {
imports.entry(ImportLocal(&import.local.name)).or_insert(import);
}
let top = self.scopes.first();
for c in clause {
let declared = top.is_some_and(|s| s.lexical.contains_key(&c.local) || s.vars.contains(&c.local));
if !declared {
return Err(self.error_at_offset(c.span.start, format!("'{}' is exported but not declared in the module", c.local)));
}
let imported = imports.get(&ImportLocal(&c.local));
let entry = match imported {
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);
}
let mut seen = HashSet::new();
for e in &info.exports {
let (name, span) = match e {
ExportEntry::Local { export_name, span, .. } | ExportEntry::Indirect { export_name, span, .. } => (export_name, span),
ExportEntry::Star { .. } => continue,
};
if !seen.insert(name.as_str()) {
return Err(self.error_at_offset(span.start, format!("'{name}' is exported more than once")));
}
}
Ok(())
}
}
#[cfg(test)]
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::JsValue, crate::RunError>, 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
[r"import './\141.mjs';", r"import value from './\141.mjs';", r"export * from './\141.mjs';", r"export { value } from './\141.mjs';"]
{
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
}
for source in [r"import './\u0061.mjs';", r"export * from './\x61.mjs';", r"import './\uD800.mjs';"] {
assert!(parse_module(source, &Options::default()).is_ok(), "{source}");
}
}
#[test]
fn module_request_search_work_is_bounded_by_request_count() {
let count = 1_000;
let mut source = String::new();
for index in 0..count {
source.push_str(&format!("import './{index}.mjs';"));
}
source.push_str(r"import './\u0030.mjs'; import './\uD800.mjs'; import './\uFFFD.mjs'; import './\uDC00.mjs'; import './\uD800.mjs';");
let (_, info) = match parse_module(&source, &Options::default()) {
Ok(parsed) => parsed,
Err(error) => panic!("{error:?}"),
};
assert_eq!(info.requests.len(), count + 3);
for (index, request) in info.requests.iter().take(count).enumerate() {
assert_eq!(request.specifier, format!("./{index}.mjs"));
}
assert_eq!(info.requests[count].units[2], 0xD800);
assert_eq!(info.requests[count + 1].units[2], 0xFFFD);
assert_eq!(info.requests[count + 2].units[2], 0xDC00);
let steps = REQUEST_SEARCH_STEPS.with(std::cell::Cell::get);
assert!(steps > 0, "the repeated requests compare their exact UTF-16 keys");
assert!(steps <= 2 * (count + 5), "{steps} request-search steps for {} requests", count + 5);
}
#[test]
fn imported_export_resolution_work_is_bounded_by_binding_count() {
let count = 1_000;
let bindings = (0..count).map(|index| format!("value as local{index}")).collect::<Vec<_>>().join(",");
let exports = (0..count).map(|index| format!("local{index} as exported{index}")).collect::<Vec<_>>().join(",");
let source = format!(
"import {{{bindings}}} from './values.mjs'; import * as ns from './namespace.mjs'; export {{{exports},ns as namespace,local0 as again}};"
);
let (_, info) = match parse_module(&source, &Options::default()) {
Ok(parsed) => parsed,
Err(error) => panic!("{error:?}"),
};
assert_eq!(info.imports.len(), count + 1);
assert_eq!(info.exports.len(), count + 2);
for (index, export) in info.exports.iter().take(count).enumerate() {
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::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")
);
let steps = EXPORT_SEARCH_STEPS.with(std::cell::Cell::get);
assert!(steps > 0);
assert!(steps <= 3 * (count + 2), "{steps} import-local comparisons for {} exports", count + 2);
for source in [
"import {value as x} from './values.mjs'; export {x,x};",
"import {value as x} from './values.mjs'; import * as x from './namespace.mjs';",
] {
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
}
}
}
+89 -24
View File
@@ -7,9 +7,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
use crate::bytecode::CodeKind;
use crate::heap::{Func, HIDDEN, Object, Prop, key};
use crate::interp::{Abrupt, CompileError, Interp};
use crate::module::{LinkFail, ModuleLimits, ModuleLoader};
use crate::value::Value;
use crate::{Options, SyntaxError};
fn internal_error(message: &str) -> RunError {
RunError { kind: RunErrorKind::Internal, message: message.to_string(), line: 0, column: 0, authored: false }
}
/// The limits a run is held to. Reaching one ends the run with [`RunErrorKind::Limit`]; scripts
/// cannot catch it, and their `finally` blocks do not run.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -287,6 +292,78 @@ impl Realm {
/// Compiles `source` and readies the realm for a run.
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
self.end();
self.reset_run()?;
let interp = &mut self.interp;
let strict = interp.options.strict;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
interp.source_tag = self.script_tag;
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
interp.source_tag = UNKNOWN_SOURCE;
match code {
Ok(code) => Ok(code),
Err(CompileError::Syntax(e)) => {
interp.error_tag = self.script_tag;
Err(e.into())
}
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
}
}
/// Begins a run of the module `key` with `source` (ECMA-262 2015 section 15.2), which
/// [`Realm::advance`] carries on as it does a script [`Realm::start`] began. `load` gives each
/// module a module imports ([`ModuleLoader`]). Every module is loaded, parsed and linked before
/// any runs, so a syntax error, an import of a missing or ambiguous export, a module `load`
/// cannot give or a module past `limits` ends the run here, with no code run. The first module
/// has [`Realm::script_tag`] as its source's tag, and each module loaded after it the next tag,
/// in the order `load` first gave their sources, as the sources an evaluator gives during a run
/// take theirs. A realm without [`Options::es2015`] runs no module: that is a syntax error.
/// A paused or waiting run ends before loading; its globals remain available.
pub fn start_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<(), RunError> {
self.end();
self.reset_run()?;
if !self.interp.options.es2015 {
let message = "modules need ECMAScript 2015; this script runs ECMAScript 5".to_string();
return Err(RunError { kind: RunErrorKind::Syntax, message, line: 0, column: 0, authored: false });
}
let interp = &mut self.interp;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
let marks = (interp.temp_envs_mark(), interp.temp_roots_mark(), interp.temp_codes_mark());
let linked = crate::module::link(interp, key, source, self.script_tag, limits, load);
let pushed = match linked {
Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run),
Err(fail) => Err(fail),
};
let interp = &mut self.interp;
interp.drop_temp_envs(marks.0);
interp.drop_temp_roots(marks.1);
interp.drop_temp_codes(marks.2);
match pushed {
Ok(()) => Ok(()),
Err(LinkFail::Syntax { tag, error }) => {
self.interp.error_tag = tag;
Err(error.into())
}
Err(LinkFail::At { tag, line, column, abrupt }) => {
let e = self.outcome(Err(abrupt)).err();
self.interp.error_tag = tag;
Err(e.map_or_else(|| internal_error("a module failed without an error"), |e| RunError { line, column, ..e }))
}
Err(LinkFail::Run(abrupt)) => self.outcome(Err(abrupt)).map(drop),
}
}
/// Runs the module `key` with `source` to its end ([`Realm::start_module`]), drains its queued
/// Promise jobs, and returns `undefined`.
pub fn run_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<JsValue, RunError> {
self.start_module(key, source, limits, load)?;
let result = self.interp.execute().and_then(|value| self.interp.drain_jobs(value));
self.outcome(result)
}
/// Readies the realm for a run: its state from the last run cleared and its fuel filled.
fn reset_run(&mut self) -> Result<(), RunError> {
self.script_tag = UNKNOWN_SOURCE;
self.rejections = (Vec::new(), 0);
let interp = &mut self.interp;
@@ -328,21 +405,7 @@ impl Realm {
}),
};
}
let interp = &mut self.interp;
let strict = interp.options.strict;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
interp.source_tag = self.script_tag;
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
interp.source_tag = UNKNOWN_SOURCE;
match code {
Ok(code) => Ok(code),
Err(CompileError::Syntax(e)) => {
interp.error_tag = self.script_tag;
Err(e.into())
}
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
}
Ok(())
}
/// The end of a run: its completion value or error, with the interpreter's stacks emptied.
@@ -358,7 +421,7 @@ impl Realm {
// A generator whose body was running when the run ended cannot go on.
let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect();
running.into_iter().for_each(|g| interp.end_generator(Some(g)));
interp.frames.clear();
interp.clear_frames();
interp.temp_roots.clear();
interp.join_stack.clear();
interp.waiting = false;
@@ -549,16 +612,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.
@@ -566,9 +630,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
}
+21 -2
View File
@@ -408,8 +408,27 @@ impl Interp {
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
None => {}
}
let proto = self.object(id)?.proto;
match proto.map(|p| self.find_sym(p, &k)).transpose()?.flatten() {
let mut cur = self.object(id)?.proto;
let mut inherited = None;
let mut steps = 0usize;
while let Some(object) = cur {
if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) {
return self.reject_sym(throw, &k, "a module namespace object is read-only");
}
if let Some(property) = self.get_own_sym(object, &k)? {
inherited = Some(property);
break;
}
cur = self.object(object)?.proto;
if cur.is_some() {
self.use_fuel()?;
}
steps += 1;
if steps > 1_000_000 {
return Err(crate::interp::Abrupt::Internal("prototype chain too long".into()));
}
}
match inherited {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"),
+199 -2
View File
@@ -31,7 +31,10 @@
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
//! arrow functions, templates, default and rest parameters, classes, `super` and `new.target`,
//! and from ECMAScript 2020 optional chains and `??`) without and with that option, and
//! prints both counts; its failures with the option go to `es2015-failures.txt`.
//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs
//! the module tests under `test/language/module-code`, `import` and `export` as modules, reading
//! the fixture files they import from the suite, and as scripts for comparison; its failures as
//! modules go to `module-failures.txt`.
//!
//! A sixth test runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names (`Map`, `Set`,
//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in
@@ -73,7 +76,11 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize};
use vectorcraft_js::{
JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize,
tokenize_module,
};
/// A test file's metadata, from its `/*--- … ---*/` block.
#[derive(Default)]
struct Meta {
@@ -453,6 +460,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options:
Err(_) => return true,
}
}
uses_missing_builtin(&lists, missing)
}
/// The tokens `lists` (of a test and the harness files it includes) use a missing built-in, as
/// [`needs_missing_builtin`] counts them.
fn uses_missing_builtin(lists: &[Vec<Token>], missing: &HashSet<&str>) -> bool {
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
lists.iter().flatten().any(|t| match &t.kind {
TokenKind::Ident(name) => missing.contains(name.as_str()),
@@ -967,6 +980,190 @@ fn run_es2015(dir: &Path) {
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display());
}
/// The folders under `test/language/` whose module tests [`modules_run`] reads.
const MODULE_FOLDERS: &[&str] = &["module-code", "import", "export"];
/// The feature tags a module test may carry: those of [`ES2015_FEATURES`] and `export * as ns from`.
const MODULE_FEATURES: &[&str] =
&["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters", "export-star-as-namespace-from-module"];
#[test]
fn modules_run() {
let Some(dir) = suite_dir() else {
println!("test262 modules: SKIPPED (no suite; run cargo xtask test262)");
return;
};
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_modules(&dir)).unwrap();
handle.join().unwrap();
}
/// The `/`-separated path, from the suite's folder, of the module `specifier` names for the module
/// at `referrer` (a path from the suite's folder too): only a `./` or `../` path that stays inside
/// `test/`.
fn module_path(referrer: &str, specifier: &str) -> Result<String, LoadError> {
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
return Err(LoadError::Syntax(format!("the runner reads only relative specifiers: '{specifier}'")));
}
let mut names: Vec<&str> = referrer.split('/').collect();
names.pop();
for name in specifier.split('/') {
match name {
"" | "." => {}
".." if names.len() > 1 => {
names.pop();
}
".." => return Err(LoadError::Other(format!("'{specifier}' leads out of the suite's tests"))),
name => names.push(name),
}
}
Ok(names.join("/"))
}
/// Runs a module test's `source` (at `rel`, a path from the suite's folder) in a new realm with
/// `options`, after `prelude` (the harness) as a script; the modules it imports are read from the
/// suite. `Err` describes a failure. `negative` is the phase (`resolution` or `runtime`) and the
/// error the test expects. A `resolution` test's module must parse, and the run must end with the
/// error while the modules load and link, before any runs; an imported module that does not parse
/// counts for a `SyntaxError`. A `runtime` test's modules must load and link, and the error must be thrown
/// while they run.
fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative: Option<(&str, &str)>, options: &Options) -> Result<(), String> {
let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
realm.run(prelude).map_err(|e| format!("the harness failed: {}", e.message))?;
let mut given = HashSet::new();
let mut load = |referrer: &str, specifier: &str| {
let key = module_path(referrer, specifier)?;
let path = inside(dir, &key).map_err(LoadError::Other)?;
let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None };
Ok(LoadedModule { key, source })
};
let resolution = negative.is_some_and(|(phase, _)| phase == "resolution");
if resolution && let Err(e) = vectorcraft_js::parse_module(source, options) {
return Err(format!("did not parse; a resolution error was expected: {} (line {})", e.message, e.line));
}
let started = realm.start_module(rel, source, ModuleLimits::default(), &mut load);
let result = match started {
Ok(()) if resolution => return Err("linked; an error while linking was expected".to_string()),
Err(e) if !resolution && negative.is_some() => {
return Err(format!("did not start; an error while running was expected: {:?}: {} (line {})", e.kind, e.message, e.line));
}
Err(e) => Err(e),
Ok(()) => loop {
match realm.advance(u64::MAX) {
Ok(Progress::Paused) => {}
Ok(Progress::Done(v)) => break Ok(v),
Err(e) => break Err(e),
}
},
};
match (result, negative.map(|(_, t)| t)) {
(Ok(_), None) => Ok(()),
(Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")),
(Err(e), Some("SyntaxError")) if resolution && e.kind == RunErrorKind::Syntax => Ok(()),
(Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => {
realm.bind_last_thrown("__thrown");
match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) {
Ok(JsValue::Bool(true)) => Ok(()),
_ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)),
}
}
(Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)),
}
}
/// Runs the module tests (`flags: [module]`) under [`MODULE_FOLDERS`] whose feature tags are all in
/// [`MODULE_FEATURES`], leaving out asynchronous tests and those that use a missing built-in: each
/// once as a strict script with [`Options::es2015`], as they could run before modules, and once as
/// a module, and prints both counts. A `negative: phase: parse` test must not parse as a module,
/// and a `phase: resolution` one must end before it runs with the error its `type:` names.
/// Failures as a module go to `module-failures.txt`.
fn run_modules(dir: &Path) {
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
let missing = missing_builtins(&[TEXT_BUILTINS]);
let options = Options { es2015: true, ..Options::default() };
let (mut selected, mut skipped) = (0usize, 0usize);
let (mut before, mut after) = ((0usize, 0usize), (0usize, 0usize));
let mut failures = String::new();
let mut panics = 0usize;
for folder in MODULE_FOLDERS {
let root = or_fail(inside(dir, &format!("test/language/{folder}")));
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
for path in or_fail(test_files(&root)) {
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
let source = or_fail(read_source(&path));
let meta = meta(&source);
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
if !has("module") || !meta.features.iter().all(|f| MODULE_FEATURES.contains(&f.as_str())) {
continue;
}
let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
let phase = meta.negative_phase.as_deref();
// A module that must not parse has no tokens to look at, and one that does not parse
// runs, to fail.
let missing_builtin = phase != Some("parse")
&& match (tokenize_module(&source, &options), tokenize(&includes, &options)) {
(Ok(test), Ok(harness)) => uses_missing_builtin(&[test, harness], &missing),
(Err(_), Ok(_)) => false,
(_, Err(_)) => true,
};
if has("async") || missing_builtin {
skipped += 1;
continue;
}
selected += 1;
let negative_type = meta.negative_type.clone().filter(|_| matches!(phase, Some("runtime" | "resolution")));
let negative = phase.zip(negative_type.as_deref());
let as_script = if matches!(phase, Some("parse" | "resolution")) {
parse(&source, &Options { strict: true, ..options.clone() }).is_err()
} else {
run_one(&format!("\"use strict\";\n{prelude}{includes}{source}"), negative_type.as_deref(), &options).is_ok()
};
if as_script {
before.0 += 1;
} else {
before.1 += 1;
}
let outcome = if phase == Some("parse") {
match vectorcraft_js::parse_module(&source, &options) {
Err(_) => Ok(()),
Ok(_) => Err("parsed; a SyntaxError was expected".to_string()),
}
} else {
let prelude = format!("{prelude}{includes}");
match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative, &options)) {
Ok(r) => r,
Err(_) => {
panics += 1;
Err("PANIC".to_string())
}
}
};
match outcome {
Ok(()) => after.0 += 1,
Err(why) => {
after.1 += 1;
failures.push_str(&format!("{rel}: {why}\n"));
}
}
}
}
assert!(selected > 0, "no module tests under {}", dir.display());
let report = dir.join("module-failures.txt");
if let Err(e) = std::fs::write(&report, &failures) {
println!("could not write {}: {e}", report.display());
}
println!(
"test262 modules: {selected} tests. As scripts: {} passed, {} failed. As modules: {} passed, {} failed. Skipped {skipped} \
asynchronous or missing-built-in tests. Failures: {}",
before.0,
before.1,
after.0,
after.1,
report.display()
);
assert_eq!(panics, 0, "the interpreter panicked; see {}", report.display());
}
#[test]
fn annex_b_runs() {
let Some(dir) = suite_dir() else {
+2 -2
View File
@@ -2070,13 +2070,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.runScript",
"Other Script…",
"Cmd+F12",
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
"{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
"ui.runInstalledScript",
"Run Script",
"",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
"ui.checkScript",
+4 -3
View File
@@ -4,7 +4,7 @@
//! A script's ScriptUI dialog is in [`script_window`]; these questions and dialogs open over it.
//!
//! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it
//! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show
//! asks for a `.js`, `.mjs` or `.jsx` file through the app's file asks. With Preferences › General › Show
//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts
//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a
//! prompt: its `choice` field (`proceed` runs, `cancel` does not), `skip` (true: turn the warning
@@ -551,7 +551,8 @@ pub(crate) fn picked_script(app: &mut VectorcraftApp, picked: Picked) -> Result<
return Err(TOO_LARGE.to_string());
}
let source = String::from_utf8(bytes).map_err(|_| "the script is not UTF-8 text".to_string())?;
return chosen(app, json!({"source": source, "name": name}));
let module = Path::new(&name).extension().is_some_and(|e| e.eq_ignore_ascii_case("mjs"));
return chosen(app, json!({"source": source, "name": name, "module": module}));
}
match picked.paths().into_iter().next() {
Some(path) => chosen(app, json!({ "path": path.to_string_lossy() })),
@@ -563,7 +564,7 @@ pub(crate) fn picked_script(app: &mut VectorcraftApp, picked: Picked) -> Result<
pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result<Value, String> {
let path = params.get("path").and_then(Value::as_str);
if path.is_some_and(|path| !runs(path)) {
return Err("Choose a .js or .jsx script".into());
return Err("Choose a .js, .mjs or .jsx script".into());
}
if !app.session.prefs.show_external_script_warning {
return crate::script_runs::run_chosen(app, params);
+2 -2
View File
@@ -6466,7 +6466,7 @@ digits Malayalam Malaiàlam
Do not show this warning again No tornis a mostrar aquest avís
Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir.
This script has added a great many objects. Continue, or stop it and undo what it did? Aquest script ha afegit moltíssims objectes. Voleu continuar, o aturar-lo i desfer el que ha fet?
@msg Choose a .js or .jsx script Trieu un script .js o .jsx
@msg Choose a .js, .mjs or .jsx script Trieu un script .js, .mjs o .jsx
@msg Ran {name} S'ha executat {name}
@msg The script was stopped and its changes were undone L'script s'ha aturat i s'han desfet els seus canvis
@msg a script is running: stop it or wait for it to finish s'està executant un script: atureu-lo o espereu que acabi
@@ -6638,7 +6638,7 @@ liquify-list-end {0}, {1} {0} i {1}
@msg `args` is larger than 1 MiB `args` ocupa més d'1 MiB
@msg `path` is empty `path` és buit
@msg `installed` takes a `path`, not a `source` `installed` admet un `path`, no un `source`
@msg `path` must name a .js or .jsx file `path` ha d’indicar un fitxer .js o .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` ha d’indicar un fitxer .js, .mjs o .jsx
@msg give exactly one of `path` and `source` indiqueu exactament un de `path` i `source`
@msg Running a script S'està executant un script
@msg Copied the script report S’ha copiat l’informe de l’script
Can't render this file because it is too large.
+2 -2
View File
@@ -5273,7 +5273,7 @@ imageTrace Outline Obrys
Do not show this warning again Toto upozornění již nezobrazovat
Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu.
This script has added a great many objects. Continue, or stop it and undo what it did? Tento skript přidal velmi mnoho objektů. Pokračovat, nebo jej zastavit a vrátit jeho změny?
@msg Choose a .js or .jsx script Vyberte skript .js nebo .jsx
@msg Choose a .js, .mjs or .jsx script Vyberte skript .js, .mjs nebo .jsx
@msg Ran {name} Spuštěno: {name}
@msg The script was stopped and its changes were undone Skript byl zastaven a jeho změny byly vráceny
@msg a script is running: stop it or wait for it to finish běží skript: zastavte jej nebo počkejte na jeho dokončení
@@ -5420,7 +5420,7 @@ liquify-list-end {0}, {1} {0} a {1}
@msg `args` is larger than 1 MiB `args` je větší než 1 MiB
@msg `path` is empty `path` je prázdný
@msg `installed` takes a `path`, not a `source` `installed` přijímá `path`, ne `source`
@msg `path` must name a .js or .jsx file `path` musí označovat soubor .js nebo .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` musí označovat soubor .js, .mjs nebo .jsx
@msg give exactly one of `path` and `source` zadejte právě jedno z `path` a `source`
@msg Running a script Běží skript
@msg Copied the script report Zpráva o skriptu zkopírována
Can't render this file because it is too large.
+2 -2
View File
@@ -54,7 +54,7 @@
@msg it decompresses to more than {_1} MB den udpakkes til mere end {_1} MB
@msg its editing data is for a different page dens redigeringsdata er til en anden side
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` skal være "emBox", "capHeight", "xHeight" eller "icfBox"
@msg Choose a .js or .jsx script Vælg et .js- eller .jsx-script
@msg Choose a .js, .mjs or .jsx script Vælg et .js-, .mjs- eller .jsx-script
@msg Ran {name} Kørte {name}
@msg The script was stopped and its changes were undone Scriptet blev stoppet, og dets ændringer blev fortrudt
@msg a script is running: stop it or wait for it to finish et script kører: stop det, eller vent, til det er færdigt
@@ -245,7 +245,7 @@ liquify-list-end {0}, {1} {0} og {1}
@msg `args` is larger than 1 MiB `args` er større end 1 MiB
@msg `path` is empty `path` er tom
@msg `installed` takes a `path`, not a `source` `installed` tager en `path`, ikke en `source`
@msg `path` must name a .js or .jsx file `path` skal angive en .js- eller .jsx-fil
@msg `path` must name a .js, .mjs or .jsx file `path` skal angive en .js-, .mjs- eller .jsx-fil
@msg give exactly one of `path` and `source` angiv præcis én af `path` og `source`
@msg Running a script Kører et script
@msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e}
Can't render this file because it is too large.
+2 -2
View File
@@ -4859,7 +4859,7 @@ theme Appearance Erscheinungsbild
Do not show this warning again Diese Warnung nicht mehr anzeigen
Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut.
This script has added a great many objects. Continue, or stop it and undo what it did? Dieses Skript hat sehr viele Objekte hinzugefügt. Fortfahren oder das Skript stoppen und seine Änderungen rückgängig machen?
@msg Choose a .js or .jsx script Wählen Sie ein .js- oder .jsx-Skript
@msg Choose a .js, .mjs or .jsx script Wählen Sie ein .js-, .mjs- oder .jsx-Skript
@msg Ran {name} {name} ausgeführt
@msg The script was stopped and its changes were undone Das Skript wurde gestoppt und seine Änderungen wurden rückgängig gemacht
@msg a script is running: stop it or wait for it to finish ein Skript wird ausgeführt: stoppen Sie es oder warten Sie, bis es fertig ist
@@ -8592,7 +8592,7 @@ breakText Glyphs Glyphen
@msg `args` is larger than 1 MiB `args` ist größer als 1 MiB
@msg `path` is empty `path` ist leer
@msg `installed` takes a `path`, not a `source` `installed` nimmt einen `path`, keine `source`
@msg `path` must name a .js or .jsx file `path` muss eine .js- oder .jsx-Datei angeben
@msg `path` must name a .js, .mjs or .jsx file `path` muss eine .js-, .mjs- oder .jsx-Datei angeben
@msg give exactly one of `path` and `source` geben Sie genau eines von `path` und `source` an
@msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein
@msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein
Can't render this file because it is too large.
+2 -2
View File
@@ -2656,7 +2656,7 @@ axis Both Και τα δύο
Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση
Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο.
This script has added a great many objects. Continue, or stop it and undo what it did? Αυτό το σενάριο πρόσθεσε πάρα πολλά αντικείμενα. Συνέχεια, ή διακοπή και αναίρεση όσων έκανε;
@msg Choose a .js or .jsx script Επιλέξτε ένα σενάριο .js ή .jsx
@msg Choose a .js, .mjs or .jsx script Επιλέξτε ένα σενάριο .js, .mjs ή .jsx
@msg Ran {name} Εκτελέστηκε: {name}
@msg The script was stopped and its changes were undone Το σενάριο διακόπηκε και οι αλλαγές του αναιρέθηκαν
@msg a script is running: stop it or wait for it to finish εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει
@@ -2829,7 +2829,7 @@ liquify-list-end {0}, {1} {0} και {1}
@msg `args` is larger than 1 MiB το `args` είναι μεγαλύτερο από 1 MiB
@msg `path` is empty το `path` είναι κενό
@msg `installed` takes a `path`, not a `source` το `installed` δέχεται `path`, όχι `source`
@msg `path` must name a .js or .jsx file το `path` πρέπει να ορίζει αρχείο .js ή .jsx
@msg `path` must name a .js, .mjs or .jsx file το `path` πρέπει να ορίζει αρχείο .js, .mjs ή .jsx
@msg give exactly one of `path` and `source` δώστε ακριβώς ένα από τα `path` και `source`
@msg Running a script Εκτελείται σενάριο
@msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε
Can't render this file because it is too large.
+2 -2
View File
@@ -4935,7 +4935,7 @@ axis Both Ambos
Do not show this warning again No volver a mostrar esta advertencia
Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir.
This script has added a great many objects. Continue, or stop it and undo what it did? Este script ha añadido muchísimos objetos. ¿Continuar, o detenerlo y deshacer lo que hizo?
@msg Choose a .js or .jsx script Elija un script .js o .jsx
@msg Choose a .js, .mjs or .jsx script Elija un script .js, .mjs o .jsx
@msg Ran {name} Se ejecutó {name}
@msg The script was stopped and its changes were undone El script se detuvo y sus cambios se deshicieron
@msg a script is running: stop it or wait for it to finish se está ejecutando un script: deténgalo o espere a que termine
@@ -5107,7 +5107,7 @@ liquify-list-end {0}, {1} {0}, {1}
@msg `args` is larger than 1 MiB `args` ocupa más de 1 MiB
@msg `path` is empty `path` está vacío
@msg `installed` takes a `path`, not a `source` `installed` admite un `path`, no un `source`
@msg `path` must name a .js or .jsx file `path` debe indicar un archivo .js o .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` debe indicar un archivo .js, .mjs o .jsx
@msg give exactly one of `path` and `source` indique exactamente uno de `path` y `source`
@msg Running a script Ejecutando un script
@msg Copied the script report Se copió el informe del script
Can't render this file because it is too large.
+2 -2
View File
@@ -5178,7 +5178,7 @@ imageTrace Outline Ääriviiva
Do not show this warning again Älä näytä tätä varoitusta uudelleen
Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen.
This script has added a great many objects. Continue, or stop it and undo what it did? Tämä komentosarja on lisännyt hyvin paljon objekteja. Jatketaanko, vai pysäytetäänkö se ja kumotaan sen muutokset?
@msg Choose a .js or .jsx script Valitse .js- tai .jsx-komentosarja
@msg Choose a .js, .mjs or .jsx script Valitse .js-, .mjs- tai .jsx-komentosarja
@msg Ran {name} Suoritettu: {name}
@msg The script was stopped and its changes were undone Komentosarja pysäytettiin ja sen muutokset kumottiin
@msg a script is running: stop it or wait for it to finish komentosarja on käynnissä: pysäytä se tai odota sen valmistumista
@@ -5350,7 +5350,7 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg `args` is larger than 1 MiB `args` on suurempi kuin 1 MiB
@msg `path` is empty `path` on tyhjä
@msg `installed` takes a `path`, not a `source` `installed` ottaa `path`-arvon, ei `source`-arvoa
@msg `path` must name a .js or .jsx file `path` on oltava .js- tai .jsx-tiedosto
@msg `path` must name a .js, .mjs or .jsx file `path` on oltava .js-, .mjs- tai .jsx-tiedosto
@msg give exactly one of `path` and `source` anna tasan yksi arvoista `path` ja `source`
@msg Running a script Suoritetaan komentosarjaa
@msg Copied the script report Komentosarjan raportti kopioitiin
Can't render this file because it is too large.
+2 -2
View File
@@ -4917,7 +4917,7 @@ axis Both Les deux
Do not show this warning again Ne plus afficher cet avertissement
Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau.
This script has added a great many objects. Continue, or stop it and undo what it did? Ce script a ajouté un très grand nombre d’objets. Continuer, ou l’arrêter et annuler ce qu’il a fait ?
@msg Choose a .js or .jsx script Choisissez un script .js ou .jsx
@msg Choose a .js, .mjs or .jsx script Choisissez un script .js, .mjs ou .jsx
@msg Ran {name} {name} exécuté
@msg The script was stopped and its changes were undone Le script a été arrêté et ses modifications ont été annulées
@msg a script is running: stop it or wait for it to finish un script est en cours d’exécution : arrêtez-le ou attendez qu’il se termine
@@ -5063,7 +5063,7 @@ liquify-list-end {0}, {1} {0} et {1}
@msg `args` is larger than 1 MiB `args` dépasse 1 Mio
@msg `path` is empty `path` est vide
@msg `installed` takes a `path`, not a `source` `installed` prend un `path`, pas un `source`
@msg `path` must name a .js or .jsx file `path` doit désigner un fichier .js ou .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` doit désigner un fichier .js, .mjs ou .jsx
@msg give exactly one of `path` and `source` indiquez exactement un paramètre parmi `path` et `source`
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue
@msg Running a script Exécution d’un script
Can't render this file because it is too large.
+2 -2
View File
@@ -7674,7 +7674,7 @@ arrowhead Feather पंख
Do not show this warning again यह चेतावनी फिर न दिखाएँ
Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें।
This script has added a great many objects. Continue, or stop it and undo what it did? इस स्क्रिप्ट ने बहुत सारे ऑब्जेक्ट जोड़े हैं। जारी रखें, या इसे रोककर इसके बदलाव पूर्ववत करें?
@msg Choose a .js or .jsx script .js या .jsx स्क्रिप्ट चुनें
@msg Choose a .js, .mjs or .jsx script .js, .mjs या .jsx स्क्रिप्ट चुनें
@msg Ran {name} {name} चलाई गई
@msg The script was stopped and its changes were undone स्क्रिप्ट रोकी गई और उसके बदलाव पूर्ववत किए गए
@msg a script is running: stop it or wait for it to finish एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें
@@ -7847,7 +7847,7 @@ liquify-list-end {0}, {1} {0} और {1}
@msg `args` is larger than 1 MiB `args` 1 MiB से बड़ा है
@msg `path` is empty `path` खाली है
@msg `installed` takes a `path`, not a `source` `installed` एक `path` लेता है, `source` नहीं
@msg `path` must name a .js or .jsx file `path` में किसी .js या .jsx फ़ाइल का नाम होना चाहिए
@msg `path` must name a .js, .mjs or .jsx file `path` में किसी .js, .mjs या .jsx फ़ाइल का नाम होना चाहिए
@msg give exactly one of `path` and `source` `path` और `source` में से ठीक एक दें
@msg Running a script स्क्रिप्ट चल रही है
@msg Copied the script report Copied स्क्रिप्ट रिपोर्ट
Can't render this file because it is too large.
+2 -2
View File
@@ -5794,7 +5794,7 @@ imageTrace Outline Körvonal
Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés
Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra.
This script has added a great many objects. Continue, or stop it and undo what it did? Ez a parancsfájl nagyon sok objektumot adott hozzá. Folytatja, vagy leállítja és visszavonja a módosításait?
@msg Choose a .js or .jsx script Válasszon .js vagy .jsx parancsfájlt
@msg Choose a .js, .mjs or .jsx script Válasszon .js, .mjs vagy .jsx parancsfájlt
@msg Ran {name} Lefutott: {name}
@msg The script was stopped and its changes were undone A parancsfájl leállt, a módosításai visszavonva
@msg a script is running: stop it or wait for it to finish egy parancsfájl fut: állítsa le, vagy várja meg, hogy befejeződjön
@@ -5942,7 +5942,7 @@ liquify-list-end {0}, {1} {0} és {1}
@msg `args` is larger than 1 MiB `args`: nagyobb 1 MiB-nál
@msg `path` is empty a `path` üres
@msg `installed` takes a `path`, not a `source` az `installed` `path` értéket vár, nem `source` értéket
@msg `path` must name a .js or .jsx file a `path` értékének .js vagy .jsx fájlt kell megadnia
@msg `path` must name a .js, .mjs or .jsx file a `path` értékének .js, .mjs vagy .jsx fájlt kell megadnia
@msg give exactly one of `path` and `source` pontosan egyet adj meg ezek közül: `path`, `source`
@msg Running a script Parancsfájl futtatása
@msg Copied the script report Szkriptjelentés másolva
Can't render this file because it is too large.
+2 -2
View File
@@ -54,7 +54,7 @@
@msg it decompresses to more than {_1} MB hasil dekompresinya lebih dari {_1} MB
@msg its editing data is for a different page data penyuntingannya untuk halaman lain
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` harus "emBox", "capHeight", "xHeight" atau "icfBox"
@msg Choose a .js or .jsx script Pilih skrip .js atau .jsx
@msg Choose a .js, .mjs or .jsx script Pilih skrip .js, .mjs, atau .jsx
@msg Ran {name} {name} dijalankan
@msg The script was stopped and its changes were undone Skrip dihentikan dan perubahannya dibatalkan
@msg a script is running: stop it or wait for it to finish skrip sedang berjalan: hentikan atau tunggu hingga selesai
@@ -151,7 +151,7 @@
@msg `args` is larger than 1 MiB `args` lebih besar dari 1 MiB
@msg `path` is empty `path` kosong
@msg `installed` takes a `path`, not a `source` `installed` menerima `path`, bukan `source`
@msg `path` must name a .js or .jsx file `path` harus menyebut file .js atau .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` harus menyebut file .js, .mjs, atau .jsx
@msg give exactly one of `path` and `source` berikan tepat satu dari `path` dan `source`
@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why}
@msg `answers[{i}]` {e} `answers[{i}]` {e}
Can't render this file because it is too large.
+2 -2
View File
@@ -4997,7 +4997,7 @@ axis Both Entrambi
Do not show this warning again Non mostrare più questo avviso
Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo.
This script has added a great many objects. Continue, or stop it and undo what it did? Questo script ha aggiunto moltissimi oggetti. Continuare, oppure interromperlo e annullare ciò che ha fatto?
@msg Choose a .js or .jsx script Scegli uno script .js o .jsx
@msg Choose a .js, .mjs or .jsx script Scegli uno script .js, .mjs o .jsx
@msg Ran {name} {name} eseguito
@msg The script was stopped and its changes were undone Lo script è stato interrotto e le sue modifiche sono state annullate
@msg a script is running: stop it or wait for it to finish è in esecuzione uno script: interrompilo o attendi che finisca
@@ -8633,7 +8633,7 @@ breakText Glyphs Glifi
@msg `args` is larger than 1 MiB `args` supera 1 MiB
@msg `path` is empty `path` è vuoto
@msg `installed` takes a `path`, not a `source` `installed` accetta un `path`, non un `source`
@msg `path` must name a .js or .jsx file `path` deve indicare un file .js o .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` deve indicare un file .js, .mjs o .jsx
@msg give exactly one of `path` and `source` indica esattamente uno tra `path` e `source`
@msg `answers` must be a list of answers `answers` deve essere un elenco di risposte
@msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento
Can't render this file because it is too large.
+2 -2
View File
@@ -5824,7 +5824,7 @@ variable-list-end {0}, {1} {0}、{1}
Do not show this warning again 今後この警告を表示しない
Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。
This script has added a great many objects. Continue, or stop it and undo what it did? このスクリプトは非常に多くのオブジェクトを追加しました。続行しますか、それとも停止して変更を取り消しますか?
@msg Choose a .js or .jsx script .js または .jsx スクリプトを選択してください
@msg Choose a .js, .mjs or .jsx script .js、.mjs または .jsx スクリプトを選択してください
@msg Ran {name} {name} を実行しました
@msg The script was stopped and its changes were undone スクリプトを停止し、変更を取り消しました
@msg a script is running: stop it or wait for it to finish スクリプトの実行中です: 停止するか、終了するまでお待ちください
@@ -5971,7 +5971,7 @@ liquify-list-end {0}, {1} {0}、{1}
@msg `args` is larger than 1 MiB `args` が 1 MiB を超えています
@msg `path` is empty `path` が空です
@msg `installed` takes a `path`, not a `source` `installed` には `source` ではなく `path` を指定してください
@msg `path` must name a .js or .jsx file `path` には .js または .jsx ファイルを指定してください
@msg `path` must name a .js, .mjs or .jsx file `path` には .js、.mjs または .jsx ファイルを指定してください
@msg give exactly one of `path` and `source` `path` と `source` のうち 1 つだけを指定してください
@msg Running a script スクリプトを実行中
@msg Copied the script report スクリプトのレポートをコピーしました
Can't render this file because it is too large.
+2 -2
View File
@@ -2140,7 +2140,7 @@
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` უნდა იყოს მთელი რიცხვი 1-დან {_1}-მდე
@msg `max` must be 1 to {MAX_WORDS} `max` უნდა იყოს 1-დან {MAX_WORDS}-მდე
@msg `path` is empty `path` ცარიელია
@msg `path` must name a .js or .jsx file `path` უნდა მიუთითებდეს .js ან .jsx ფაილს
@msg `path` must name a .js, .mjs or .jsx file `path` უნდა მიუთითებდეს .js, .mjs ან .jsx ფაილს
@msg `reference` must be a whole number from 0 to 8 `reference` უნდა იყოს მთელი რიცხვი 0-დან 8-მდე
@msg `ringSeed` must be below 2^53, not {r} `ringSeed` უნდა იყოს 2^53-ზე ნაკლები და არა {r}
@msg `source` is the only path, line or label that graph group `target` stands for `source` ერთადერთი ტრაექტორია, ხაზი ან წარწერაა, რომელსაც დიაგრამის ჯგუფი `target` წარმოადგენს
@@ -8505,7 +8505,7 @@ imageTrace Outline კონტური
Do not show this warning again აღარ აჩვენო ეს გაფრთხილება
Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით.
This script has added a great many objects. Continue, or stop it and undo what it did? ამ სკრიპტმა ძალიან ბევრი ობიექტი დაამატა. გაგრძელდეს, თუ შეჩერდეს და გაუქმდეს მისი ცვლილებები?
@msg Choose a .js or .jsx script აირჩიეთ .js ან .jsx სკრიპტი
@msg Choose a .js, .mjs or .jsx script აირჩიეთ .js, .mjs ან .jsx სკრიპტი
@msg Ran {name} გაშვებულია: {name}
@msg The script was stopped and its changes were undone სკრიპტი შეჩერდა და მისი ცვლილებები გაუქმდა
@msg a script is running: stop it or wait for it to finish სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას
Can't render this file because it is too large.
+2 -2
View File
@@ -5753,7 +5753,7 @@ variable-list-end {0}, {1} {0} 및 {1}
Do not show this warning again 이 경고를 다시 표시하지 않음
Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요.
This script has added a great many objects. Continue, or stop it and undo what it did? 이 스크립트가 매우 많은 개체를 추가했습니다. 계속할까요, 아니면 중지하고 변경 내용을 취소할까요?
@msg Choose a .js or .jsx script .js 또는 .jsx 스크립트를 선택하세요
@msg Choose a .js, .mjs or .jsx script .js, .mjs 또는 .jsx 스크립트를 선택하세요
@msg Ran {name} {name} 실행됨
@msg The script was stopped and its changes were undone 스크립트를 중지하고 변경 내용을 취소했습니다
@msg a script is running: stop it or wait for it to finish 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요
@@ -5900,7 +5900,7 @@ liquify-list-end {0}, {1} {0} 및 {1}
@msg `args` is larger than 1 MiB `args`이(가) 1 MiB보다 큽니다
@msg `path` is empty `path`이(가) 비어 있습니다
@msg `installed` takes a `path`, not a `source` `installed`에는 `source`가 아니라 `path`를 지정하세요
@msg `path` must name a .js or .jsx file `path`은(는) .js 또는 .jsx 파일을 가리켜야 합니다
@msg `path` must name a .js, .mjs or .jsx file `path`은(는) .js, .mjs 또는 .jsx 파일을 가리켜야 합니다
@msg give exactly one of `path` and `source` `path`, `source` 중 정확히 하나를 지정하세요
@msg Running a script 스크립트 실행 중
@msg Copied the script report 스크립트 보고서를 복사했습니다
Can't render this file because it is too large.
+2 -2
View File
@@ -54,7 +54,7 @@
@msg it decompresses to more than {_1} MB gedecomprimeerd is het groter dan {_1} MB
@msg its editing data is for a different page zijn bewerkingsgegevens horen bij een andere pagina
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` moet "emBox", "capHeight", "xHeight" of "icfBox" zijn
@msg Choose a .js or .jsx script Kies een .js- of .jsx-script
@msg Choose a .js, .mjs or .jsx script Kies een .js-, .mjs- of .jsx-script
@msg Ran {name} {name} uitgevoerd
@msg The script was stopped and its changes were undone Het script is gestopt en de wijzigingen ervan zijn ongedaan gemaakt
@msg a script is running: stop it or wait for it to finish er wordt een script uitgevoerd: stop het of wacht tot het klaar is
@@ -221,7 +221,7 @@ liquify-list-end {0}, {1} {0} en {1}
@msg `args` is larger than 1 MiB `args` is groter dan 1 MiB
@msg `path` is empty `path` is leeg
@msg `installed` takes a `path`, not a `source` `installed` neemt een `path`, geen `source`
@msg `path` must name a .js or .jsx file `path` moet een .js- of .jsx-bestand aanwijzen
@msg `path` must name a .js, .mjs or .jsx file `path` moet een .js-, .mjs- of .jsx-bestand aanwijzen
@msg give exactly one of `path` and `source` geef precies een van `path` en `source`
@msg Running a script Er wordt een script uitgevoerd
@msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e}
Can't render this file because it is too large.
+2 -2
View File
@@ -5099,7 +5099,7 @@ imageTrace Outline Kontur
Do not show this warning again Nie pokazuj więcej tego ostrzeżenia
Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie.
This script has added a great many objects. Continue, or stop it and undo what it did? Ten skrypt dodał bardzo wiele obiektów. Kontynuować, czy zatrzymać go i cofnąć jego zmiany?
@msg Choose a .js or .jsx script Wybierz skrypt .js lub .jsx
@msg Choose a .js, .mjs or .jsx script Wybierz skrypt .js, .mjs lub .jsx
@msg Ran {name} Wykonano: {name}
@msg The script was stopped and its changes were undone Skrypt został zatrzymany, a jego zmiany cofnięte
@msg a script is running: stop it or wait for it to finish skrypt jest uruchomiony: zatrzymaj go lub poczekaj na jego zakończenie
@@ -8836,7 +8836,7 @@ breakText Glyphs Glify
@msg `args` is larger than 1 MiB `args` ma rozmiar większy niż 1 MiB
@msg `path` is empty `path` jest puste
@msg `installed` takes a `path`, not a `source` `installed` przyjmuje `path`, a nie `source`
@msg `path` must name a .js or .jsx file `path` musi wskazywać plik .js lub .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` musi wskazywać plik .js, .mjs lub .jsx
@msg give exactly one of `path` and `source` podaj dokładnie jedno z: `path` i `source`
@msg `answers` must be a list of answers `answers` musi być listą odpowiedzi
@msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu
Can't render this file because it is too large.
+2 -2
View File
@@ -6144,7 +6144,7 @@ variable-list-end {0}, {1} {0} e {1}
Do not show this warning again Não mostrar este aviso novamente
Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente.
This script has added a great many objects. Continue, or stop it and undo what it did? Este script adicionou muitíssimos objetos. Continuar, ou pará-lo e desfazer o que ele fez?
@msg Choose a .js or .jsx script Escolha um script .js ou .jsx
@msg Choose a .js, .mjs or .jsx script Escolha um script .js, .mjs ou .jsx
@msg Ran {name} {name} executado
@msg The script was stopped and its changes were undone O script foi parado e suas alterações foram desfeitas
@msg a script is running: stop it or wait for it to finish um script está em execução: pare-o ou aguarde até que termine
@@ -9207,7 +9207,7 @@ swatch Yellow Green Verde-amarelado
@msg `args` is larger than 1 MiB `args` tem mais de 1 MiB
@msg `path` is empty `path` está vazio
@msg `installed` takes a `path`, not a `source` `installed` aceita um `path`, não um `source`
@msg `path` must name a .js or .jsx file `path` deve indicar um arquivo .js ou .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` deve indicar um arquivo .js, .mjs ou .jsx
@msg give exactly one of `path` and `source` informe exatamente um de `path` e `source`
@msg `answers` must be a list of answers `answers` deve ser uma lista de respostas
@msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento
Can't render this file because it is too large.
+2 -2
View File
@@ -4973,7 +4973,7 @@ axis Both Оба
Do not show this warning again Больше не показывать это предупреждение
Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз.
This script has added a great many objects. Continue, or stop it and undo what it did? Этот скрипт добавил очень много объектов. Продолжить или остановить его и отменить его изменения?
@msg Choose a .js or .jsx script Выберите скрипт .js или .jsx
@msg Choose a .js, .mjs or .jsx script Выберите скрипт .js, .mjs или .jsx
@msg Ran {name} Выполнено: {name}
@msg The script was stopped and its changes were undone Скрипт остановлен, его изменения отменены
@msg a script is running: stop it or wait for it to finish выполняется скрипт: остановите его или дождитесь завершения
@@ -5132,7 +5132,7 @@ liquify-list-end {0}, {1} {0} и {1}
@msg `args` is larger than 1 MiB `args` больше 1 МиБ
@msg `path` is empty параметр `path` пуст
@msg `installed` takes a `path`, not a `source` `installed` принимает `path`, а не `source`
@msg `path` must name a .js or .jsx file `path` должен указывать на файл .js или .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` должен указывать на файл .js, .mjs или .jsx
@msg give exactly one of `path` and `source` укажите ровно одно из: `path` и `source`
@msg Running a script Выполняется скрипт
@msg Copied the script report Отчёт о сценарии скопирован
Can't render this file because it is too large.
+2 -2
View File
@@ -4832,7 +4832,7 @@ axis Both Båda
Do not show this warning again Visa inte den här varningen igen
Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen.
This script has added a great many objects. Continue, or stop it and undo what it did? Det här skriptet har lagt till väldigt många objekt. Fortsätta, eller stoppa det och ångra det det gjort?
@msg Choose a .js or .jsx script Välj ett .js- eller .jsx-skript
@msg Choose a .js, .mjs or .jsx script Välj ett .js-, .mjs- eller .jsx-skript
@msg Ran {name} Körde {name}
@msg The script was stopped and its changes were undone Skriptet stoppades och dess ändringar ångrades
@msg a script is running: stop it or wait for it to finish ett skript körs: stoppa det eller vänta tills det är klart
@@ -5005,7 +5005,7 @@ liquify-list-end {0}, {1} {0} och {1}
@msg `args` is larger than 1 MiB `args` är större än 1 MiB
@msg `path` is empty `path` är tomt
@msg `installed` takes a `path`, not a `source` `installed` tar en `path`, inte en `source`
@msg `path` must name a .js or .jsx file `path` måste ange en .js- eller .jsx-fil
@msg `path` must name a .js, .mjs or .jsx file `path` måste ange en .js-, .mjs- eller .jsx-fil
@msg give exactly one of `path` and `source` ange exakt en av `path` och `source`
@msg Running a script Kör ett skript
@msg Copied the script report Kopierade skriptrapporten
Can't render this file because it is too large.
+2 -2
View File
@@ -4678,7 +4678,7 @@ axis Both Her İkisi
Do not show this warning again Bu uyarıyı bir daha gösterme
Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın.
This script has added a great many objects. Continue, or stop it and undo what it did? Bu betik çok sayıda nesne ekledi. Devam edilsin mi, yoksa durdurulup yaptıkları geri mi alınsın?
@msg Choose a .js or .jsx script Bir .js veya .jsx betiği seçin
@msg Choose a .js, .mjs or .jsx script Bir .js, .mjs veya .jsx betiği seçin
@msg Ran {name} {name} çalıştırıldı
@msg The script was stopped and its changes were undone Betik durduruldu ve değişiklikleri geri alındı
@msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin
@@ -4833,7 +4833,7 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg `args` is larger than 1 MiB `args` 1 MiB'tan büyük
@msg `path` is empty `path` boş
@msg `installed` takes a `path`, not a `source` `installed` bir `path` alır, `source` almaz
@msg `path` must name a .js or .jsx file `path` bir .js veya .jsx dosyasını adlandırmalıdır
@msg `path` must name a .js, .mjs or .jsx file `path` bir .js, .mjs veya .jsx dosyasını adlandırmalıdır
@msg give exactly one of `path` and `source` `path` ve `source` değerlerinden tam olarak birini verin
@msg Running a script Betik çalıştırılıyor
@msg Copied the script report Komut dosyası raporu kopyalandı
Can't render this file because it is too large.
+2 -2
View File
@@ -4981,7 +4981,7 @@ axis Both Обидві
Do not show this warning again Більше не показувати це попередження
Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз.
This script has added a great many objects. Continue, or stop it and undo what it did? Цей скрипт додав дуже багато об’єктів. Продовжити чи зупинити його та скасувати його зміни?
@msg Choose a .js or .jsx script Виберіть скрипт .js або .jsx
@msg Choose a .js, .mjs or .jsx script Виберіть скрипт .js, .mjs або .jsx
@msg Ran {name} Виконано: {name}
@msg The script was stopped and its changes were undone Скрипт зупинено, його зміни скасовано
@msg a script is running: stop it or wait for it to finish виконується скрипт: зупиніть його або дочекайтеся завершення
@@ -8792,7 +8792,7 @@ breakText Glyphs Гліфи
@msg `args` is larger than 1 MiB `args` більший за 1 МіБ
@msg `path` is empty параметр `path` порожній
@msg `installed` takes a `path`, not a `source` `installed` приймає `path`, а не `source`
@msg `path` must name a .js or .jsx file `path` має вказувати на файл .js або .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` має вказувати на файл .js, .mjs або .jsx
@msg give exactly one of `path` and `source` укажіть рівно одне з: `path`, `source`
@msg `answers` must be a list of answers `answers` має бути списком відповідей
@msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа
Can't render this file because it is too large.
+2 -2
View File
@@ -5460,7 +5460,7 @@ theme Appearance Giao diện
Do not show this warning again Không hiện lại cảnh báo này
Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại.
This script has added a great many objects. Continue, or stop it and undo what it did? Tập lệnh này đã thêm rất nhiều đối tượng. Tiếp tục, hay dừng lại và hoàn tác những gì nó đã làm?
@msg Choose a .js or .jsx script Chọn một tập lệnh .js hoặc .jsx
@msg Choose a .js, .mjs or .jsx script Chọn một tập lệnh .js, .mjs hoặc .jsx
@msg Ran {name} Đã chạy {name}
@msg The script was stopped and its changes were undone Tập lệnh đã dừng và các thay đổi của nó đã được hoàn tác
@msg a script is running: stop it or wait for it to finish một tập lệnh đang chạy: hãy dừng nó hoặc chờ nó kết thúc
@@ -5632,7 +5632,7 @@ liquify-list-end {0}, {1} {0} và {1}
@msg `args` is larger than 1 MiB `args` lớn hơn 1 MiB
@msg `path` is empty `path` trống
@msg `installed` takes a `path`, not a `source` `installed` nhận `path`, không nhận `source`
@msg `path` must name a .js or .jsx file `path` phải chỉ đến tệp .js hoặc .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` phải chỉ đến tệp .js, .mjs hoặc .jsx
@msg give exactly one of `path` and `source` hãy cung cấp đúng một trong `path` và `source`
@msg Running a script Đang chạy tập lệnh
@msg Copied the script report Đã sao chép báo cáo script
Can't render this file because it is too large.
+2 -2
View File
@@ -5489,7 +5489,7 @@ imageTrace Outline 轮廓
Do not show this warning again 不再显示此警告
Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。
This script has added a great many objects. Continue, or stop it and undo what it did? 此脚本已添加大量对象。要继续,还是停止并撤销其更改?
@msg Choose a .js or .jsx script 请选择 .js 或 .jsx 脚本
@msg Choose a .js, .mjs or .jsx script 请选择 .js、.mjs 或 .jsx 脚本
@msg Ran {name} 已运行 {name}
@msg The script was stopped and its changes were undone 脚本已停止,其更改已撤销
@msg a script is running: stop it or wait for it to finish 脚本正在运行:请停止它或等待其完成
@@ -8844,7 +8844,7 @@ breakText Glyphs 字形
@msg `args` is larger than 1 MiB `args` 大于 1 MiB
@msg `path` is empty `path` 为空
@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source`
@msg `path` must name a .js or .jsx file `path` 必须指向 .js 或 .jsx 文件
@msg `path` must name a .js, .mjs or .jsx file `path` 必须指向 .js、.mjs 或 .jsx 文件
@msg give exactly one of `path` and `source` `path` 和 `source` 中必须且只能给出一个
@msg `answers` must be a list of answers `answers` 必须是回答的列表
@msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引
Can't render this file because it is too large.
+2 -2
View File
@@ -2821,7 +2821,7 @@ file-filter Templates 範本
Do not show this warning again 不再顯示此警告
Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。
This script has added a great many objects. Continue, or stop it and undo what it did? 此指令碼已新增大量物件。要繼續,還是停止並還原其變更?
@msg Choose a .js or .jsx script 請選擇 .js 或 .jsx 指令碼
@msg Choose a .js, .mjs or .jsx script 請選擇 .js、.mjs 或 .jsx 指令碼
@msg Ran {name} 已執行 {name}
@msg The script was stopped and its changes were undone 指令碼已停止,其變更已還原
@msg a script is running: stop it or wait for it to finish 指令碼正在執行:請停止它或等待其完成
@@ -2968,7 +2968,7 @@ liquify-list-end {0}, {1} {0}和{1}
@msg `args` is larger than 1 MiB `args` 大於 1 MiB
@msg `path` is empty `path` 為空
@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source`
@msg `path` must name a .js or .jsx file `path` 必須指向 .js 或 .jsx 檔案
@msg `path` must name a .js, .mjs or .jsx file `path` 必須指向 .js、.mjs 或 .jsx 檔案
@msg give exactly one of `path` and `source` `path` 和 `source` 請只提供其中一個
@msg Running a script 正在執行指令碼
@msg Copied the script report 已複製指令碼報告
Can't render this file because it is too large.
+2 -2
View File
@@ -2071,13 +2071,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.runScript",
"Other Script…",
"Cmd+F12",
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
"{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
crate::scripts_menu::COMMAND,
"Run Script",
"",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
"ui.checkScript",
+12 -1
View File
@@ -192,7 +192,7 @@ fn only_js_and_jsx_files_are_taken() {
let mut app = app();
for name in ["a.txt", "a.jsxbin", "a"] {
let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": name })).unwrap().unwrap_err();
assert!(e.contains(".js or .jsx"), "{name}: {e}");
assert!(e.contains(".js, .mjs or .jsx"), "{name}: {e}");
}
assert!(!app.any_dialog_open());
assert!(!is_open::<RunQuestion>(&app));
@@ -247,6 +247,17 @@ fn a_picked_script_goes_to_the_warning() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_web_pick_of_a_mjs_file_runs_as_a_module() {
let mut app = app();
app.session.prefs.show_external_script_warning = false;
// `export` is a syntax error outside a module, and `this` is undefined at a module's top.
let module = format!("export var a = 1;\nif (this !== undefined) throw new Error('not a module');\n{DRAW}");
script_run::picked_script(&mut app, Picked::Contents(vec![("Picked.MJS".into(), module.into_bytes())])).unwrap();
finish(&mut app);
assert_eq!(objects(&app), 2, "{}", app.ui.status);
}
#[test]
fn a_web_pick_that_is_not_text_is_reported() {
let mut app = app();
+56 -8
View File
@@ -2773,12 +2773,12 @@ the included files too.
vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}'
```
`script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents.
`script.run {path? | source?, module?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents.
In an ES2015 realm, `Symbol.for` lookups and insertions take fuel for the key's code units. A registered description
shares the key's existing string buffer.
Block-scoped declaration checks retain one copy of each `var` declaration name through nested blocks.
File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page
File › Scripts › Other Script… (Cmd+F12) picks a `.js`, `.mjs` or `.jsx` file and runs it the same way; the help page
https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html
describes that menu item. Its warning before the run lists what `script.check` finds the script reaches outside
the document, read without running it: each `outside` category of the report (files it writes, moves or deletes,
@@ -2789,7 +2789,7 @@ says when the script is too large to check, compiled or not a script, when the c
short at its limit. The listing does not stop the run. Run checks the script again, and when the report has changed
since the warning opened, nothing runs and the warning opens again with the new report. A script from the Scripts
folder runs without the warning.
Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
Pass exactly one of `path` and `source`. A `path` must end in `.js`, `.mjs` or `.jsx`, in any
case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is
not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and
`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in
@@ -2835,23 +2835,71 @@ throws a `TypeError`, since that engine was made without the ECMAScript 2015 bui
an engine that `#targetengine` keeps reads each run the way that run's script does. A
`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there
`yield` is a name like any other. A `.js` file
`.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and
accept the ECMAScript 2015 forms listed here. A `.js` file
also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`,
`f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or
`null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&`
or `||` without parentheses, and assigning to an optional chain, are syntax errors. In a `.jsx` file and a `source`
string, `?.` and `??` are syntax errors. Which files read these forms is VectorCraft's own rule. Every script, `.js`,
`.jsx` or `source`, also reads ECMAScript for XML (E4X, ECMA-357, 2nd edition,
string that runs as a script, `?.` and `??` are syntax errors. Which files read these forms is VectorCraft's own rule.
Every script, `.js`, `.jsx` or `source`, also reads ECMAScript for XML (E4X, ECMA-357, 2nd edition,
https://ecma-international.org/publications-and-standards/standards/ecma-357/): XML and XMLList literals, the `..`,
`.@`, `.*`, `.()` and `::` selectors, `for each`, `default xml namespace`, and the global `XML`, `XMLList`,
`Namespace`, `QName`, `isXMLName` and `setDefaultXMLNamespace`, as the XML object pages describe them
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file also has
`Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a named engine
(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file or a module also has
`Promise` (described below); a `.jsx` file and a script given as `source` that runs as a script do not, except that a named engine
(`#targetengine`) has `Promise` from the first `.js` or module run that names it and keeps it for every later run, as it keeps
its globals. An ES5.1 script does not have `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` or the
typed arrays; the JavaScript engine's ECMAScript 2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as
`docs/target-app-parity.md` describes. The collector retains tagged-template cache entries only while the site's code
is reachable. The script reaches the app through the global object `vc`, and writes to the Script Console and runs
other files through `$`:
`Promise` (described below); a `.jsx` file and a `source` string that runs as a script do not, except that a named engine
(`#targetengine`) has `Promise` from its first `.js` or module run and keeps it for every later run, as it keeps its globals.
A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module
(https://262.ecma-international.org/6.0/#sec-modules): strict mode code with the forms above (optional chains and `??`
included), and `import` and
`export` declarations at its top level. Module source reserves `await` as an identifier. A module namespace has an
own `Symbol.toStringTag` property with value `"Module"` that is nonwritable, nonenumerable and nonconfigurable.
`import` and `export` are syntax errors in a `.js` or `.jsx` script.
`module` (true or false) chooses this for any `path` or `source`; it defaults to true for a `path` that ends in
`.mjs` and false otherwise. The app passes `module: true` for a `.mjs` file picked on the web, where the script
arrives as `source`. A `source` that runs as a module imports no files: each import ends the run with an error that
names the specifier.
- A specifier is a path relative to the file that imports it. It starts with `./` or `../`, separates names with
`/` and names a `.mjs` or `.js` file, which is read as a module. A bare name such as `'lib'`, a URL, an absolute
path, and a specifier with `\`, `:` or a control character end the run with a `SyntaxError` that names the
specifier.
- Modules are read through the script's own file scope: only from the script's folder and the folders below it.
A specifier whose `..` names lead above the script's folder, and a link that leads out of it, end the run with an
error that names the specifier. A missing file ends the run with an error that names the specifier.
- Every module is read, parsed and linked before any of them runs. A syntax error, a missing or refused file, an
import of a name the module does not export, and an import of a name that two `export *` declarations give from
different modules end the run with no code run, at the file, line and column of the module they are in.
- Each module runs once in a run, after the modules it imports, in the order it imports them. 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. Two paths to one file
(a link, `sub/../x.mjs`, or names that differ only in letter case in a Windows folder that ignores case) are one
module, and a module's relative imports are read from the folder the file is in, whichever path reached it first. An import reads
the exporting module's binding each time, so it sees later assignments, and reading it before that module has
initialized it (in a cycle of imports) throws a `ReferenceError`. Assigning to an import throws a `TypeError`.
- `import * as ns` gives a namespace object: not extensible, with no prototype, its export names in code unit order
as properties that cannot be written or deleted, and `[object Module]` from `Object.prototype.toString`.
Export redefinitions use the ECMAScript 2020 rule, which accepts a descriptor only when it leaves the current
export unchanged (https://262.ecma-international.org/11.0/#sec-module-namespace-exotic-objects-defineownproperty-p-desc).
`export *` passes on every name but `default`, and `export * as ns from` passes on a namespace.
- A module's top-level names stay in the module, `this` is `undefined` at its top, it has no preprocessor lines,
and `import()` is a syntax error. `vc`, `$` and the other globals are there as in a script.
- In the host API, `Realm::run_module` drains queued Promise jobs before returning, as sliced module execution does.
`Realm::start_module` and `Realm::run_module` end a paused or waiting run before loading replacement source,
including when that source fails to compile. Existing globals remain available.
- Module files count against the limits of `#include` files: 8 MiB a file, 32 MiB of source in all, 64 files
besides the script, imports 16 deep and 1,024 paths looked up. These limits are VectorCraft's own.
The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files
through `$`:
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
catch. The documents and the session state the command changed, preferences included, go back, and any file it
+5 -2
View File
@@ -55,6 +55,8 @@ Block-scoped declaration checks keep each `var` declaration name in the current
- Fold Preview orders overlapping coplanar panels by their fold tree, draws distinct planes and crossing panels by depth, and calculates poses relative to the blank's center. Each plane uses one comparison depth, and every member of a plane group must match every other member. A hinge uses its longest line across all split pieces. Tests cover flat, near-flat, nested and offset folds in `crates/three-d/src/fold/tests.rs` and `crates/three-d/src/fold/raster/tests.rs`.
- `addon.packaging.setFoldAngle` stores or resets individual fold angles for editable Crease, Partial Cut, and Perforation lines. The fold commands read those angles, and role queries report their shared value and stored-angle counts. Engine tests cover validation, locked compound members, one-step undo, native save, and SVG exports.
Synchronous module execution through `Realm::run_module` drains queued Promise jobs before returning. Both module entry points end a paused or waiting run before loading new source and preserve existing globals. Module namespaces expose an immutable own `Symbol.toStringTag` property with value `"Module"`, and module source rejects `await` identifiers before dependencies execute. `crates/js/src/module_tests.rs` compares resolution and rejection callbacks with sliced execution and covers paused-script replacement with valid and invalid module source, namespace properties and reserved identifiers.
`vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings.
Scripts: `Promise.prototype[Symbol.toStringTag]` is `"Promise"` when Symbols are available, with a configurable, non-enumerable, non-writable descriptor. Promise instances report `[object Promise]` in engines without Symbols. Test: `promise_prototype_has_a_configurable_string_tag` in `crates/js/src/promise_tests.rs`.
@@ -1186,10 +1188,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans. A comma may follow the last argument of a call or `new` expression and the last parameter of a function other than a setter, as ECMAScript 2017 allows (https://tc39.es/ecma262/2017/#sec-left-hand-side-expressions, https://tc39.es/ecma262/2017/#sec-function-definitions); `f(,)` and `f(1,,)` give a `SyntaxError`. It reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`.
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
- `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,676 of 4,682 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. Modules are still syntax errors. `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`.
- 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. `import` and `export` outside a module are syntax errors (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`.
The collector retains tagged-template cache entries only while the site's code is reachable.
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.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 read them and `.jsx` files and `source` strings 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 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`.
@@ -1283,7 +1286,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`).
- The status bar translates the errors of Object › Plug-ins › Cutting Tools › Banner Hems and Grommets… and the line for a recovery copy that fails in a store with no folder to name (`{saving} failed: {e}`) in every language that translates every message. The untranslated-strings report also lists the messages a status takes from a local variable, such as the recovery folder errors (`banner_and_recovery_messages_are_translated_in_every_complete_catalog`, `message_scan_reads_locals_given_to_a_status`).
- The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`).
- The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`).
- The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js, .mjs or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`).
- The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). A native speaker has not reviewed the wording.
- A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`).
- Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`).