diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 67d6556bbe..fa4d7ea425 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{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), 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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, and an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -173,6 +173,7 @@ fn run(s: &mut Session, p: &Value) -> Result { } 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")), @@ -217,6 +218,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, + module, }; let name = s.script_start(request)?; if s.script_frames { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index abc7fa0740..cd45cccaaf 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -640,6 +640,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), 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>), 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); @@ -655,6 +664,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() { @@ -672,7 +684,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). @@ -891,6 +903,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] diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 8de325cb70..bc91914f0b 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -249,8 +249,9 @@ pub(crate) fn module_script(path: Option<&str>) -> bool { } /// What names the file at the real path `real` among a run's modules: on Unix its device and file -/// number, so two paths to one file give one module; elsewhere its path, in lowercase on Windows, -/// whose file names ignore letter case. +/// 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)] { @@ -259,8 +260,13 @@ fn module_key(real: &Path) -> String { return format!("{}:{}", m.dev(), m.ino()); } } - let shown = display(real).to_string(); - if cfg!(windows) { shown.to_lowercase() } else { shown } + 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> { + 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 @@ -380,6 +386,11 @@ impl Files { } } + /// 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()); @@ -417,30 +428,38 @@ impl Files { if self.probes > MAX_PROBES { return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached"))); } - let candidate = path.iter().fold(root, |p, name| p.join(name)); - let (real, bytes) = match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { + 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())); } - self.bytes += bytes.len(); - let key = module_key(&real); - self.module_paths.insert(relative, key.clone()); - if self.module_dirs.contains_key(&key) { - return Ok((key, None)); - } if self.files >= MAX_FILES { return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); } - self.files += 1; let text = decode(&bytes, specifier).map_err(LoadError::Other)?; + 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(); - self.module_dirs.insert(key.clone(), path); + 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)))) } @@ -483,12 +502,20 @@ 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 { + /// The folder of the module `key` ([`Files::module`] gave it), from the script's folder. + pub(crate) fn module_dir(&self, key: &str) -> Option { + 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 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) -> Result { 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); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index e318c0abb6..101cdc2bac 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -202,6 +202,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, + /// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]). + pub module: bool, } thread_local! { @@ -777,6 +779,9 @@ struct Host { script_map: RefCell, /// The same for each source `$.evalFile` gave, in order. eval_maps: RefCell>, + /// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a + /// module's, by its index there. + module_maps: RefCell>, /// 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, u32, u32)>>, @@ -932,6 +937,18 @@ impl Host { } } + /// The folder of the module whose source has `tag`, when it is a module the script imported + /// (not the script itself, a file `$.evalFile` gave, or code from another run). + fn module_dir_at(&self, tag: u32) -> Option { + 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).filter(|n| *n > 0)?; + 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 }; @@ -1436,6 +1453,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc) -> std::result::Result { +/// 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) -> std::result::Result { + 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())); }; @@ -1466,7 +1492,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message }; let error = match f.kind { include::FailKind::Limit => HostError::Abort(message), @@ -1582,7 +1608,10 @@ fn explained(e: &RunError) -> String { fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result { let (key, read) = host.files.borrow_mut().module(referrer, specifier)?; let source = read.map(|(text, map)| { - host.eval_maps.borrow_mut().push(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::>()); text }); @@ -1951,9 +1980,12 @@ 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()); - // A `.mjs` script is a module, with no preprocessor lines; `module_key` names it among the - // modules it imports. - let (expanded, module_key) = if include::module_script(request.file.as_deref()) { + 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), @@ -1992,7 +2024,7 @@ impl Session { let fresh = realm.is_none(); // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read // code the way the script does. - let es2015 = include::es2015_script(request.file.as_deref()); + 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, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. @@ -2058,6 +2090,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()), diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..e64f7c3ad2 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -359,6 +359,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, }; s.script_start(request).unwrap(); assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1])); diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs index 9727abb927..0dec7ea7da 100644 --- a/crates/engine/src/tests/script_modules.rs +++ b/crates/engine/src/tests/script_modules.rs @@ -225,3 +225,78 @@ fn script_module_is_listed_and_taken_by_path() { 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); +} diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index a5d39c0b06..ce1e66f6d1 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -483,7 +483,11 @@ pub enum ImportName { /// 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, pub span: Span, } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 537752b9fe..eae7ae1924 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -250,8 +250,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, HashSet, HashSet)> = 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, HashSet, HashSet)> = 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()) { @@ -285,7 +287,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, .. } => { @@ -293,7 +295,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)); } } @@ -322,23 +324,27 @@ 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 { - let s = enter(self.lexical_names(&h.body), self.block_function_names(&h.body)); + let s = if inner { enter(self.lexical_names(&h.body), 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(_) @@ -921,8 +927,12 @@ impl<'a> FnCompiler<'a> { fn switch_stmt(&mut self, id: StmtId, labels: Vec) -> CResult<()> { let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") }; self.expr(*discriminant)?; - let all: Vec = 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 = 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; diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 0173fb2d6c..07032c6506 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -97,8 +97,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"); } @@ -167,7 +175,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] @@ -269,8 +277,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() { assert!(is_thrown(&realm.run("let z;"), "SyntaxError")); assert_eq!(realm.run("delete z"), Ok(JsValue::Bool(true))); assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0))); + // 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_eq!(realm.run("let w = 4; w"), Ok(JsValue::Number(4.0))); + 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:?}"); } #[test] @@ -343,6 +357,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')"); + // Other functions keep their attributes. + 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;"); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f158f45a0f..34ac97155d 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -186,7 +186,7 @@ pub(crate) enum Func { Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, - Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, + Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc, site: bool }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..156849035f 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -148,11 +148,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, strict_writes: Rc Option>, + site: bool, }, /// A read-only property that reads the interpreter's own state. Script(ScriptItem), @@ -414,7 +417,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, @@ -422,8 +426,13 @@ impl Interp { strict_writes: &Rc Option>, name: &Rc, args: &[Value], + site: bool, ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let caller = site.then(|| self.call_site()); + let mut data = self.read_args(name, 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), @@ -586,9 +595,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 } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..2df62d419f 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -284,7 +284,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(); @@ -306,6 +306,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>>> = 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); @@ -658,7 +683,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()); @@ -680,7 +705,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)); @@ -695,7 +720,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(); @@ -728,7 +753,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(); @@ -749,7 +774,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(); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ae755f3aa3..a3b62411e1 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1387,7 +1387,17 @@ impl Interp { } _ => return internal("not a declarative environment"), }, - Resolved::Obj { object, .. } => self.delete(object, &name, false)?, + Resolved::Obj { object, with_this } => { + let deleted = self.delete(object, &name, false)?; + // A deleted global variable no longer stops a `let` or `const` of its name: the + // global environment's DeleteBinding drops it from its var names (ECMA-262 2015 + // section 8.1.1.4.7). Deleting the global object's property by any other route + // leaves the name recorded. + if deleted && !with_this && object == self.global { + self.global_vars.remove(&name); + } + deleted + } }; self.push(Value::Bool(result)) } @@ -1532,11 +1542,16 @@ impl Interp { /// [[GetProperty]]: the property found on the object or its prototype chain. pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult> { + 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> { 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))); } cur = self.object(o)?.proto; steps += 1; @@ -1553,10 +1568,14 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + 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). - self.check_namespace_export(start, k)?; - match self.find_property(start, k)? { + // 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) { 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, &[]), @@ -1863,8 +1882,26 @@ impl Interp { Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), None => {} } - let proto = self.object(id)?.proto; - match 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"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), @@ -1930,12 +1967,6 @@ impl Interp { match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { - // A deleted global variable no longer stops a `let` or `const` of its name - // (ECMA-262 2015 section 8.1.1.4.7), and the names kept are never more than the - // global object's properties. - if id == self.global { - self.global_vars.remove(k); - } let o = self.object_mut(id)?; o.props.remove(k); if let Class::Arguments(map) = &mut o.class @@ -2216,7 +2247,10 @@ impl Interp { let arrow = code.arrow; let self_name = code.self_name.clone(); let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto))); - self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + // An arrow function's `length` is configurable (ECMA-262 2015 section 9.2.4, + // FunctionInitialize); the other forms keep their earlier attributes. + let length_flags = if arrow { CONFIGURABLE } else { 0 }; + self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: length_flags })?; // An arrow function has no `prototype` and cannot be constructed (section 14.2.16). if arrow { return Ok(f); @@ -2670,14 +2704,9 @@ 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 reads each one (ECMA-262 2015 section 9.4.6.5). + // 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| { - for k in &keys { - self.check_namespace_export(o, k)?; - } - Ok(keys) - }); - let keys = keys.and_then(|keys| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); @@ -2780,8 +2809,8 @@ impl Interp { // keeps itself reachable. return Ok(Prepared::Done(self.call_data(&f, &name, &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 = args.iter().map(|v| self.to_js_value(v)).collect(); @@ -3435,7 +3464,8 @@ impl Interp { /// 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) -> JsResult<(EnvId, EnvId)> { - self.charge_code(code, declaration_bytes(code).saturating_add(ENV_BYTES))?; + // 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); @@ -3501,6 +3531,24 @@ impl Interp { 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) -> 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); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 8f99275192..09fdc4b715 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -61,7 +61,10 @@ //! [`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. +//! 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. #![forbid(unsafe_code)] diff --git a/crates/js/src/module.rs b/crates/js/src/module.rs index b706c280f5..e8147668cd 100644 --- a/crates/js/src/module.rs +++ b/crates/js/src/module.rs @@ -17,7 +17,7 @@ //! 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; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ExportEntry, ImportName, ModuleInfo}; @@ -84,6 +84,11 @@ struct Record { /// The environment its code runs in and the outer one, once instantiated. envs: Option<(EnvId, EnvId)>, namespace: Option, + /// Each name the module exports itself or re-exports by name, with its entry in + /// `info.exports`. + explicit: HashMap, + /// The request each `export *` of the module names, in order. + stars: Vec, } /// Why a module run could not start. @@ -153,7 +158,19 @@ impl Graph<'_, '_> { Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }), Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))), }; - self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None }); + // 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) @@ -175,10 +192,21 @@ impl Graph<'_, '_> { let mut depths = vec![0usize]; let mut i = 0; while i < self.records.len() { - let requests: Vec<(String, u32)> = self.records[i].info.requests.iter().map(|r| (r.specifier.clone(), r.span.start)).collect(); + 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, offset) in requests { + 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, @@ -247,29 +275,28 @@ impl Graph<'_, '_> { } self.interp.use_fuel().map_err(LinkFail::Run)?; seen.push((m, name.to_string())); - let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); - for e in &exports { - match e { - ExportEntry::Local { export_name, local, .. } if export_name == name => { - return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))); - } - ExportEntry::Indirect { export_name, request, import, .. } if export_name == name => { - 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), - }; - } - _ => {} + 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; - for e in &exports { - let ExportEntry::Star { request, .. } = e else { continue }; - let Some(t) = self.target(m, *request) else { continue }; + let stars = record.stars.clone(); + for request in stars { + let Some(t) = self.target(m, request) else { continue }; match self.resolve_export(t, name, seen)? { Err(Ambiguous) => return Ok(Err(Ambiguous)), Ok(None) => {} @@ -285,23 +312,32 @@ impl Graph<'_, '_> { /// 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, names: &mut Vec) -> Result<(), LinkFail> { + fn exported_names( + &mut self, + m: usize, + star: bool, + visited: &mut Vec, + names: &mut Vec, + seen: &mut HashSet, + ) -> Result<(), LinkFail> { if visited.contains(&m) { return Ok(()); } visited.push(m); - let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); - for e in &exports { + 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") && !names.contains(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)?; + self.exported_names(t, true, visited, names, seen)?; } } } @@ -322,7 +358,7 @@ impl Graph<'_, '_> { return Ok(ns); } let mut names = Vec::new(); - self.exported_names(m, false, &mut Vec::new(), &mut names)?; + self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?; let mut resolved = Vec::new(); for name in names { if let Ok(Some(r)) = self.resolve_export(m, &name, &mut Vec::new())? { diff --git a/crates/js/src/module_tests.rs b/crates/js/src/module_tests.rs index 26f453b652..55c75139b4 100644 --- a/crates/js/src/module_tests.rs +++ b/crates/js/src/module_tests.rs @@ -105,6 +105,31 @@ fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() { 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;"; @@ -175,10 +200,14 @@ fn reading_an_import_before_its_module_ran_is_a_reference_error() { 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'), () => { for (var k in ns) {} }, () => Object.isSealed(ns), () => Object.isFrozen(ns), - () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns)]; + () => 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); } }); - out.push('a' in ns, Object.getOwnPropertyNames(ns).join());"; + // 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| { @@ -186,8 +215,8 @@ fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() { }; 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(12); - assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}true|a")))); + let errors = "ReferenceError|".repeat(13); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a")))); } #[test] @@ -401,19 +430,79 @@ fn a_module_lists_what_it_imports_and_exports() { ); } +#[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 = ".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 = (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)]); - let r = realm.run_module( + // 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, ); - assert_eq!(r, Ok(JsValue::Undefined)); + 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"]); +} diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 28b7cd5f72..573bd06072 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -533,6 +533,11 @@ impl<'s> Parser<'s> { Ok(self.ast.push_stmt(Stmt::Empty, start)) } TokenKind::Keyword(k) => self.keyword_statement(*k, start), + // An expression statement cannot start with `let [` (ECMA-262 2015 section 13.5), so + // the body of an `if` or a loop cannot be a `let` declaration with a pattern either. + _ if self.es2015 && self.tok.ident() == Some("let") && !self.tok.escaped && self.peek().is_some_and(|t| t.is_punct(Punct::LBracket)) => { + Err(self.error_at_token(&self.tok, "a lexical declaration cannot stand here; put it in a block")) + } _ => { let expr = self.parse_expression(false)?; self.semicolon()?; diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index ec39092afb..ca5317ca4e 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -65,18 +65,18 @@ impl Parser<'_> { } /// 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) -> Result { 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)))); }; - let Ok(specifier) = String::from_utf16(units) else { - return Err(self.error_at_token(&self.tok, "a module specifier must be valid text")); - }; + let units = units.to_vec(); let span = self.bump()?.span; - if let Some(i) = info.requests.iter().position(|r| r.specifier == specifier) { + if let Some(i) = info.requests.iter().position(|r| r.units == units) { return Ok(i); } - info.requests.push(ModuleRequest { specifier, span }); + let specifier = String::from_utf16_lossy(&units); + info.requests.push(ModuleRequest { specifier, units, span }); Ok(info.requests.len() - 1) } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 1765d6d9d1..0e648d4fcc 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -295,7 +295,7 @@ impl Realm { 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()); + 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), @@ -304,6 +304,7 @@ impl Realm { 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 }) => { diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 3e3472d634..01d9e98665 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -50,7 +50,8 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vectorcraft_js::{ - JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, tokenize_module, + JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, + tokenize_module, }; /// A test file's metadata, from its `/*--- … ---*/` block. @@ -845,9 +846,12 @@ fn module_path(referrer: &str, specifier: &str) -> Result { /// 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. A `negative_type` is the error the run must end with: thrown, -/// or, for a `SyntaxError`, also a module that does not parse. -fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_type: Option<&str>, options: &Options) -> Result<(), String> { +/// 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(); @@ -857,10 +861,29 @@ fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_t let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None }; Ok(LoadedModule { key, source }) }; - match (realm.run_module(rel, source, ModuleLimits::default(), &mut load), negative_type) { + 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 e.kind == RunErrorKind::Syntax => Ok(()), + (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}")) { @@ -886,6 +909,7 @@ fn run_modules(dir: &Path) { 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()); @@ -913,6 +937,7 @@ fn run_modules(dir: &Path) { } 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 { @@ -930,9 +955,12 @@ fn run_modules(dir: &Path) { } } else { let prelude = format!("{prelude}{includes}"); - match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative_type.as_deref(), &options)) { + match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative, &options)) { Ok(r) => r, - Err(_) => Err("PANIC".to_string()), + Err(_) => { + panics += 1; + Err("PANIC".to_string()) + } } }; match outcome { @@ -958,7 +986,7 @@ fn run_modules(dir: &Path) { after.1, report.display() ); - assert!(!failures.contains("PANIC"), "the interpreter panicked; see {}", report.display()); + assert_eq!(panics, 0, "the interpreter panicked; see {}", report.display()); } #[test] diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f281431dc5..46ddcfeb3d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -119,7 +119,10 @@ pub(crate) fn drain(app: &mut VectorcraftApp) { let Some((name, bytes)) = app.services.script_inbox.as_ref().and_then(|q| q.lock().unwrap_or_else(|e| e.into_inner()).pop()) else { return }; let result = match bytes.as_deref().map(std::str::from_utf8) { None => Err(TOO_LARGE.to_string()), - Some(Ok(source)) => chosen(app, json!({"source": source, "name": name})), + Some(Ok(source)) => { + let module = std::path::Path::new(&name).extension().is_some_and(|e| e.eq_ignore_ascii_case("mjs")); + chosen(app, json!({"source": source, "name": name, "module": module})) + } Some(Err(_)) => Err("the script is not UTF-8 text".to_string()), }; if let Err(e) = result { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index f8d3d4c39e..7106b22f14 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -164,6 +164,18 @@ fn a_web_pick_goes_to_the_warning_and_waits_for_an_open_dialog() { assert_eq!(objects(&app), 2); } +#[test] +fn a_web_pick_of_a_mjs_file_runs_as_a_module() { + let (mut app, inbox, _picks) = app_with_picker(); + 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}"); + inbox.lock().unwrap().push(("Picked.MJS".to_string(), Some(module.into_bytes()))); + script_runs::poll(&mut app); + 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, inbox, _picks) = app_with_picker(); diff --git a/docs/mcp.md b/docs/mcp.md index b34a4ebed6..5a882a3371 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2610,7 +2610,7 @@ 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. 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. Pass exactly one of `path` and `source`. A `path` must end in `.js`, `.mjs` or `.jsx`, in @@ -2630,6 +2630,10 @@ an engine that `#targetengine` keeps reads each run the way that run's script do 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, and `import` and `export` declarations at its top level. `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 @@ -2641,8 +2645,11 @@ A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module - 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; two paths to one file - (a link, `sub/../x.mjs`, or names that differ only in letter case on Windows) are one module. An import reads +- 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 15745fc595..04effe52c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1080,7 +1080,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `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,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. 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. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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. 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: 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. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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`.