mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
Merge pull request #10334 from dotCooCoo/fix/script-run-accounting
Scripts: list rebuilds count against the run, a stop is not masked, bad answers throw at the call
This commit is contained in:
11 files changed
+314
-57
No files matched your search
@@ -620,10 +620,12 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
}
|
||||
|
||||
/// The ids of a document's page items, topmost first, each group or compound path before the
|
||||
/// objects in it ([`State`] keeps the lists of the last documents read).
|
||||
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// objects in it ([`State`] keeps the lists of the last documents read). Building the list again,
|
||||
/// after an edit or for another document, counts against the run's host-call allowance as a list
|
||||
/// of that many objects does ([`list_charge`]).
|
||||
fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
|
||||
return ids;
|
||||
return Ok(ids);
|
||||
}
|
||||
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
|
||||
for n in nodes.iter().rev() {
|
||||
@@ -641,9 +643,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
}
|
||||
let mut ids = Vec::new();
|
||||
walk(&st.doc.layers, &mut ids);
|
||||
h.charge_call(list_charge(ids.len()))?;
|
||||
let ids = Rc::new(ids);
|
||||
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The bytes a list of `n` objects that a collection builds again counts against the run's
|
||||
/// host-call allowance, as the selection's list counts them ([`selection_of`]).
|
||||
pub(super) fn list_charge(n: usize) -> u64 {
|
||||
16u64.saturating_mul(n as u64)
|
||||
}
|
||||
|
||||
/// The objects directly in the layers and sublayers of a document: what deleting every page item
|
||||
@@ -901,8 +910,8 @@ fn on_doc_steps<T>(
|
||||
restored = restore_layer(h, uid, layer.0, &layer.1);
|
||||
}
|
||||
}
|
||||
// The document that was active is active again before any error is given: `f`'s error first,
|
||||
// then the selection's, then the switch back's.
|
||||
// The document that was active is active again before any error is given: an error that ends
|
||||
// the run first, then `f`'s error, then the selection's, then the switch back's.
|
||||
let back = match active {
|
||||
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
|
||||
_ => Ok(()),
|
||||
@@ -914,12 +923,35 @@ fn on_doc_steps<T>(
|
||||
{
|
||||
st.activated = activated;
|
||||
}
|
||||
first_error(r, restored, back)
|
||||
}
|
||||
|
||||
/// [`on_doc`]'s result from `f`'s result `r`, then putting back the selection and the layer
|
||||
/// (`restored`) and the active document (`back`): an error that ends the run first, since a
|
||||
/// script could catch `f`'s ordinary error, then the first error in that order.
|
||||
fn first_error<T>(
|
||||
r: std::result::Result<T, HostError>,
|
||||
restored: std::result::Result<(), HostError>,
|
||||
back: std::result::Result<(), HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
if !r.as_ref().is_err_and(ends_run) {
|
||||
restored.as_ref().err().into_iter().chain(back.as_ref().err()).find(|e| ends_run(e)).map_or(Ok(()), |e| Err(e.clone()))?;
|
||||
}
|
||||
let v = r?;
|
||||
restored?;
|
||||
back?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether `e` ends the run, so that a script cannot catch it.
|
||||
fn ends_run(e: &HostError) -> bool {
|
||||
match e {
|
||||
HostError::Abort(_) => true,
|
||||
HostError::Marked { error, .. } => ends_run(error),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
@@ -2081,7 +2113,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).len());
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
@@ -2122,7 +2154,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => Ok(item_at(h, doc, i)),
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
@@ -2133,8 +2165,8 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The object at position `i` of `pageItems`, or `undefined` past the end.
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
|
||||
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(page_items(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2146,7 +2178,7 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The first object of `pageItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
let ids = page_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -2158,7 +2190,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match position(*n).map(|i| item_at(h, doc, i)) {
|
||||
match position(*n).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
@@ -3178,6 +3210,24 @@ mod tests {
|
||||
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
|
||||
}
|
||||
|
||||
/// A stop from putting back the selection or the active document is not hidden by the edit's
|
||||
/// own error, which a script could catch; ordinary errors keep their order.
|
||||
#[test]
|
||||
fn an_edit_gives_a_stop_ahead_of_its_own_error() {
|
||||
let error = |m: &str| HostError::Error(m.into());
|
||||
let stop = || HostError::Abort("stop".into());
|
||||
let marked = || HostError::Marked { error: Box::new(stop()), mark: 0 };
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(stop()), Ok(())), Err(stop()));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Ok(()), Err(stop())), Err(stop()));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(marked())), Err(marked()));
|
||||
assert_eq!(first_error(Ok(1), Ok(()), Err(stop())), Err(stop()));
|
||||
// The edit's own stop comes first, and with no stop the edit's error does.
|
||||
assert_eq!(first_error::<()>(Err(HostError::Abort("edit".into())), Err(stop()), Ok(())), Err(HostError::Abort("edit".into())));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(error("back"))), Err(error("edit")));
|
||||
assert_eq!(first_error::<()>(Ok(()), Err(error("selection")), Err(error("back"))), Err(error("selection")));
|
||||
assert_eq!(first_error(Ok(1), Ok(()), Ok(())), Ok(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_item_lists_are_kept_for_several_documents() {
|
||||
let docs: Vec<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
|
||||
|
||||
@@ -367,16 +367,18 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
|
||||
// ---- Document.pathItems ----
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// The ids of a document's paths, in the order of its page items. Building the list again counts
|
||||
/// the page items it looks through against the run's host-call allowance.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
|
||||
return ids;
|
||||
return Ok(ids);
|
||||
}
|
||||
let all = super::page_items(h, st);
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Rc<Vec<NodeId>> =
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
|
||||
super::keep_list(&h.dom.paths, st, &ids);
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -396,7 +398,7 @@ fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -408,14 +410,14 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st);
|
||||
let ids = path_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -438,10 +440,10 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st);
|
||||
let ids = path_items(h, st)?;
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused)
|
||||
});
|
||||
Ok::<_, HostError>((ids, refused))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
|
||||
|
||||
@@ -74,7 +74,7 @@ fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> Control
|
||||
Ok(())
|
||||
}),
|
||||
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
let ids = page_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
for id in ids.iter() {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
|
||||
@@ -1233,18 +1233,21 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember {
|
||||
}
|
||||
|
||||
/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the
|
||||
/// document is unchanged.
|
||||
fn frame_ids(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// document is unchanged. Building the list again counts the page items it looks through against
|
||||
/// the run's host-call allowance.
|
||||
fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow()
|
||||
&& *uid == st.uid
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
return ids.clone();
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids: Vec<NodeId> = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
|
||||
let all = page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Vec<NodeId> = all.iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
|
||||
let ids = Rc::new(ids);
|
||||
*h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone()));
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
@@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
|
||||
fn frames_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -1265,14 +1268,14 @@ fn frames_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = frame_ids(h, st);
|
||||
let ids = frame_ids(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -1364,13 +1367,13 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = frame_ids(h, st);
|
||||
let ids = frame_ids(h, st)?;
|
||||
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused, on_locked)
|
||||
});
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
|
||||
|
||||
@@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostEr
|
||||
{
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids = frame_ids(h, st);
|
||||
let ids = frame_ids(h, st)?;
|
||||
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
|
||||
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
|
||||
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
|
||||
|
||||
@@ -2427,8 +2427,17 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() {
|
||||
assert_eq!(out[0][0].as_array().map(Vec::len), Some(3));
|
||||
// Each pass edits the document, so nothing kept from the last read can be reused.
|
||||
let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;";
|
||||
// The script's fuel, and the host's calls and the bytes they count, which hold the work the
|
||||
// host does for them: 64 KiB is less than one list of the large document's objects.
|
||||
let cost = |s: &mut Session| {
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
|
||||
let r = run(s, edits);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap_or_else(|e| panic!("the reads went over: {e}"));
|
||||
(r["fuelUsed"].as_u64().unwrap(), r["hostCalls"].as_u64().unwrap())
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap();
|
||||
let small = cost(&mut s);
|
||||
// 3 objects doubled 11 times: 6,144.
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
for _ in 0..11 {
|
||||
@@ -2436,11 +2445,39 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
|
||||
let large = run(&mut s, edits);
|
||||
assert_eq!(small, cost(&mut s));
|
||||
}
|
||||
|
||||
/// Building a collection's list again after an edit counts the objects it lists against the
|
||||
/// run's allowance, so a loop that edits and reads `pageItems`, `pathItems` or `textFrames` in a
|
||||
/// large document ends with the limit instead of walking the document each time for nothing.
|
||||
#[test]
|
||||
fn rebuilding_a_collection_after_an_edit_counts_against_the_run() {
|
||||
let (mut s, a, _) = doc();
|
||||
let source = |list: &str| {
|
||||
format!("var d = app.activeDocument, it = d.pageItems[0]; for (var i = 0; i < 40; i++) {{ it.opacity = 50 + i % 2; d.{list}.length; }}")
|
||||
};
|
||||
let lists = ["pageItems", "pathItems", "textFrames"];
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20)));
|
||||
let small: Vec<bool> = lists.iter().map(|l| run(&mut s, &source(l)).is_ok()).collect();
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap();
|
||||
assert_eq!(small, large);
|
||||
assert_eq!(small, vec![true; 3], "a small document stays under 1 MiB");
|
||||
// 2 objects doubled 11 times: 4,096, a list of 64 KiB each time it is built again.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
for _ in 0..11 {
|
||||
s.execute("edit.duplicate", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
}
|
||||
// Nothing selected, so putting the selection back after each edit passes no list of ids.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
for list in lists {
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20)));
|
||||
let r = run(&mut s, &source(list));
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("{list}: 40 lists of 4,096 objects stayed under 1 MiB: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data to and from commands"), "{list}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection read with a name gives what `getByName` gives, and throws as it does for no match.
|
||||
|
||||
@@ -874,6 +874,29 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
|
||||
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into()));
|
||||
}
|
||||
|
||||
/// An answer that cannot be read as a value, for a global function or a member of a host class,
|
||||
/// is thrown at the call that waited, where the script catches it, and the run goes on.
|
||||
#[test]
|
||||
fn an_answer_that_cannot_be_read_is_thrown_at_the_waiting_call() {
|
||||
let mut nested = Data::Null;
|
||||
for _ in 0..20 {
|
||||
nested = Data::Array(vec![nested]);
|
||||
}
|
||||
for call in ["ask('x')", "thing.fetch()"] {
|
||||
let source = format!("var m = 'none'; try {{ {call}; }} catch (e) {{ m = e.name + '|' + e.message; }} m + '|after'");
|
||||
let mut r = realm(1_000_000);
|
||||
with_ask(&mut r);
|
||||
with_thing(&mut r, None);
|
||||
r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 });
|
||||
r.start(&source).unwrap();
|
||||
assert_eq!(r.advance(1_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits());
|
||||
r.answer(nested.clone()).unwrap();
|
||||
let JsValue::String(out) = finish(&mut r, 1_000).0.unwrap() else { panic!("{call}: not a string") };
|
||||
assert!(out.starts_with("RangeError|") && out.contains("nested too deep") && out.ends_with("|after"), "{call}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by
|
||||
/// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing`
|
||||
/// with the handle `[0]`.
|
||||
|
||||
+38
-4
@@ -254,8 +254,10 @@ pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult<Pause>
|
||||
/// resume function gives.
|
||||
pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult<Value>;
|
||||
|
||||
/// What a [`Pause`] does with its kept values when its host call fails.
|
||||
pub(crate) type FailFn = fn(&mut Interp, &[Value]);
|
||||
/// What a [`Pause`] does with its kept values when its host call fails. An error it gives that is
|
||||
/// not thrown (a stop, such as a host's Abort) ends the run in place of a thrown failure; a thrown
|
||||
/// one gives way to the failure.
|
||||
pub(crate) type FailFn = fn(&mut Interp, &[Value]) -> JsResult<()>;
|
||||
|
||||
/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to
|
||||
/// `resume` with `keep`, at once when the host answers at once. When the host waits
|
||||
@@ -274,6 +276,23 @@ pub(crate) struct Pause {
|
||||
pub(crate) struct Resumption {
|
||||
resume: ResumeFn,
|
||||
keep: Vec<Value>,
|
||||
/// Runs when the answer cannot be read, so the resume function never gets it.
|
||||
failed: Option<FailFn>,
|
||||
}
|
||||
|
||||
impl Resumption {
|
||||
/// The built-in does not get the host's answer: its failure function runs with its kept
|
||||
/// values, which `thrown` is kept from collection with. → the stop the failure function
|
||||
/// gave, which ends the run in place of `thrown`.
|
||||
pub(crate) fn fail(self, interp: &mut Interp, thrown: &Value) -> JsResult<()> {
|
||||
let Some(failed) = self.failed else { return Ok(()) };
|
||||
let mark = interp.temp_roots.len();
|
||||
interp.temp_roots.extend(self.keep.iter().cloned());
|
||||
interp.temp_roots.push(thrown.clone());
|
||||
let r = failed(interp, &self.keep);
|
||||
interp.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Interp {
|
||||
@@ -378,6 +397,10 @@ pub(crate) struct Interp {
|
||||
/// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its
|
||||
/// answer is read as such a member's result is ([`Interp::write_hosted`]).
|
||||
pub(crate) waiting_hosted: bool,
|
||||
/// The answer to the call that waited could not be read as a value
|
||||
/// ([`crate::Realm::answer`]): the value on top of the stack is the exception, which the next
|
||||
/// step throws at that call.
|
||||
pub(crate) answer_throws: bool,
|
||||
/// A host class's constructor runs with `new`: it may not wait for its result.
|
||||
pub(crate) constructing: bool,
|
||||
/// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before
|
||||
@@ -690,6 +713,7 @@ impl Interp {
|
||||
can_wait: Rc::default(),
|
||||
waiting: false,
|
||||
waiting_hosted: false,
|
||||
answer_throws: false,
|
||||
constructing: false,
|
||||
resuming: None,
|
||||
again: None,
|
||||
@@ -1031,6 +1055,11 @@ impl Interp {
|
||||
|
||||
fn step(&mut self) -> JsResult<Option<Value>> {
|
||||
self.tick()?;
|
||||
// An answer that could not be read is thrown at the call that waited for it.
|
||||
if std::mem::take(&mut self.answer_throws) {
|
||||
let thrown = self.pop()?;
|
||||
return Err(Abrupt::Throw(thrown));
|
||||
}
|
||||
// A built-in that waited for the host takes the answer on top of the stack before the
|
||||
// instruction after its call runs; what it throws is thrown at that call.
|
||||
if let Some(r) = self.resuming.take() {
|
||||
@@ -3560,6 +3589,7 @@ impl Interp {
|
||||
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read),
|
||||
_ => self.call(&host, &Value::Undefined, &args),
|
||||
};
|
||||
let mut stop = Ok(());
|
||||
if let Err(e) = &answer
|
||||
&& let Some(failed) = failed
|
||||
{
|
||||
@@ -3567,11 +3597,15 @@ impl Interp {
|
||||
if let Abrupt::Throw(v) = e {
|
||||
self.temp_roots.push(v.clone());
|
||||
}
|
||||
failed(self, &keep);
|
||||
stop = failed(self, &keep);
|
||||
}
|
||||
self.temp_roots.truncate(mark);
|
||||
// A stop from `failed` is not masked by a thrown error the script could catch.
|
||||
if matches!(answer, Err(Abrupt::Throw(_))) {
|
||||
stop?;
|
||||
}
|
||||
let answer = answer?;
|
||||
let r = Resumption { resume, keep };
|
||||
let r = Resumption { resume, keep, failed };
|
||||
if self.waiting && !was_waiting {
|
||||
self.resuming = Some(r);
|
||||
return Ok(answer);
|
||||
|
||||
+28
-6
@@ -380,6 +380,7 @@ impl Realm {
|
||||
interp.host_abort = None;
|
||||
interp.waiting = false;
|
||||
interp.waiting_hosted = false;
|
||||
interp.answer_throws = false;
|
||||
interp.constructing = false;
|
||||
interp.resuming = None;
|
||||
interp.again = None;
|
||||
@@ -426,6 +427,7 @@ impl Realm {
|
||||
interp.join_stack.clear();
|
||||
interp.waiting = false;
|
||||
interp.waiting_hosted = false;
|
||||
interp.answer_throws = false;
|
||||
interp.constructing = false;
|
||||
interp.resuming = None;
|
||||
interp.again = None;
|
||||
@@ -566,8 +568,10 @@ impl Realm {
|
||||
/// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next
|
||||
/// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the
|
||||
/// call, the built-in takes `d` first and gives its own result, and what it throws is thrown
|
||||
/// at its call. A result past the heap limit ends the run with that
|
||||
/// limit, and with no call waiting this gives an internal error.
|
||||
/// at its call. A result that cannot be read as a value, such as one nested too deep, is
|
||||
/// thrown at the call as an immediate result would be, and the built-in does not get it. A
|
||||
/// result past the heap limit ends the run with that limit, and with no call waiting this gives
|
||||
/// an internal error.
|
||||
pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> {
|
||||
let interp = &mut self.interp;
|
||||
if !interp.waiting {
|
||||
@@ -584,10 +588,28 @@ impl Realm {
|
||||
let hosted = std::mem::take(&mut interp.waiting_hosted);
|
||||
// The value on top of the stack stood in for the result.
|
||||
let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) };
|
||||
let r = written.and_then(|v| {
|
||||
interp.stack.pop();
|
||||
interp.push(v)
|
||||
});
|
||||
let r = match written {
|
||||
// An answer that cannot be read as a value (too deep, too many entries, a stale host
|
||||
// reference) is thrown at the call, where the script can catch it, and a built-in
|
||||
// that waited with the call does not get it: it fails as when its host call throws. A
|
||||
// stop its failure gives (an Abort from the host) ends the run before the error is
|
||||
// thrown.
|
||||
Err(Abrupt::Throw(thrown)) => {
|
||||
interp.stack.pop();
|
||||
let stop = match interp.resuming.take() {
|
||||
Some(r) => r.fail(interp, &thrown),
|
||||
None => Ok(()),
|
||||
};
|
||||
stop.and_then(|()| {
|
||||
interp.answer_throws = true;
|
||||
interp.push(thrown)
|
||||
})
|
||||
}
|
||||
written => written.and_then(|v| {
|
||||
interp.stack.pop();
|
||||
interp.push(v)
|
||||
}),
|
||||
};
|
||||
match r {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
|
||||
@@ -1543,16 +1543,21 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult<Pause> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing.
|
||||
fn failed(i: &mut Interp, keep: &[Value]) {
|
||||
let Some(win) = arg(keep, 0).as_object() else { return };
|
||||
/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. → a stop
|
||||
/// (an Abort) the host's `end` gave; an error `end` throws gives way to the failure.
|
||||
fn failed(i: &mut Interp, keep: &[Value]) -> JsResult<()> {
|
||||
let Some(win) = arg(keep, 0).as_object() else { return Ok(()) };
|
||||
if classes(i).ok().and_then(|c| c.showing) != Some(win) {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
set_showing(i, None);
|
||||
if let Ok(end) = host_fn(i, "end") {
|
||||
let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]);
|
||||
match i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]) {
|
||||
Ok(_) | Err(Abrupt::Throw(_)) => {}
|
||||
Err(stop) => return Err(stop),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `show()` ends with `result`.
|
||||
@@ -1611,10 +1616,15 @@ fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResu
|
||||
Abrupt::Throw(t) => vec![t.clone()],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let thrown_error = !thrown.is_empty();
|
||||
let mark = i.temp_roots.len();
|
||||
i.temp_roots.extend(thrown);
|
||||
failed(i, keep);
|
||||
let stop = failed(i, keep);
|
||||
i.temp_roots.truncate(mark);
|
||||
// A stop from `end` is not masked by a thrown error the script could catch.
|
||||
if thrown_error {
|
||||
stop?;
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -229,6 +229,82 @@ fn a_dialog_can_be_shown_again_after_it_closed() {
|
||||
assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into()));
|
||||
}
|
||||
|
||||
/// An event the host gives a waiting `show()` that cannot be read is thrown at `show()`, and the
|
||||
/// dialog is no longer showing, so it can be shown again.
|
||||
#[test]
|
||||
fn an_event_that_cannot_be_read_ends_show_and_the_dialog_can_show_again() {
|
||||
let (mut r, seen, _) = realm(Vec::new());
|
||||
r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 });
|
||||
let mut nested = Data::Null;
|
||||
for _ in 0..20 {
|
||||
nested = Data::Array(vec![nested]);
|
||||
}
|
||||
r.start("var w = new Window('dialog'), m = 'none'; try { w.show(); } catch (e) { m = e.name; } m + '|' + w.show()").unwrap();
|
||||
assert_eq!(r.advance(100_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits());
|
||||
r.answer(nested).unwrap();
|
||||
assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result");
|
||||
assert_eq!(r.advance(100_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits(), "the second show waits for its event");
|
||||
r.answer(close()).unwrap();
|
||||
let mut out = r.advance(100_000).unwrap();
|
||||
while out == Progress::Paused {
|
||||
out = r.advance(100_000).unwrap();
|
||||
}
|
||||
assert_eq!(out, Progress::Done(JsValue::String("RangeError|0".into())));
|
||||
assert_eq!(seen.borrow().ends, vec![(0.0, false), (0.0, true)]);
|
||||
}
|
||||
|
||||
/// A realm whose `end` stops the run (an Abort) when `show()` ends without its result, whose
|
||||
/// `open` throws when `open_fails`, and whose `wait` gives `events` in order, then waits.
|
||||
fn stopping_realm(open_fails: bool, events: Vec<Data>) -> Realm {
|
||||
let mut r = Realm::new();
|
||||
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
let queue = RefCell::new(VecDeque::from(events));
|
||||
let open: HostFunction = Rc::new(move |_| if open_fails { Err(HostError::Error("no window".into())) } else { Ok(Data::Undefined) });
|
||||
let wait: HostFunction = Rc::new(move |_| queue.borrow_mut().pop_front().ok_or(HostError::Wait));
|
||||
let end: HostFunction = Rc::new(|args| match args.get(1) {
|
||||
Some(Data::Bool(true)) => Ok(Data::Undefined),
|
||||
_ => Err(HostError::Abort("stopped by the host".into())),
|
||||
});
|
||||
let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))];
|
||||
r.define_script_ui(items).unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
fn is_host_stop(e: &RunError) -> bool {
|
||||
e.kind == RunErrorKind::Limit(LimitKind::Host) && e.message == "stopped by the host"
|
||||
}
|
||||
|
||||
/// A stop the host's `end` gives when `show()` fails ends the run: the script cannot catch the
|
||||
/// failure and go on, whether the event could not be read, the host call threw or a handler threw.
|
||||
#[test]
|
||||
fn a_stop_from_end_when_show_fails_ends_the_run() {
|
||||
let caught = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { throw new Error('handler'); }; \
|
||||
try { w.show(); } catch (e) {} 'went on'";
|
||||
|
||||
let mut r = stopping_realm(false, Vec::new());
|
||||
r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 });
|
||||
let mut nested = Data::Null;
|
||||
for _ in 0..20 {
|
||||
nested = Data::Array(vec![nested]);
|
||||
}
|
||||
r.start(caught).unwrap();
|
||||
assert_eq!(r.advance(100_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits());
|
||||
let answered = r.answer(nested);
|
||||
assert!(answered.as_ref().is_err_and(is_host_stop), "unreadable event: {answered:?}");
|
||||
|
||||
let mut r = stopping_realm(true, Vec::new());
|
||||
let ran = r.run(caught);
|
||||
assert!(ran.as_ref().is_err_and(is_host_stop), "open threw: {ran:?}");
|
||||
|
||||
let mut r = stopping_realm(false, vec![click(1)]);
|
||||
let ran = r.run(caught);
|
||||
assert!(ran.as_ref().is_err_and(is_host_stop), "handler threw: {ran:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn types_that_are_not_available_yet_throw_errors_that_say_so() {
|
||||
for (source, want) in [
|
||||
|
||||
Reference in new issue
Block a user