mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 02:03:02 +00:00
Scripts: the status bar shows text a script throws as it is
A failed run's status translated a script's own thrown text whenever it
matched one of the app's messages, so `throw new Error('invalid array
length')` read as the app's translated error. Run errors now say whether
their message is the script's own text: errors the interpreter or a host
function throws are marked when they are made, stay the app's own when a
script catches and rethrows them unchanged, and become the script's text
when it changes their name or message. The status bar translates the
words around such a message and shows the script's text unchanged.
- `script.run`'s failed report adds `messageOrigin` (`script` or
`built-in`); `message`, `kind` and the console line are unchanged.
- The advice about other applications' objects follows only the app's
own reference errors, not the same text thrown by a script.
This commit is contained in:
@@ -1476,12 +1476,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()
|
||||
@@ -1499,7 +1501,7 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
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,
|
||||
@@ -1508,20 +1510,20 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<st
|
||||
let map = |m: &include::SourceMap| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column }, index, file)
|
||||
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
|
||||
};
|
||||
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
|
||||
// file's place.
|
||||
if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line, column }, Some(file));
|
||||
return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file));
|
||||
}
|
||||
if e.line == 0 {
|
||||
return (e.clone(), None);
|
||||
}
|
||||
// An error in code from a source whose map is not at hand, such as code that `eval` compiled,
|
||||
// is given without a place.
|
||||
let unplaced = || (RunError { kind: e.kind.clone(), message: e.message.clone(), line: 0, column: 0 }, None);
|
||||
let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None);
|
||||
match realm.error_source() {
|
||||
0 => {
|
||||
let (e, index, file) = map(&host.script_map.borrow());
|
||||
@@ -1694,6 +1696,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 {
|
||||
@@ -1764,7 +1775,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
|
||||
}
|
||||
@@ -1986,14 +1997,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)),
|
||||
@@ -2006,7 +2017,7 @@ impl Session {
|
||||
let n = job.host.dialogs.unused();
|
||||
let kind = LimitKind::Host;
|
||||
let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" });
|
||||
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);
|
||||
@@ -2050,7 +2061,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);
|
||||
}
|
||||
}
|
||||
@@ -2153,7 +2164,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,
|
||||
@@ -2245,6 +2257,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() {
|
||||
@@ -2259,7 +2277,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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -318,7 +318,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)?;
|
||||
|
||||
@@ -213,7 +213,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<u64>),
|
||||
Arguments(Box<ArgMap>),
|
||||
/// A `Boolean` object made by ToObject, with its primitive value.
|
||||
Boolean(bool),
|
||||
@@ -311,7 +313,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",
|
||||
|
||||
+45
-3
@@ -48,6 +48,14 @@ fn internal<T>(message: &str) -> JsResult<T> {
|
||||
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 {
|
||||
@@ -498,15 +521,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 {
|
||||
@@ -770,7 +812,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();
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_functions_receive_arguments_and_return_values() {
|
||||
let mut realm = Realm::new();
|
||||
|
||||
+29
-10
@@ -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<SyntaxError> 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);
|
||||
@@ -268,7 +272,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 }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,15 +295,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 }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,10 +328,16 @@ impl Realm {
|
||||
pub fn advance(&mut self, slice: u64) -> Result<Progress, RunError> {
|
||||
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);
|
||||
@@ -380,7 +393,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.
|
||||
|
||||
@@ -237,7 +237,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()));
|
||||
@@ -245,6 +245,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;
|
||||
|
||||
|
||||
@@ -491,6 +491,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.
|
||||
|
||||
@@ -765,6 +765,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)
|
||||
|
||||
@@ -3252,6 +3252,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
|
||||
|
||||
+4
-2
@@ -2374,8 +2374,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.
|
||||
|
||||
@@ -827,6 +827,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`.
|
||||
|
||||
Reference in New Issue
Block a user