diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 62a07282e8..00d0a3a371 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2117,6 +2117,7 @@ impl Session { Ok(expanded) => { *host.script_map.borrow_mut() = expanded.map; realm.set_strict_writes(expanded.strict == Some(true)); + realm.set_script_name(Some(host.name.to_string())); if fresh { let l = link.clone(); realm.set_source_locator(Rc::new(move |tag, line| match current(&l) { diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs index bef2cf5c93..cb588abe14 100644 --- a/crates/engine/src/tests/script_dollar.rs +++ b/crates/engine/src/tests/script_dollar.rs @@ -63,7 +63,7 @@ fn each_member_has_its_value() { ("$.memCache", json!(0)), ("$.os", json!(os)), ("$.screens.length", json!(0)), - ("$.stack", json!("[global]@t.js:1\n")), + ("$.stack", json!("[t.js]\n[global]@t.js:1\n")), ("$.strict", json!(false)), ("$.version", json!(version)), ("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")), @@ -174,10 +174,31 @@ fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { fn error_line_and_stack_follow_the_running_code() { let mut s = Session::new(); let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());"; - assert_eq!(logged(&mut s, source)[0], json!([3, "[global]@t.js:5\nwhere@t.js:3\n", true])); + assert_eq!(logged(&mut s, source)[0], json!([3, "[t.js]\n[global]@t.js:5\nwhere@t.js:3\n", true])); assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one"); } +/// `$.stack`'s first line is the run's name in square brackets, the name `script.run` reports, +/// in a function as at the top level. +#[test] +fn the_stack_starts_with_the_runs_name() { + let mut s = Session::new(); + let first = |s: &mut Session, params: Value| { + let r = s.execute("script.run", ¶ms).unwrap_or_else(|e| panic!("{params}: {e}")); + let line = r["log"][0].as_str().unwrap_or_default().to_string(); + (line, r["name"].clone()) + }; + let top = "vc.log($.stack.split('\\n')[0]);"; + let (line, name) = first(&mut s, json!({"source": top, "name": "Marks.jsx"})); + assert_eq!((line.as_str(), name), ("[Marks.jsx]", json!("Marks.jsx"))); + let inner = "function f() { return $.stack.split('\\n')[0]; }\nvc.log(f());"; + assert_eq!(first(&mut s, json!({"source": inner, "name": "Marks.jsx"})).0, "[Marks.jsx]"); + let (line, name) = first(&mut s, json!({"source": format!("#script \"Named\"\n{top}")})); + assert_eq!((line.as_str(), name), ("[Named]", json!("Named")), "a #script line names the run"); + let (line, name) = first(&mut s, json!({"source": top})); + assert_eq!(format!("[{}]", name.as_str().unwrap_or_default()), line, "a run given no name"); +} + #[test] fn sleep_waits_between_slices_until_its_time_has_passed() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_engines.rs b/crates/engine/src/tests/script_engines.rs index a25b0489ba..9723464bfb 100644 --- a/crates/engine/src/tests/script_engines.rs +++ b/crates/engine/src/tests/script_engines.rs @@ -298,19 +298,23 @@ fn the_line_and_the_stack_of_code_an_earlier_run_kept_are_at_that_runs_files() { }; let r = call(&mut s, "vc.log(fromMain());"); assert_eq!(r[0], 4, "{r}"); - assert_eq!(short_stack(&r[1]), "[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n"); - assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[global]@caller.js:3\nfromText@t.js:4\n"); + assert_eq!( + short_stack(&r[1]), + "[caller.js]\n[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n", + "the first line names the run that is calling, not the one that defined the function" + ); + assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[caller.js]\n[global]@caller.js:3\nfromText@t.js:4\n"); assert_eq!(call(&mut s, "vc.log(eval('\\n\\n$.line'));"), 3); - assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[global]@caller.js:3\n[global]@[eval]:2\n"); + assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[caller.js]\n[global]@caller.js:3\n[global]@[eval]:2\n"); let r = call(&mut s, "vc.log(new Function('\\nreturn $.stack;')());"); - assert_eq!(r, "[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles"); + assert_eq!(r, "[caller.js]\n[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles"); // A map larger than the budget is not kept. TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1))); let lost = run(&mut s, "#targetengine e\n\n\nfunction lost() {\n return [$.line, $.stack];\n}"); let r = lost.map(|_| call(&mut s, "vc.log(lost());")); TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); let r = r.unwrap(); - assert_eq!(r, json!([0, "[global]@caller.js:3\nlost@[unknown]:0\n"])); + assert_eq!(r, json!([0, "[caller.js]\n[global]@caller.js:3\nlost@[unknown]:0\n"])); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index cc6756c332..78b0065b46 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -521,12 +521,15 @@ fn script_included_error_has_local_file_and_line() { let _ = std::fs::remove_dir_all(base); } -/// `$.stack`'s text with each frame's file cut to its name: `function@name:line` a line. +/// `$.stack`'s text with each frame's file cut to its name. The first line is the run's name +/// (`[script name]`) and is kept as written; each line after it is `function@name:line`. pub(crate) fn short_stack(stack: &Value) -> String { let stack = stack.as_str().unwrap_or_else(|| panic!("a stack: {stack}")); stack .lines() - .map(|frame| match (frame.split_once('@'), frame.rsplit_once(':')) { + .enumerate() + .map(|(i, frame)| match (frame.split_once('@'), frame.rsplit_once(':')) { + _ if i == 0 => format!("{frame}\n"), (Some((name, _)), Some((place, line))) => { let file = place.split_once('@').map_or(place, |(_, f)| f).rsplit(['/', '\\']).next().unwrap_or_default(); format!("{name}@{file}:{line}\n") @@ -554,12 +557,12 @@ fn script_line_and_stack_are_at_the_line_of_each_file() { let log = run(&base, text).unwrap()["log"].clone(); assert_eq!(log[0], json!([5, 3, 4]), "{log}"); assert_eq!(log[1][0], 3, "{log}"); - assert_eq!(short_stack(&log[1][1]), "[global]@main.jsx:6\nlibWhere@lib.jsxinc:3\n"); - assert_eq!(short_stack(&log[2]), "[global]@main.jsx:7\ndeepStack@deep.jsxinc:5\n"); + assert_eq!(short_stack(&log[1][1]), "[main.jsx]\n[global]@main.jsx:6\nlibWhere@lib.jsxinc:3\n"); + assert_eq!(short_stack(&log[2]), "[main.jsx]\n[global]@main.jsx:7\ndeepStack@deep.jsxinc:5\n"); assert_eq!(log[3][0], 4, "{log}"); - assert_eq!(short_stack(&log[3][1]), "[global]@main.jsx:8\n[global]@ev.jsx:5\nevWhere@ev.jsx:3\nincWhere@inc.jsxinc:4\n"); + assert_eq!(short_stack(&log[3][1]), "[main.jsx]\n[global]@main.jsx:8\n[global]@ev.jsx:5\nevWhere@ev.jsx:3\nincWhere@inc.jsxinc:4\n"); // The file a frame names is the one `$.fileName` gives while that file runs. - let log = run(&base, "vc.log($.stack.slice(9, -3) === $.fileName);").unwrap()["log"].clone(); + let log = run(&base, "vc.log($.stack.split('\\n')[1].slice(9, -2) === $.fileName);").unwrap()["log"].clone(); assert_eq!(log, json!([true])); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..3c58fc64a1 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -410,12 +410,16 @@ const STACK_FRAMES: usize = 64; const STACK_NAME_UNITS: usize = 64; /// The script's frames, outermost first, one a line: the function's name and the line it is at, -/// as `name:line`, or as `name@file:line` with the file the realm's locator names. +/// as `name:line`, or as `name@file:line` with the file the realm's locator names. A first line +/// `[script]` names the running script when the realm has its name. fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let frames: Vec<(Rc, usize, bool)> = interp.script_frames().map(|(c, pc, f)| (c.clone(), pc, f)).collect(); let skip = frames.len().saturating_sub(STACK_FRAMES); let locator = interp.locator.clone(); let mut text = String::new(); + if let Some(script) = &interp.script_name { + text.push_str(&format!("[{script}]\n")); + } if skip > 0 { text.push_str("…\n"); } diff --git a/crates/js/src/extension_tests.rs b/crates/js/src/extension_tests.rs index 4807856bf5..045ec94d87 100644 --- a/crates/js/src/extension_tests.rs +++ b/crates/js/src/extension_tests.rs @@ -245,6 +245,21 @@ fn the_line_and_the_stack_give_the_place_the_source_locator_maps_each_frame_to() assert_eq!(text(&mut r, deep), format!("66,…,d@f{tag}:101"), "the frames past 64 are still left out"); } +#[test] +fn the_stack_starts_with_the_name_of_the_script() { + let mut r = realm(); + let items = [("stack".to_string(), HostItem::Script(ScriptItem::Stack))].into_iter().collect(); + r.define_host_object("h", items).unwrap(); + r.set_script_name(Some("Marks.jsx".to_string())); + assert_eq!(text(&mut r, "h.stack"), "[Marks.jsx]\n[global]:1\n"); + let source = "function outer() {\n return h.stack;\n}\nouter()"; + assert_eq!(text(&mut r, source), "[Marks.jsx]\n[global]:4\nouter:2\n", "in a function too"); + let deep = "function d(n) { return n ? d(n - 1) : h.stack; } var s = d(100).split('\\n'); s.length + ',' + s[0] + ',' + s[1]"; + assert_eq!(text(&mut r, deep), "67,[Marks.jsx],…", "the name comes before the line for the frames left out"); + r.set_script_name(None); + assert_eq!(text(&mut r, "h.stack"), "[global]:1\n"); +} + #[test] fn a_host_property_reads_its_getter_and_gives_assignments_to_its_setter() { let mut r = Realm::new(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..f52c9e88f2 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -169,7 +169,9 @@ pub enum ScriptItem { Line, /// The running frames of the script's code, outermost first, one a line as `name:line`: the /// global code is `[global]` and a function without a name `[anonymous]`. At most 64 frames - /// are listed, the innermost ones, after a line `…` when some are left out. + /// are listed, the innermost ones, after a line `…` when some are left out. A first line + /// `[name]` names the running script when the realm has its name + /// ([`crate::Realm::set_script_name`]). Stack, } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0c5ba55e84..e51ce7ed73 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -315,6 +315,8 @@ pub(crate) struct Interp { pub(crate) error_tag: u32, /// Where `$.line` and `$.stack` find the file and line of a compiled line. pub(crate) locator: Option, + /// The name of the running script, which `$.stack` writes as its first line. + pub(crate) script_name: Option, /// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is /// propagating. pub(crate) thrown_mark: Option, @@ -583,6 +585,7 @@ impl Interp { code_observer: None, error_tag: crate::realm::UNKNOWN_SOURCE, locator: None, + script_name: None, thrown_mark: None, finally_marks: Vec::new(), finally_sites: Vec::new(), diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 3ec71080bd..bd9f812256 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -445,6 +445,12 @@ impl Realm { self.interp.locator = Some(locate); } + /// Has `$.stack` start with a line `[name]` that names the running script, before its frames; + /// `None` leaves the line out. + pub fn set_script_name(&mut self, name: Option) { + self.interp.script_name = name; + } + /// Which source the last error's `line` and `column` are in: 0 for the script last given to /// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which diff --git a/docs/mcp.md b/docs/mcp.md index 31faae1cd9..5d8f6679bd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2725,7 +2725,7 @@ VectorCraft's own, and `vc.api.has("dollar")` is true where they are available: | `global` | the global object | | `hiresTimer` | the microseconds since the run last read it, or since the run started; `0` on the web | | `level`, `memCache` | `0`; setting `memCache` throws | -| `line`, `stack` | `$.line` is the line of the code that reads it, counted in the file that code is in (the script, a file it included or a file `$.evalFile` ran, in this run or an earlier run of its named engine). `$.stack` lists the running code, outermost first, one frame a line as `name@file:line`: `name` is `[global]` for code outside a function (in the script, in a file it included, or in code that `$.evalFile` or `eval` ran) and `[anonymous]` for a function without a name, and `file` and `line` are the file and line that code is in, so `file` is the file `$.fileName` gives in that code. It lists the innermost 64 frames; when there are more, a first line `…` stands for the ones left out. In code from a script given as `source`, `file` is that run's name, while `$.fileName` is empty. Code that `eval` or `Function` compiled keeps the line of the source they compiled, in the file `[eval]`, while `$.fileName` there is the file being run; code whose place a named engine no longer keeps is at line `0` of `[unknown]`, and `$.fileName` there is empty | +| `line`, `stack` | `$.line` is the line of the code that reads it, counted in the file that code is in (the script, a file it included or a file `$.evalFile` ran, in this run or an earlier run of its named engine). `$.stack` starts with a line that holds the run's name in square brackets, as the console shows that name (for example `[main.jsx]`: the `name` given to `script.run`, else the `#script` name, else the file's name, else `script`); the running code follows, outermost first, one frame a line as `name@file:line`: `name` is `[global]` for code outside a function (in the script, in a file it included, or in code that `$.evalFile` or `eval` ran) and `[anonymous]` for a function without a name, and `file` and `line` are the file and line that code is in, so `file` is the file `$.fileName` gives in that code. It lists the innermost 64 frames; when there are more, a line `…` after the name stands for the ones left out. In code from a script given as `source`, `file` is that run's name, while `$.fileName` is empty. Code that `eval` or `Function` compiled keeps the line of the source they compiled, in the file `[eval]`, while `$.fileName` there is the file being run; code whose place a named engine no longer keeps is at line `0` of `[unknown]`, and `$.fileName` there is empty | | `locale` | the interface's language as a locale such as `de` or `pt_BR` (`en` when the interface follows the system); a script can set `ll` or `ll_RR`, and `null` or `""` sets the interface's again | | `localize` | `false`; while `true`, `String(object)` of a localization object gives its text for `$.locale` | | `os` | `Windows`, `macOS`, `Linux`, `FreeBSD`, `Unix` or `Web`, without a version | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c432e26097..0c76488b3d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1045,7 +1045,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. + - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` starts with a line holding the run's name in square brackets, such as `[main.jsx]`, then writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files, and read the files linked as the next line says; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`.