diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0dd9a46b6b..14618a6108 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1559,12 +1559,14 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { } } -/// `message`, with what to do about a failure that comes from a script written for another program. -fn explained(kind: &RunErrorKind, message: &str) -> String { +/// `e`'s message, with what to do about a failure that comes from a script written for another +/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. +fn explained(e: &RunError) -> String { const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; + let message = &e.message; let names_host_object = message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); - if *kind == RunErrorKind::Thrown && names_host_object { + if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { message.to_string() @@ -1582,7 +1584,7 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { include::FailKind::Limit => (RunErrorKind::Limit(LimitKind::Host), f.message), }; let file = (f.index > 0).then_some(f.file); - (RunError { kind, message, line: f.line, column: f.column }, file) + (RunError { kind, message, line: f.line, column: f.column, authored: false }, file) } /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, @@ -1591,20 +1593,20 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let (e, index, file) = map(&host.script_map.borrow()); @@ -1777,6 +1779,15 @@ impl Session { self.script_report.as_ref().filter(|r| r["ok"] == false).map(failure_text) } + /// [`Self::script_failure_text`] split around the message when that message is text the script + /// supplied itself (`messageOrigin` `script`): the text before it, the message and the text after + /// it. `None` when the last run did not fail, or failed with one of the app's own errors. + pub fn script_authored_failure(&self) -> Option<(String, &str, String)> { + let r = self.script_report.as_ref().filter(|r| r["ok"] == false && r["messageOrigin"] == "script")?; + let (before, after) = failure_frame(r); + Some((before, r["message"].as_str().unwrap_or_default(), after)) + } + /// Has the running script used up its growth allowance, so a person must answer? A run asked /// to stop no longer waits: the next [`Session::script_pump`] ends it. pub fn script_waiting(&self) -> bool { @@ -1873,7 +1884,7 @@ impl Session { }; drop(key); let kind = LimitKind::Interrupted; - let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; let _ = self.script_failed(job, &e); true } @@ -2120,14 +2131,14 @@ impl Session { // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. if job.realm.waits() { let kind = LimitKind::Interrupted; - let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; return Some(self.script_failed(job, &e)); } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); match outcome { Err(panic) => { - let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false }; Some(self.script_failed(job, &e)) } Ok(Err(e)) => Some(self.script_failed(job, &e)), @@ -2144,7 +2155,7 @@ impl Session { } else { format!("`answers` has {n} answers the script did not use") }; - Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 })) + Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false })) } Ok(Ok(Progress::Done(_))) => { let r = self.script_commit(job); @@ -2197,7 +2208,7 @@ impl Session { if changed && (!crate::sanity::doc_sane(&st.doc, &st.selection) || st.doc.too_deep(None)) { job.world.docs = start; job.world.swap(self); - let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0, authored: false }; return self.script_failed(job, &e); } } @@ -2302,7 +2313,8 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue let mut report = json!({ "ok": false, "kind": kind_id(&e.kind), - "message": explained(&e.kind, &e.message), + "message": explained(e), + "messageOrigin": if e.authored { "script" } else { "built-in" }, "name": name, "line": e.line, "column": e.column, @@ -2395,6 +2407,12 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: /// The text of a failed run's error. fn failure_text(report: &Value) -> String { + let (before, after) = failure_frame(report); + format!("{before}{}{after}", report["message"].as_str().unwrap_or_default()) +} + +/// The text of a failed run's error before its message and after it. +fn failure_frame(report: &Value) -> (String, String) { let s = |k: &str| report[k].as_str().unwrap_or_default(); let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); let at = match report["file"].as_str() { @@ -2409,7 +2427,7 @@ fn failure_text(report: &Value) -> String { } else { String::new() }; - format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind")) + (format!("{}{at}: ", s("name")), format!(" ({}){kept}", s("kind"))) } /// A run's slice: the working copy in, the real session lent to the host functions, one measured diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 1ad659cfdd..cc6756c332 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -77,6 +77,31 @@ fn script_missing_include_reports_origin() { assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}"); assert_eq!(report["log"], json!([]), "nothing ran before the include was read"); assert!(report.get("file").is_none(), "the line is the script's own"); + assert_eq!(report["messageOrigin"], "built-in"); + let _ = std::fs::remove_dir_all(base); +} + +/// An error in an included file keeps where its message came from: a value the file threw is the +/// script's own text, and an error the app raised for it, or for a file `$.evalFile` could not run, is not. +#[test] +fn script_include_errors_keep_their_message_origin() { + let base = folder("origin"); + write(&base.join("main/lib.jsxinc"), "var a = 1;\n throw new RangeError('invalid array length');"); + write(&base.join("main/native.jsxinc"), "var a = 1;\n new Array(-1);"); + for (text, message, origin) in [ + ("#include \"lib.jsxinc\"", "RangeError: invalid array length", "script"), + ("#include \"native.jsxinc\"", "RangeError: invalid array length", "built-in"), + ("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e; }", "RangeError: invalid array length", "built-in"), + ("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e.message; }", "invalid array length", "script"), + ] { + let report = failed(&base, text); + assert_eq!((report["message"].as_str(), report["messageOrigin"].as_str()), (Some(message), Some(origin)), "{text}: {report}"); + } + let report = failed(&base, "#include \"lib.jsxinc\""); + let file = report["file"].as_str().map(|f| Path::new(f).ends_with("lib.jsxinc")); + assert_eq!((file, report["line"].as_u64(), report["column"].as_u64()), (Some(true), Some(2), Some(3)), "{report}"); + let report = failed(&base, "$.evalFile('nope.jsx');"); + assert_eq!(report["messageOrigin"], "built-in", "{report}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 50828e855c..bf8154f9a7 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -170,6 +170,58 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(s.script_report().unwrap()["line"], 1); } +/// A failed run's report keeps its message and kind and says where the message came from: text the +/// script supplied, or one of the app's own errors. The status text and the console line read the +/// same either way, and only the app's own errors get advice about other applications' objects. +#[test] +fn failed_script_report_keeps_message_and_adds_origin() { + let mut s = two_docs(); + for (source, kind, message, origin) in [ + ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), + ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), + ("throw 'invalid array length';", "thrown", "invalid array length", "script"), + ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), + ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), + ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), + ("vc.run();", "thrown", "TypeError: vc.run: give a command id, as a string", "built-in"), + ] { + let e = run(&mut s, source).unwrap_err().to_string(); + let report = s.script_report().unwrap().clone(); + assert_eq!( + (report["kind"].as_str(), report["message"].as_str(), report["messageOrigin"].as_str()), + (Some(kind), Some(message), Some(origin)), + "{source}" + ); + let (line, column) = (&report["line"], &report["column"]); + let before = format!("t.js: line {line}, column {column}: "); + assert_eq!(e, format!("{before}{message} ({kind})"), "{source}"); + assert_eq!(s.script_failure_text().as_deref(), Some(e.as_str())); + let authored = s.script_authored_failure(); + assert_eq!(authored, (origin == "script").then(|| (before.clone(), message, format!(" ({kind})"))), "{source}"); + let console = s.execute("script.console", &json!({})).unwrap(); + let error = console["lines"].as_array().unwrap().iter().rev().find(|l| l["kind"] == "error").map(|l| l["text"].clone()); + assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); + } + // The app's own reference error names the `vc` object; the same text a script threw does not. + run(&mut s, "app.activeDocument;").unwrap_err(); + assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); + assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); + // An error in code `eval` compiled keeps where its message came from. + let e = run(&mut s, "eval(\"throw new Error('invalid array length')\");").unwrap_err().to_string(); + assert_eq!(e, "t.js: Error: invalid array length (thrown)"); + assert_eq!(s.script_authored_failure(), Some(("t.js: ".to_string(), "Error: invalid array length", " (thrown)".to_string()))); + // Syntax errors and limits are the app's own. + run(&mut s, "var = 1;").unwrap_err(); + assert_eq!((s.script_report().unwrap()["kind"].as_str(), s.script_authored_failure()), (Some("syntax"), None)); + s.execute("script.run", &json!({"source": "while (true) {}", "name": "t.js", "maxFuel": 100_000})).unwrap_err(); + assert_eq!((s.script_report().unwrap()["messageOrigin"].as_str(), s.script_authored_failure()), (Some("built-in"), None)); + // A run that completes has no failure to split. + run(&mut s, "throw 'x';").unwrap_err(); + run(&mut s, "1").unwrap(); + assert_eq!(s.script_authored_failure(), None); +} + /// An error raised where the run has no place for it, such as in code `eval` compiled, is named /// with the script and its kind alone, with one colon after the script's name. #[test] diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 98327a2b61..380d161ecf 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -327,7 +327,7 @@ fn install_errors(interp: &mut Interp, object_proto: ObjId) -> JsResult<()> { for (i, (name, f)) in kinds.into_iter().enumerate() { // Error.prototype and each NativeError prototype are Error objects (sections 15.11.4 and // 15.11.7.7). - let proto = alloc(interp, Class::Error, Some(if i == 0 { object_proto } else { error_proto })); + let proto = alloc(interp, Class::Error(None), Some(if i == 0 { object_proto } else { error_proto })); if i == 0 { error_proto = proto; method(interp, proto, "toString", error_to_string, 0)?; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 3b96953e8d..f612b00138 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,7 +215,9 @@ pub(crate) enum Class { length_writable: bool, }, Function(Func), - Error, + /// An error object. One the interpreter threw itself holds a hash of the description it had + /// then ([`crate::interp::Interp::describe`]); one a script made holds `None`. + Error(Option), Arguments(Box), /// A `Boolean` object made by ToObject, with its primitive value. Boolean(bool), @@ -313,7 +315,7 @@ impl Class { Class::Ordinary | Class::ForIn(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", - Class::Error => "Error", + Class::Error(_) => "Error", Class::Arguments(_) => "Arguments", Class::Boolean(_) => "Boolean", Class::Number(_) => "Number", diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index d81e12f3ac..24c33d2fc5 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -48,6 +48,14 @@ fn internal(message: &str) -> JsResult { Err(Abrupt::Internal(message.into())) } +/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]). +fn description_hash(text: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + text.hash(&mut h); + h.finish() +} + /// The kinds of error object the engine throws. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ErrorType { @@ -60,6 +68,21 @@ pub(crate) enum ErrorType { Uri, } +impl ErrorType { + /// The `name` the prototype of this kind of error has before a script changes it. + pub(crate) fn name(self) -> &'static str { + match self { + ErrorType::Error => "Error", + ErrorType::Eval => "EvalError", + ErrorType::Range => "RangeError", + ErrorType::Reference => "ReferenceError", + ErrorType::Syntax => "SyntaxError", + ErrorType::Type => "TypeError", + ErrorType::Uri => "URIError", + } + } +} + /// The objects the interpreter itself refers to. #[derive(Clone, Copy, Debug)] pub(crate) struct Intrinsics { @@ -538,15 +561,34 @@ impl Interp { pub(crate) fn error_object(&mut self, t: ErrorType, message: &str) -> ObjId { let proto = self.intrinsics.error_proto(t); - let mut o = Object::new(Class::Error, Some(proto)); + let mut o = Object::new(Class::Error(None), Some(proto)); if !message.is_empty() { o.props.insert(key("message"), Prop::Data { value: Value::str(message), flags: HIDDEN }); } self.heap.alloc_object(o) } + /// An error of the interpreter's or a host function's own, marked as such with a hash of the + /// description it has with its kind's own name ([`Self::thrown_by_script`]), so a name a script + /// gave the kind's prototype before the error was made counts as the script's text. pub(crate) fn throw(&mut self, t: ErrorType, message: &str) -> Abrupt { - Abrupt::Throw(Value::Object(self.error_object(t, message))) + let o = self.error_object(t, message); + let own = if message.is_empty() { t.name().to_string() } else { format!("{}: {message}", t.name()) }; + if let Some(object) = self.heap.object_mut(o) { + object.class = Class::Error(Some(description_hash(&own))); + } + Abrupt::Throw(Value::Object(o)) + } + + /// Is the text [`Self::describe`] gives for the thrown value `v` the script's own? It is unless + /// `v` is an error the interpreter or a host function threw, with its name and message as they + /// were then: a value the script threw, an error it made, and an error whose name or message it + /// changed all hold its own text. + pub(crate) fn thrown_by_script(&mut self, v: &Value) -> bool { + let Value::Object(o) = v else { return true }; + let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true }; + let hash = *hash; + description_hash(&self.describe(v)) != hash } pub(crate) fn type_error(&mut self, message: &str) -> Abrupt { @@ -819,7 +861,7 @@ impl Interp { let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed && let Value::Object(o) = v - && self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error)) + && self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error(_))) { self.last_error = v.clone(); } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 9f9c59a96f..bfe358bc20 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -239,6 +239,44 @@ fn errors_carry_line_and_column() { assert_eq!(e.message, "42"); } +/// A run error says whether its message is the script's own text, whatever that text reads: an +/// error the interpreter or a host function threw is not, even when a script caught it and threw +/// it again, and a value or error the script made, or an error whose name or message it changed, +/// is. +#[test] +fn script_error_origin_distinguishes_native_and_authored_values() { + let native = "RangeError: invalid array length"; + for (src, message, authored) in [ + ("new Array(-1)", native, false), + ("try { new Array(-1); } catch (e) { throw e; }", native, false), + ("try { new Array(-1); } catch (e) { e.message = 'invalid array length'; throw e; }", native, false), + ("nope()", "ReferenceError: nope is not defined", false), + ("throw new RangeError('invalid array length')", native, true), + ("throw new Error('invalid array length')", "Error: invalid array length", true), + ("throw 'invalid array length'", "invalid array length", true), + ("throw 17", "17", true), + ("throw {}", "[object Object]", true), + ("throw new Error()", "Error", true), + ("try { new Array(-1); } catch (e) { throw e.message; }", "invalid array length", true), + ("try { new Array(-1); } catch (e) { throw new RangeError(e.message); }", native, true), + ("try { new Array(-1); } catch (e) { e.message = 'mine'; throw e; }", "RangeError: mine", true), + ("try { nope(); } catch (e) { e.name = 'TypeError'; throw e; }", "TypeError: nope is not defined", true), + ("try { new Array(-1); } catch (e) { RangeError.prototype.name = 'Mine'; throw e; }", "Mine: invalid array length", true), + ("RangeError.prototype.name = 'Mine'; new Array(-1)", "Mine: invalid array length", true), + ("RangeError.prototype.name = 'RangeError'; new Array(-1)", native, false), + ] { + let e = fail(src); + assert_eq!((e.kind, e.message.as_str(), e.authored), (RunErrorKind::Thrown, message, authored), "{src}"); + } + assert!(!fail("var x = ;").authored, "a syntax error"); + let mut realm = Realm::new(); + realm.define_function("add", |_| Err("add takes two numbers".into())); + let e = realm.run("add()").unwrap_err(); + assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", false), "a host function's error"); + let e = realm.run("throw new Error('add takes two numbers')").unwrap_err(); + assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", true)); +} + /// An error about a property of `null` or `undefined` names a computed property whose name is a /// primitive, and says whether the script read or set it, never naming an empty property; a /// member assignment, an object key and a long name leave the name out. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 0a1006a23c..d675e82ec7 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -139,6 +139,10 @@ pub struct RunError { pub message: String, pub line: u32, pub column: u32, + /// `message` is text the script supplied: a value it threw, or an error object it made or whose + /// name or message it changed. False for the interpreter's and host functions' own errors, + /// syntax errors and limits, even when a script caught one and threw it again. + pub authored: bool, } impl std::fmt::Display for RunError { @@ -151,7 +155,7 @@ impl std::error::Error for RunError {} impl From for RunError { fn from(e: SyntaxError) -> Self { - RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column } + RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column, authored: false } } } @@ -241,7 +245,7 @@ impl Realm { self.script_tag = UNKNOWN_SOURCE; let interp = &mut self.interp; if let Some(message) = &interp.install_error { - return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 }); + return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false }); } interp.fuel = interp.limits.fuel; interp.flattened_fuel.set(0); @@ -269,7 +273,7 @@ impl Realm { interp.error_tag = self.script_tag; Err(e.into()) } - Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), + Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }), } } @@ -293,15 +297,18 @@ impl Realm { Ok(v) => Ok(interp.to_js_value(&v)), Err(Abrupt::Throw(v)) => { let message = interp.describe(&v); + let authored = interp.thrown_by_script(&v); interp.last_thrown = v; - Err(RunError { kind: RunErrorKind::Thrown, message, line, column }) + Err(RunError { kind: RunErrorKind::Thrown, message, line, column, authored }) } Err(Abrupt::Limit(LimitKind::Host)) => { let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); - Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column }) + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false }) } - Err(Abrupt::Limit(kind)) => Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column }), - Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column }), + Err(Abrupt::Limit(kind)) => { + Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false }) + } + Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column, authored: false }), } } @@ -323,10 +330,16 @@ impl Realm { pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; if interp.frames.is_empty() { - return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 }); + return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false }); } if interp.waiting { - return Err(RunError { kind: RunErrorKind::Internal, message: "the run waits for a host function's result".into(), line: 0, column: 0 }); + return Err(RunError { + kind: RunErrorKind::Internal, + message: "the run waits for a host function's result".into(), + line: 0, + column: 0, + authored: false, + }); } let total = interp.fuel; let cap = slice.saturating_add(self.unbroken_fuel).min(total); @@ -384,7 +397,13 @@ impl Realm { pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; if !interp.waiting { - return Err(RunError { kind: RunErrorKind::Internal, message: "no host function waits for a result".into(), line: 0, column: 0 }); + return Err(RunError { + kind: RunErrorKind::Internal, + message: "no host function waits for a result".into(), + line: 0, + column: 0, + authored: false, + }); } interp.waiting = false; // The value on top of the stack stood in for the result. diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 45cd600771..7c39666f78 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -401,7 +401,7 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { let more = busy.len() - 1; (if more > 0 { format!("{label}… (+{more})") } else { format!("{label}…") }, &[][..]) } else { - (crate::i18n::msg(&app.ui.status), status_notes(&app.ui)) + (status_message(app), status_notes(&app.ui)) }; if !message.is_empty() { let rect = egui::Rect::from_min_max(egui::pos2((area.left() + 18.0).min(right), area.top()), egui::pos2(right, area.bottom())); @@ -409,6 +409,19 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { } } +/// The status message in the interface language. While it is the error of the last script run +/// and that error's message is text the script supplied, that text is shown as it is and only the +/// words around it are translated. +pub(crate) fn status_message(app: &VectorcraftApp) -> String { + let status = app.ui.status.as_str(); + if let Some((before, kept, after)) = app.session.script_authored_failure() + && status.strip_prefix(before.as_str()).and_then(|rest| rest.strip_suffix(after.as_str())) == Some(kept) + { + return crate::i18n::msg_keeping(&before, kept, &after); + } + crate::i18n::msg(status) +} + /// Most notes the status message's hover and access information list. const MAX_LISTED_NOTES: usize = 30; diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 09d31f1a5f..629e6a0ef0 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -899,6 +899,59 @@ fn the_message_of_an_open_with_several_notes_lists_them_on_hover() { assert_eq!(hovered.iter().filter(|t| t.text.starts_with("Opened")).count(), 1, "no tooltip: {hovered:?}"); } +/// The status message of a failed script run shows text the script threw as it is, even when it +/// reads like one of the app's own errors, and translates the words around it; the app's own error +/// is translated. Both a run that ends in one call and a run the frames take to its end show it. +#[test] +fn german_script_status_preserves_authored_error_and_translates_native_error() { + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let failed = |app: &mut crate::VectorcraftApp, source: &str, frames: bool| { + app.session.script_frames = frames; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})); + if frames { + assert_eq!(r.map(|v| v["running"].clone()), Ok(json!(true)), "{source}"); + for _ in 0..1_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(app); + } + } else { + assert!(r.is_err(), "{source}"); + } + assert!(!app.session.script_running()); + super::status_bar::status_message(app) + }; + let long = "invalid array length ".repeat(120); + for frames in [false, true] { + let shown = failed(&mut app, "throw new Error('invalid array length')", frames); + assert_eq!(shown, "t.js: Zeile 1, Spalte 1: Error: invalid array length (ausgelöst)"); + let shown = failed(&mut app, "throw 'invalid array length'", frames); + assert_eq!(shown, "t.js: Zeile 1, Spalte 1: invalid array length (ausgelöst)"); + let shown = failed(&mut app, "new Array(-1)", frames); + assert!(shown.starts_with("t.js: Zeile 1, Spalte 1: ") && shown.contains("ungültige Array-Länge"), "{shown}"); + for text in ["", "invalid array length\nsecond line", "{name}: {e}", "t.js: line 1, column 1: invalid array length (thrown)", long.as_str()] { + let source = format!("throw {}", serde_json::to_string(text).unwrap()); + assert_eq!(failed(&mut app, &source, frames), format!("t.js: Zeile 1, Spalte 1: {text} (ausgelöst)"), "{text}"); + } + } + // Another message, even one spelled like the script's text, is translated as before. + failed(&mut app, "throw 'invalid array length'", false); + app.ui.status = "invalid array length".to_string(); + assert_eq!(super::status_bar::status_message(&app), "ungültige Array-Länge"); + // A change of language while the message stays keeps the script's text. + failed(&mut app, "throw new Error('invalid array length')", false); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered")); + assert_eq!(super::status_bar::status_message(&app), "t.js : ligne 1, colonne 1 : Error: invalid array length (levée)"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(super::status_bar::status_message(&app), app.ui.status); + // After a run that completes, the message is an ordinary one. + app.session.script_frames = false; + app.run("script.run", json!({"source": "1", "name": "t.js"})).unwrap(); + assert_eq!(app.session.script_authored_failure(), None); +} + /// The message of an open that starts with a line about its linked files lists the open's notes on /// hover and for screen readers, in a wide and in a narrow window. A later message leaves the list /// out. diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index b8b8804542..eb9a7b10ec 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -934,6 +934,35 @@ pub fn msg(s: &str) -> String { out } +/// Stands in for the value [`message_keeping`] shows as it is while the text around it is +/// translated. +const KEPT_VALUE: char = '\u{FFFC}'; + +/// The message `before`, `kept` and `after` make, with `before` and `after` translated as +/// [`message`] translates a message and `kept` (such as text a script threw) shown as it is, even +/// when it reads like a message that has a translation. When the translation does not hold the +/// place of `kept` exactly once, the message is shown in English. +pub fn message_keeping(lang: Lang, before: &str, kept: &str, after: &str) -> String { + keeping(|s| message(lang, s), before, kept, after) +} + +/// [`message_keeping`] in the current language, remembering the last translation as [`msg`] does. +pub fn msg_keeping(before: &str, kept: &str, after: &str) -> String { + keeping(msg, before, kept, after) +} + +fn keeping(translate: impl Fn(&str) -> String, before: &str, kept: &str, after: &str) -> String { + let english = || format!("{before}{kept}{after}"); + if before.contains(KEPT_VALUE) || after.contains(KEPT_VALUE) { + return english(); + } + let shown = translate(&format!("{before}{KEPT_VALUE}{after}")); + match shown.split_once(KEPT_VALUE) { + Some((head, tail)) if !tail.contains(KEPT_VALUE) => format!("{head}{kept}{tail}"), + _ => english(), + } +} + /// [`trn`] in the current language. pub fn tn(n: u64, one: &str, other: &str) -> String { trn(current(), n, one, other) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 693f7df849..79c7b4b7c3 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -4733,6 +4733,21 @@ fn script_errors_are_translated() { } } +/// A message with a value kept as it is translates the words around the value and shows the value +/// unchanged, whatever it reads like; when the words around it cannot hold its place once, the +/// message stays English. +#[test] +fn a_kept_value_is_shown_as_it_is_in_a_translated_message() { + let de = Lang::from_code("de").expect("registered"); + let (before, after) = ("t.js: line 1, column 1: ", " (thrown)"); + for kept in ["invalid array length", "", "{e}", "\u{FFFC}", "a\nb", "t.js: line 1, column 1: x (thrown)"] { + assert_eq!(message_keeping(de, before, kept, after), format!("t.js: Zeile 1, Spalte 1: {kept} (ausgelöst)"), "{kept:?}"); + } + assert_eq!(message_keeping(de, "t.js\u{FFFC}: line 1, column 1: ", "x", after), "t.js\u{FFFC}: line 1, column 1: x (thrown)"); + assert_eq!(message_keeping(de, "no such message ", "x", ""), "no such message x"); + assert_eq!(message_keeping(Lang::EN, before, "invalid array length", after), "t.js: line 1, column 1: invalid array length (thrown)"); +} + /// The errors a script's `$` object, its `alert`, `confirm` and `prompt` dialogs, `vc.document`, /// `vc.log`, the methods of its `File` and `Folder` objects and a run's limits give, and the errors /// of the script engine commands, are translated in every language of [`COMPLETE_MESSAGES`], on diff --git a/docs/mcp.md b/docs/mcp.md index ab28dd2452..81b3a8cb28 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2692,8 +2692,10 @@ In the app, a script past the growth limit stops at a question to continue or to with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The -report of a failed run has the same fields after `kind`, `message`, `line`, `column`, `file` (when the error is in -another file than the script) and `fuelLeft`. +report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when +the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the +script supplied (a value it threw, or an error it made or whose name or message it changed) and `built-in` for the +app's own errors, syntax errors and limits. The status bar shows a `script` message as it is, untranslated. - `runTimeMs` is the time the script ran, its commands included. Waits between frames and for a person's answer are left out. `timingAvailable` is false on the web, where `runTimeMs` is 0. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 64f4871d3d..a672d6e8f4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -955,6 +955,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. + - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`.