From 54cd14b3cd615e5d7096eeee9674351e3f30b101 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:50:35 -0800 Subject: [PATCH 01/60] Plug-ins: react to selection, layer, open and save events A plug-in at API level 2 with the new `events` permission can name any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest's `events` list. Its `vc_event` export is then called with a small JSON event after each change of that kind has finished, outside any undo step. Changes between two deliveries are one event. The desktop app delivers twice a frame, after the work that finished in the background and at the end of the frame after the canvas, panels and dialogs ran; control-channel requests run in the desktop app and are delivered by the frame. vectorcraft-cli and headless MCP deliver after each request. A plug-in installed after a change is not given it, and a change made after an install reaches the new plug-in at the next delivery. - A handler only reads. It may call ten commands that read (dataset.list, graphicStyle.list, guide.list, image.info, object.blend.info, swatch.list, symbol.list, text.getRange, transparency.info and variable.list); any other call fails before it runs with an error naming the event. After each call every document with its selection, current layer and undo history, the active document, the paint defaults, the active Appearance row and the preferences are put back, and a call that changed a document is refused. - A handler gets 5 M instructions and 200 ms, shared by the module's start function, `vc_alloc` and `vc_event`. A handler that fails 3 times in a row gets no more events until VectorCraft starts again. - An event raised while a handler runs waits for the next delivery. - Events carry the document number and counts; selected ids (at most 2,048) only with `doc.read`. No paths or file contents. - A save that finishes after its document closed is still reported. - A document opened or created since the last delivery is compared with its state when the command that added it ended, so the first change made to it is an event. - A waiting event is dropped for a plug-in that was removed, so the same module installed again is not given it. - The desktop app delivers the events of a script in the frame the script ends in. plugin.list and plugin.info report `events`, `eventsOff` and `lastEventError`. Docs: docs/plugins.md (Events), docs/mcp.md and one progress line in docs/target-app-parity.md. The new plug-in messages, the status lines for a failed handler and the permission's words in Install Plug-in... have rows in every complete catalog. --- crates/engine/src/cmd/fileio/load.rs | 3 +- crates/engine/src/cmd/fileio/save.rs | 2 + crates/engine/src/cmd/plugin.rs | 16 +- crates/engine/src/cmd/plugin_call.rs | 118 ++++++ crates/engine/src/lib.rs | 7 + crates/engine/src/plugin_events.rs | 515 +++++++++++++++++++++++ crates/engine/src/session/documents.rs | 6 + crates/engine/src/session/execute.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/plugin_events.rs | 459 ++++++++++++++++++++ crates/plugins/src/events.rs | 94 +++++ crates/plugins/src/lib.rs | 5 +- crates/plugins/src/manifest.rs | 101 ++++- crates/plugins/src/permissions.rs | 16 +- crates/plugins/src/runtime.rs | 104 ++++- crates/plugins/src/wat.rs | 12 + crates/plugins/tests/abi.rs | 73 ++++ crates/ui-egui/src/app.rs | 34 ++ crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tests.rs | 27 ++ crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/io/open.rs | 1 + crates/ui-egui/src/tests/plugins.rs | 40 ++ crates/ui-egui/src/tests/script_run.rs | 32 ++ docs/mcp.md | 5 +- docs/plugins.md | 67 ++- docs/target-app-parity.md | 1 + 54 files changed, 1976 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/plugin_events.rs create mode 100644 crates/engine/src/tests/plugin_events.rs create mode 100644 crates/plugins/src/events.rs diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 1818816842..128d91c4f6 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1003,7 +1003,8 @@ fn open_loaded( st.import_losses = losses; st.links_from = read_from; let opened = &s.documents()[index]; - let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string()); + let (title, file_info_title, uid) = (opened.title(), opened.doc.info_title().to_string(), opened.uid); + s.note_plugin_event(vectorcraft_plugins::Event::DocumentOpened, uid); Ok(super::merge( json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }), links.to_json(), diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..830378e28a 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1201,6 +1201,8 @@ impl SaveJob { } if saved { crate::cmd::recovery::forget(s, uid); + // Also when the document closed while its file was being written. + s.note_plugin_event(vectorcraft_plugins::Event::DocumentSaved, uid); } if let Some(path) = written { if native { diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..5cd4686afb 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -104,6 +104,9 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if !m.events.is_empty() { + v["events"] = json!(m.events); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -886,6 +889,7 @@ fn install(s: &mut Session, p: &Value) -> Result { s.store_disabled_plugins_in(&turn); } drop(turn); + s.plugins_changed_for_events(); let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); @@ -1198,12 +1202,17 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::>()})) } -fn info(_: &mut Session, p: &Value) -> Result { +fn info(s: &mut Session, p: &Value) -> Result { let plugin = plugin_by_id("plugin.info", p)?; let mut v = describe_installed(&plugin); v["manifest"] = serde_json::to_value(plugin.manifest()).unwrap_or(Value::Null); v["defaults"] = Value::Object(plugin.manifest().defaults()); v["lastError"] = json!(effect::last_error(plugin.id())); + if !plugin.manifest().events.is_empty() { + let (off, last) = s.plugin_event_status(&plugin); + v["eventsOff"] = json!(off); + v["lastEventError"] = json!(last); + } Ok(v) } @@ -1241,6 +1250,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { if !stored && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } + s.plugins_changed_for_events(); Ok(json!({"removed": id})) } @@ -1270,7 +1280,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md; events: it reacts to the events it names, see events), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), events?: [\"selection.changed\"|\"document.opened\"|\"document.saved\"|\"layer.changed\"] (the events its vc_event handler is given after each change of that kind, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1279,7 +1289,7 @@ pub fn specs() -> Vec { "Plug-in Info", [], None, - "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width)}", + "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or another module is installed with its id), lastEventError? (with events: its handler's last failure, null)}", always, info ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 867c1f2ff0..21d515163f 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -461,6 +461,78 @@ pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std: Ok(value) } +/// The commands a plug-in's event handler may call ([`event_call`]), in order: each one only reads +/// the document and returns what it found. Every other command is refused before it runs. +pub(crate) const EVENT_READS: &[&str] = &[ + "dataset.list", + "graphicStyle.list", + "guide.list", + "image.info", + "object.blend.info", + "swatch.list", + "symbol.list", + "text.getRange", + "transparency.info", + "variable.list", +]; + +/// Makes call `id` with `args` from a plug-in's handler of event `event` ([`crate::plugin_events`]) +/// as [`call`] does, for a command in [`EVENT_READS`]; any other command is refused before it runs, +/// with an error that names the event. The call runs inside [`read_only`]: every document and the +/// session state the commands a plug-in may call change go back to how they were afterwards, and a +/// call that changed a document, its selection, current layer or layer rows, or which document is +/// active, is refused. +pub(crate) fn event_call(s: &mut Session, run: &Calls, event: &str, id: &str, args: &Value) -> std::result::Result { + if super::find_command(id).is_none() { + return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() }); + } + if !EVENT_READS.contains(&id) { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` is not a command it may call") }); + } + let (r, changed) = read_only(s, |s| call(s, run, id, args)); + if changed { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` changed the document") }); + } + r +} + +/// Runs `f` and then puts every open document (its art, selection, current layer, rows and +/// history), which document is active and the session state the commands a plug-in may call change +/// ([`Saved`]) back to how they were → `f`'s result, and whether `f` changed a document, its +/// selection, current layer or layer rows, opened or closed one, or changed which one is active. +/// A document `f` changed is given a newer revision, so it redraws. +fn read_only(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) { + let saved = Saved::of(s); + let pending_paint = s.pending_paint.clone(); + let start = s.docs.clone(); + let active = s.active; + let r = f(s); + let now = std::mem::replace(&mut s.docs, start); + let mut changed = s.active != active || now.len() != s.docs.len(); + for st in &mut s.docs { + let Some(n) = now.iter().find(|d| d.uid == st.uid) else { + changed = true; + continue; + }; + if n.revision != st.revision + || !Arc::ptr_eq(&n.doc, &st.doc) + || n.selection != st.selection + || n.active_layer != st.active_layer + || n.layer_rows != st.layer_rows + { + st.revision = st.revision.max(n.revision).saturating_add(1); + changed = true; + } + } + s.active = active; + saved.restore(s); + s.pending_paint = pending_paint; + if changed { + s.sync_front_profiles(); + } + (r, changed) +} + /// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the /// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever /// param carries it. @@ -917,4 +989,50 @@ mod tests { assert!(!names_key("{pathData: 1}", "path")); assert!(names_key("path: x", "path")); } + + /// Each command an event handler may call is one a plug-in may call and one the journal does + /// not record, listed once, in order. + #[test] + fn event_reads_are_reviewed_reads() { + for id in EVENT_READS { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert_eq!(denied(spec), None, "{id} is refused to every plug-in"); + assert!(!spec.journal, "{id} is journaled"); + } + assert!(EVENT_READS.windows(2).all(|w| w[0] < w[1]), "in order, once each"); + } + + /// [`read_only`] puts back what its function changed: the document, its selection, the + /// preferences and the paint defaults, and says that the document changed; a function that + /// changes nothing is no change. + #[test] + fn read_only_puts_everything_back() { + use serde_json::json; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.none", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (prefs, paint) = (s.prefs.history_states, s.paint.clone()); + let ((), changed) = read_only(&mut s, |s| { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + s.prefs.history_states += 1; + s.paint.stroke_width += 3.0; + }); + assert!(changed); + let st = s.doc().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert!(st.selection.objects.is_empty(), "the selection as it was"); + assert_eq!(st.history.undo.len(), history, "no undo step"); + assert!(st.revision > revision, "a newer revision, so it redraws"); + assert_eq!((s.prefs.history_states, &s.paint), (prefs, &paint)); + let revision = st.revision; + let ((), changed) = read_only(&mut s, |s| { + s.execute("variable.list", &json!({})).unwrap(); + }); + assert!(!changed, "a read changes nothing"); + assert_eq!(s.doc().unwrap().revision, revision); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..ed85ece069 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ pub mod guard; pub mod inspect; pub mod journal; pub mod link_watch; +pub mod plugin_events; pub mod schemas; pub mod steps; pub mod store; @@ -317,6 +318,12 @@ pub struct Session { /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, + /// The events plug-ins react to that wait for delivery, and how the documents were at the last + /// check ([`plugin_events`]). + pub(crate) plugin_events: plugin_events::PluginEvents, + /// The frontend delivers plug-in events by the frame ([`Session::deliver_plugin_events`]). Off, + /// each top-level command delivers them when it ends. + pub plugin_event_frames: bool, /// The warnings of the previews that settling an interaction applied, while a top-level command /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). settled_warnings: Option>, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs new file mode 100644 index 0000000000..9951904991 --- /dev/null +++ b/crates/engine/src/plugin_events.rs @@ -0,0 +1,515 @@ +//! Events plug-ins react to ([`vectorcraft_plugins::events`]): the session notices a changed +//! selection, current layer or set of layers by comparing each open document with how it was at the +//! last check, and hears of each successful open and save ([`Session::note_plugin_event`]). It then +//! calls the `vc_event` handler of each installed plug-in whose manifest names the event, after the +//! change has finished and outside any undo step. +//! +//! - A check runs after each top-level command, or when a frontend that sets +//! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame. +//! Changes between two checks are one event: a burst of selection changes is one +//! `selection.changed` with the final selection. No check runs while an interaction is open (a +//! drag being previewed). A document opened or created since the last check is compared with how +//! it was when the command that added it ended ([`Session::plugin_events_see_new_documents`]). +//! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a +//! handler runs waits for the next delivery: handlers never run inside one another. +//! - A handler only reads. The host applies nothing it returns, and it may call only the commands +//! in [`super::cmd::plugin_call::EVENT_READS`]; any other call is refused with an error that names +//! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]). +//! - A handler that fails is reported once a streak; after +//! [`vectorcraft_plugins::events::MAX_EVENT_FAILURES`] failures in a row the plug-in's events stop +//! until the session ends, or until another module is installed under its id. +//! - When no installed plug-in reacts to events, a check returns before comparing anything. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; +use vectorcraft_plugins::events::{Event, MAX_EVENT_FAILURES, MAX_EVENT_IDS}; +use vectorcraft_plugins::permissions::Permission; +use vectorcraft_plugins::{LogLevel, Plugin, registry}; + +use crate::Session; + +/// Most events that wait for delivery. +pub const MAX_PENDING: usize = 32; + +/// Most notices kept for the frontend to show; older ones are dropped. +pub const MAX_NOTICES: usize = 64; + +/// The reasons a `layer.changed` event gives, in the order it lists them. +pub const LAYER_REASONS: [&str; 5] = ["current", "added", "deleted", "reordered", "options"]; + +/// A document as the last check saw it. +struct Seen { + uid: u64, + doc: Arc, + selection: Selection, + layer: Option, +} + +/// A plug-in an event is for: its id and the hash of its module. +type Recipient = (String, String); + +/// The recipient `p` is. +fn recipient(p: &Plugin) -> Recipient { + (p.id().to_string(), p.hash().to_string()) +} + +/// An event waiting for delivery: what changed, in which document, for `layer.changed` why, and +/// the plug-ins it is for: those installed when it happened. +#[derive(Clone, Debug, PartialEq)] +struct Pending { + event: Event, + document: u64, + reasons: Vec<&'static str>, + to: Vec, +} + +/// One plug-in's failed handlers in a row, for the module with `hash`. +#[derive(Clone, Debug, Default)] +struct Failures { + hash: String, + count: u32, + disabled: bool, + last_error: Option, +} + +/// A line a handler wrote with `vc_log`, or a handler's failure, for the frontend to show. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notice { + /// The plug-in's id and name. + pub plugin: String, + pub name: String, + /// The event its handler was given. + pub event: &'static str, + pub level: LogLevel, + /// The text, in English for a failure. + pub text: String, +} + +/// The session's plug-in event state. +#[derive(Default)] +pub struct PluginEvents { + seen: Vec, + /// The plug-ins that reacted to events when `seen` was taken. + seen_by: Vec, + pending: VecDeque, + dispatching: bool, + failures: BTreeMap, + notices: VecDeque, + /// The installed plug-ins that react to events, as of a registry revision. + subscribers: Option<(u64, Vec>)>, +} + +impl PluginEvents { + /// The installed plug-ins that react to events (none in Safe Mode). + fn subscribers(&mut self) -> Vec> { + if vectorcraft_plugins::safe_mode::active() { + return Vec::new(); + } + let revision = registry::revision(); + if let Some((at, subs)) = &self.subscribers + && *at == revision + { + return subs.clone(); + } + let subs: Vec> = registry::list().into_iter().filter(|p| !p.manifest().events.is_empty()).collect(); + self.subscribers = Some((revision, subs.clone())); + subs + } + + /// Queues `event` for document `uid`, for the plug-ins `to`. A `selection.changed` or + /// `layer.changed` already waiting for that document takes it in (a layer event adds the new + /// reasons to its own, and the new plug-ins to its own); past [`MAX_PENDING`] the oldest event is + /// dropped. + fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec) { + if matches!(event, Event::SelectionChanged | Event::LayerChanged) + && let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid) + { + for r in reasons { + if !p.reasons.contains(&r) { + p.reasons.push(r); + } + } + p.reasons.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); + for r in to { + if !p.to.contains(&r) { + p.to.push(r); + } + } + return; + } + if self.pending.len() >= MAX_PENDING + && let Some(dropped) = self.pending.pop_front() + { + log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); + } + self.pending.push_back(Pending { event, document: uid, reasons, to }); + } + + fn notice(&mut self, n: Notice) { + if self.notices.len() >= MAX_NOTICES { + self.notices.pop_front(); + } + self.notices.push_back(n); + } + + /// The failures of plug-in `p`, started again when another module was installed under its id. + fn failures_of(&mut self, p: &Plugin) -> &mut Failures { + let f = self.failures.entry(p.id().to_string()).or_default(); + if f.hash != p.hash() { + *f = Failures { hash: p.hash().to_string(), ..Failures::default() }; + } + f + } +} + +/// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its +/// contents (for comparing its options) and the ids of the rows directly in it, in order. +type LayerRow = (NodeId, Option, vectorcraft_doc::Node, Vec); + +/// Each layer and sublayer of `doc`, in order. +fn layer_rows(doc: &Document) -> Vec { + let mut out = Vec::new(); + let mut stack: Vec<(&Arc, Option)> = doc.layers.iter().rev().map(|l| (l, None)).collect(); + while let Some((n, parent)) = stack.pop() { + let NodeKind::Layer { children, .. } = &n.kind else { continue }; + stack.extend(children.iter().rev().filter(|c| c.is_layer()).map(|c| (c, Some(n.id)))); + let rows = children.iter().map(|c| c.id).collect(); + let mut bare = (**n).clone(); + if let Some(c) = bare.children_mut() { + c.clear(); + } + out.push((n.id, parent, bare, rows)); + } + out +} + +/// Whether a layer's place among the rows beside it differs between `old` (of `before`) and `new` +/// (of `after`), counting only the rows on both sides, so an object added or deleted next to a +/// sublayer is not a move. +fn layers_moved_among_rows(before: &Document, old: &[LayerRow], after: &Document, new: &[LayerRow]) -> bool { + use std::collections::{HashMap, HashSet}; + let layers: HashSet = old.iter().map(|r| r.0).collect(); + let lists = |doc: &Document, rows: &[LayerRow]| { + let mut m: HashMap, Vec> = rows.iter().map(|r| (Some(r.0), r.3.clone())).collect(); + m.insert(None, doc.layers.iter().map(|l| l.id).collect()); + m + }; + let (a, b) = (lists(before, old), lists(after, new)); + a.iter().any(|(parent, xs)| { + let Some(ys) = b.get(parent) else { return false }; + let (in_x, in_y): (HashSet, HashSet) = (xs.iter().copied().collect(), ys.iter().copied().collect()); + let places = |list: &[NodeId], other: &HashSet| { + list.iter().filter(|id| other.contains(id)).enumerate().filter(|(_, id)| layers.contains(id)).map(|(i, id)| (i, *id)).collect::>() + }; + places(xs, &in_y) != places(ys, &in_x) + }) +} + +/// Why the layers of `after` (with current layer `layer_after`) differ from those of `before` +/// (with `layer_before`), in [`LAYER_REASONS`] order; empty when they don't. +fn layer_reasons(before: &Arc, layer_before: Option, after: &Arc, layer_after: Option) -> Vec<&'static str> { + let mut reasons = Vec::new(); + if layer_before != layer_after { + reasons.push("current"); + } + if Arc::ptr_eq(before, after) { + return reasons; + } + let (old, new) = (layer_rows(before), layer_rows(after)); + if new.iter().any(|(id, ..)| !old.iter().any(|(o, ..)| o == id)) { + reasons.push("added"); + } + if old.iter().any(|(id, ..)| !new.iter().any(|(n, ..)| n == id)) { + reasons.push("deleted"); + } + let kept = + |rows: &[LayerRow], other: &[LayerRow]| rows.iter().filter(|r| other.iter().any(|o| o.0 == r.0)).map(|r| (r.0, r.1)).collect::>(); + if kept(&old, &new) != kept(&new, &old) || layers_moved_among_rows(before, &old, after, &new) { + reasons.push("reordered"); + } + if old.iter().any(|r| new.iter().any(|o| o.0 == r.0 && o.2 != r.2)) { + reasons.push("options"); + } + reasons +} + +impl Session { + /// Hears that `event` (`document.opened` or `document.saved`) happened to document `uid`, which + /// the next delivery hands the plug-ins that react to it. Nothing is kept when none does. + pub(crate) fn note_plugin_event(&mut self, event: Event, uid: u64) { + let to: Vec = self.plugin_events.subscribers().iter().filter(|p| p.manifest().reacts_to(event)).map(|p| recipient(p)).collect(); + if to.is_empty() { + return; + } + self.plugin_events.queue(event, uid, Vec::new(), to); + } + + /// Compares each open document with how the last check saw it and queues the events its changes + /// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the + /// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in + /// installed since the last check is given none: the + /// change may have come before it. A waiting event is no longer for a plug-in that is not + /// installed now, so a module removed and installed again is not given it. Nothing is compared + /// while an interaction is open, nor when no plug-in reacts to events. + fn check_plugin_events(&mut self) { + let subs = self.plugin_events.subscribers(); + if subs.is_empty() { + self.plugin_events.seen.clear(); + self.plugin_events.seen_by.clear(); + self.plugin_events.pending.clear(); + return; + } + let installed: Vec = subs.iter().map(|p| recipient(p)).collect(); + self.plugin_events.pending.retain_mut(|p| { + p.to.retain(|r| installed.contains(r)); + !p.to.is_empty() + }); + if self.docs.iter().any(|d| d.interaction.is_some()) { + return; + } + let mut events = std::mem::take(&mut self.plugin_events); + let before = std::mem::take(&mut events.seen); + let before_by = std::mem::take(&mut events.seen_by); + let to = |e: Event| -> Vec { + subs.iter().filter(|p| p.manifest().reacts_to(e)).map(|p| recipient(p)).filter(|r| before_by.contains(r)).collect() + }; + let (selection, layers) = (to(Event::SelectionChanged), to(Event::LayerChanged)); + let mut seen = Vec::with_capacity(self.docs.len()); + for st in &self.docs { + if let Some(old) = before.iter().find(|s| s.uid == st.uid) { + if !selection.is_empty() && old.selection != st.selection { + events.queue(Event::SelectionChanged, st.uid, Vec::new(), selection.clone()); + } + if !layers.is_empty() { + let reasons = layer_reasons(&old.doc, old.layer, &st.doc, st.active_layer); + if !reasons.is_empty() { + events.queue(Event::LayerChanged, st.uid, reasons, layers.clone()); + } + } + } + seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); + } + events.seen = seen; + events.seen_by = subs.iter().map(|p| recipient(p)).collect(); + events.pending.retain(|p| p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)); + self.plugin_events = events; + } + + /// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the + /// handlers of the events waiting, oldest first, one handler at a time. While a handler runs, + /// this returns at once: what the handler's calls change waits for the next delivery. + pub fn deliver_plugin_events(&mut self) { + if self.plugin_events.dispatching { + return; + } + self.check_plugin_events(); + if self.plugin_events.pending.is_empty() { + return; + } + let subs = self.plugin_events.subscribers(); + self.plugin_events.dispatching = true; + // The commands a handler calls run nested, never journaled; a panic in one leaves the depth + // as it was found. + let depth = self.depth; + self.depth += 1; + while let Some(p) = self.plugin_events.pending.pop_front() { + if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { + continue; + } + for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.to.contains(&recipient(s))) { + if self.plugin_events.failures_of(plugin).disabled { + continue; + } + self.run_handler(plugin, &p); + } + } + self.depth = depth; + self.plugin_events.dispatching = false; + } + + /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a + /// `selection.changed` only with `doc.read`. + fn event_json(&self, plugin: &Plugin, p: &Pending) -> Value { + let mut v = json!({ "type": p.event.name(), "document": p.document }); + let Some(st) = self.docs.iter().find(|d| d.uid == p.document) else { return v }; + match p.event { + Event::SelectionChanged => { + let objects = &st.selection.objects; + v["count"] = json!(objects.len()); + v["truncated"] = json!(false); + v["ids"] = Value::Null; + if plugin.manifest().permissions().contains(&Permission::DocRead) { + v["ids"] = json!(objects.iter().take(MAX_EVENT_IDS).map(|i| i.0).collect::>()); + v["truncated"] = json!(objects.len() > MAX_EVENT_IDS); + } + } + Event::LayerChanged => { + v["layer"] = json!(st.active_layer.map(|l| l.0)); + v["reasons"] = json!(p.reasons); + } + Event::DocumentOpened | Event::DocumentSaved => {} + } + v + } + + /// Calls `plugin`'s handler with event `p` and records what it wrote and whether it failed. + fn run_handler(&mut self, plugin: &Arc, p: &Pending) { + let event = p.event.name(); + let text = serde_json::to_vec(&self.event_json(plugin, p)).unwrap_or_default(); + let m = plugin.manifest(); + let may = m.permissions(); + let (r, report) = if may.contains(&Permission::Commands) && !m.command_allowlist.is_empty() { + let calls = crate::cmd::plugin_call::Calls::of(self, may.contains(&Permission::DocRead), false); + let mut bridge = |id: &str, args: &Value| crate::cmd::plugin_call::event_call(self, &calls, event, id, args); + plugin.run_event(&text, Some(&mut bridge)) + } else { + plugin.run_event(&text, None) + }; + let (id, name) = (plugin.id().to_string(), m.name.clone()); + for line in report.lines { + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text }); + } + let failures = self.plugin_events.failures_of(plugin); + let e = match r { + Ok(()) => { + failures.count = 0; + return; + } + Err(e) => e.to_string(), + }; + failures.count += 1; + failures.last_error = Some(e.clone()); + let (count, first) = (failures.count, failures.count == 1); + log::warn!("plug-in {id}: its {event} handler failed: {e}"); + if first { + let text = format!("its {event} handler failed: {e}"); + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text }); + } + if count >= MAX_EVENT_FAILURES { + self.plugin_events.failures_of(plugin).disabled = true; + let text = format!("its events are off until VectorCraft starts again, after {count} failed handlers in a row"); + self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text }); + } + } + + /// Takes each open document the last check didn't see, one opened or created since, as it is + /// now, so the next check compares it with this state: a change made to it before the next + /// delivery gives its event. Called after each top-level command and when a document is added + /// outside one. Nothing is kept when no plug-in reacted to events at the last check, nor for a + /// document in an interaction. + pub(crate) fn plugin_events_see_new_documents(&mut self) { + if self.plugin_events.seen_by.is_empty() { + return; + } + for st in &self.docs { + if st.interaction.is_none() && !self.plugin_events.seen.iter().any(|s| s.uid == st.uid) { + self.plugin_events.seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); + } + } + } + + /// Delivers the events of a top-level command that just ended, unless the frontend delivers + /// them once a frame ([`Session::plugin_event_frames`]) or a script is running. + pub(crate) fn plugin_events_after_command(&mut self) { + self.plugin_events_see_new_documents(); + if !self.plugin_event_frames && !self.script_in_run { + self.deliver_plugin_events(); + } + } + + /// After a plug-in was installed or removed, compares the open documents with the last check + /// ([`Session::check_plugin_events`]): what changed before is given only to the plug-ins that + /// were installed then, and what changes from now on to every plug-in installed now, also + /// before the next delivery. + pub(crate) fn plugins_changed_for_events(&mut self) { + if !self.plugin_events.dispatching { + self.check_plugin_events(); + } + } + + /// The handlers' log lines and failures since the last call, oldest first. + pub fn take_plugin_event_notices(&mut self) -> Vec { + self.plugin_events.notices.drain(..).collect() + } + + /// Whether this session stopped delivering events to plug-in `p` after its handlers failed, and + /// the last failure's error. + pub fn plugin_event_status(&self, p: &Plugin) -> (bool, Option) { + match self.plugin_events.failures.get(p.id()).filter(|f| f.hash == p.hash()) { + Some(f) => (f.disabled, f.last_error.clone()), + None => (false, None), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waiting_selection_and_layer_events_of_a_document_merge() { + let mut e = PluginEvents::default(); + e.queue(Event::SelectionChanged, 1, vec![], vec![]); + e.queue(Event::LayerChanged, 1, vec!["options"], vec![]); + e.queue(Event::SelectionChanged, 1, vec![], vec![]); + e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![]); + e.queue(Event::SelectionChanged, 2, vec![], vec![]); + e.queue(Event::DocumentSaved, 1, vec![], vec![]); + e.queue(Event::DocumentSaved, 1, vec![], vec![]); + let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons.clone())).collect(); + assert_eq!( + got, + [ + (Event::SelectionChanged, 1, vec![]), + (Event::LayerChanged, 1, vec!["current", "options"]), + (Event::SelectionChanged, 2, vec![]), + (Event::DocumentSaved, 1, vec![]), + (Event::DocumentSaved, 1, vec![]), + ] + ); + } + + /// While a handler runs, a delivery returns at once; the change waits for the next one, which + /// hands it over once. + #[test] + fn an_event_raised_while_a_handler_runs_waits_for_the_next_delivery() { + use serde_json::json; + use vectorcraft_plugins::wat as tpl; + let id = "test.events.nested"; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.allow_plugin_grants_from_requests(); + let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.none", &json!({})).unwrap(); + let manifest = + format!(r#"{{"id":"{id}","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let grant = json!(["progress", "events"]); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + s.plugin_event_frames = true; + let given = |s: &mut Session| s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).count(); + s.plugin_events.dispatching = true; + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 0, "not inside the running handler"); + s.plugin_events.dispatching = false; + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 1); + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 0, "once"); + s.execute("plugin.remove", &json!({"id": id})).unwrap(); + } + + #[test] + fn at_most_32_events_wait() { + let mut e = PluginEvents::default(); + for uid in 0..(MAX_PENDING as u64 + 5) { + e.queue(Event::DocumentOpened, uid, vec![], vec![]); + } + assert_eq!(e.pending.len(), MAX_PENDING); + assert_eq!(e.pending.front().map(|p| p.document), Some(5), "the oldest are dropped"); + } +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..684b2b881a 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -136,6 +136,8 @@ impl Session { screens_hand_off: None, recovery: Default::default(), in_tool_actions: false, + plugin_events: Default::default(), + plugin_event_frames: false, settled_warnings: None, previewing: false, decoded_images: Default::default(), @@ -365,6 +367,10 @@ impl Session { { self.begin_named_undo_group(label); } + if self.depth == 0 { + // Inside a command, this happens once the command has finished. + self.plugin_events_see_new_documents(); + } i } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..19cd41fdb0 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -249,6 +249,7 @@ impl Session { self.journal_in_undo_groups(doc, &grouped, journal); self.trim_histories(); self.after_command(Some(id)); + self.plugin_events_after_command(); } else if matches!(id, "edit.undo" | "edit.redo") { // A step of `command.batch`: the tool hears of it as it does of the command alone. self.notify_text_tool(id); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..36fb0b0f47 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -145,6 +145,7 @@ mod perspgrid; mod pixelalign; mod place; mod placed_document; +mod plugin_events; mod plugins; mod prefs; mod prefs_file; diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs new file mode 100644 index 0000000000..df8dd04cb4 --- /dev/null +++ b/crates/engine/src/tests/plugin_events.rs @@ -0,0 +1,459 @@ +//! Events plug-ins react to (`events`, `vc_event`): each event reaches the plug-ins that name it, +//! once, after the change; a burst of selection changes in one frame is one event; a handler only +//! reads; and a handler that keeps failing stops being called. + +use serde_json::{Value, json}; +use vectorcraft_plugins::LogLevel; +use vectorcraft_plugins::wat as tpl; + +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// A session with a 400 × 200 document that takes `grant` from requests. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.allow_plugin_grants_from_requests(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Installs plug-in `id` that reacts to `events` (a JSON list) with the vc_event body `handler`, +/// writes log lines and also has the permissions `more`; `imports` are module fields its handler +/// uses besides the host imports, and `allowlist` the commands it may call. +fn install(s: &mut Session, id: &str, events: &str, more: &[&str], imports: &str, handler: &str, allowlist: &[&str]) { + let mut grant = vec!["progress", "events"]; + grant.extend_from_slice(more); + let allow = if allowlist.is_empty() { String::new() } else { format!(r#","commandAllowlist":{}"#, json!(allowlist)) }; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{},"events":{events}{allow}}}"#, json!(grant)); + let wasm = wat::parse_str(tpl::reacting(&manifest, &format!("{} {imports}", tpl::HOST_IMPORTS), handler)).unwrap(); + run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); +} + +/// The events plug-in `id`'s handler was given since the last call, as it logged them. +fn given(s: &mut Session, id: &str) -> Vec { + let notices = s.take_plugin_event_notices(); + notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Info).map(|n| serde_json::from_str(&n.text).unwrap()).collect() +} + +fn types(events: &[Value]) -> Vec<&str> { + events.iter().map(|e| e["type"].as_str().unwrap()).collect() +} + +/// A selection change, a new layer, a save and an open each reach the plug-in that names them once, +/// after the change, with the document they happened in; a plug-in that names only `document.saved` +/// is given only the save. +#[test] +fn each_event_reaches_the_plugins_that_name_it_once() { + let (all, saves) = ("test.events.all", "test.events.saves"); + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, all, r#"["selection.changed","document.opened","document.saved","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + install(&mut s, saves, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + assert!(given(&mut s, all).is_empty(), "installing replays nothing"); + let doc = s.doc().unwrap().uid; + + run(&mut s, "select.set", json!({"ids": [r.0]})); + let notices = s.take_plugin_event_notices(); + let got: Vec = notices.iter().filter(|n| n.plugin == all).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + assert!(notices.iter().all(|n| n.plugin != saves), "not named, not given"); + + run(&mut s, "select.set", json!({"ids": [r.0]})); + assert!(given(&mut s, all).is_empty(), "the same selection again is no change"); + + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + let got = given(&mut s, all); + assert_eq!(types(&got), ["layer.changed"]); + assert_eq!(got[0]["layer"], json!(layer)); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[0]); + + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("events.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + let notices = s.take_plugin_event_notices(); + for id in [all, saves] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "document.saved", "document": doc})], "{id}"); + } + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + assert_ne!(opened, doc); + assert_eq!(given(&mut s, all), [json!({"type": "document.opened", "document": opened})], "a new document's own selection is no change"); + + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": all})); + run(&mut s, "plugin.remove", json!({"id": saves})); +} + +/// A save of a document that closes before the frame's delivery still reaches the plug-in, with +/// the document's number; its selection change does not. So does a save written on another thread +/// that finishes after its document closed. +#[test] +fn a_save_reaches_the_plugin_when_its_document_closes_first() { + let id = "test.events.closed"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed","document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [r.0]})); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-closed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("closed.vectorcraft").to_string_lossy()})); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != doc), "the document closed"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let later = s.doc().unwrap().uid; + let p = json!({"path": dir.join("later.vectorcraft").to_string_lossy()}); + let plan = crate::cmd::fileio::save_plan(&s, crate::cmd::fileio::SaveMode::SaveAs, &p).unwrap(); + let job = crate::cmd::fileio::save_job(&mut s, plan).unwrap(); + job.write(|path, bytes| std::fs::write(path, bytes).map_err(|e| EngineError::Other(e.to_string()))).unwrap(); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != later), "the document closed"); + job.complete(&mut s, later); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": later})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed after a save or a selection change, before the frame's delivery, is given +/// neither; the plug-in installed before is given both, and the next change reaches both. +#[test] +fn a_plugin_installed_before_the_delivery_gets_no_earlier_events() { + let (early, late) = ("test.events.early", "test.events.late"); + let events = r#"["selection.changed","document.saved"]"#; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, early, events, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-late-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("late.vectorcraft").to_string_lossy()})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + install(&mut s, late, events, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let of = |id: &str| -> Vec { notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect() }; + assert_eq!(types(&of(early)), ["document.saved", "selection.changed"]); + assert!(of(late).is_empty(), "{:?}", of(late)); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + for id in [early, late] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": null, "truncated": false})], "{id}"); + } + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// With delivery once a frame, a selection change made after a plug-in was installed, in the same +/// frame, reaches it. +#[test] +fn a_change_after_the_install_in_the_same_frame_reaches_the_plugin() { + let id = "test.events.same_frame"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, a change made to a document created or opened since the last +/// delivery gives its event at the next one; an opened document's `document.opened` comes first, +/// once. +#[test] +fn a_change_to_a_document_opened_since_the_last_delivery_gives_its_event() { + let id = "test.events.new_doc"; + let mut s = session(); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-new-doc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("new-doc.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + install(&mut s, id, r#"["selection.changed","document.opened","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty()); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let created = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": created, "count": 1, "ids": [r.0], "truncated": false})]); + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["document.opened", "layer.changed"], "{got:?}"); + assert_eq!((got[0]["document"].clone(), got[1]["document"].clone(), got[1]["layer"].clone()), (json!(opened), json!(opened), json!(layer))); + assert!(got[1]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[1]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "once"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save waiting for delivery is not given to the same module removed and installed again before +/// the delivery. +#[test] +fn a_module_installed_again_gets_no_event_from_before_its_removal() { + let id = "test.events.again"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-again-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("again.vectorcraft").to_string_lossy()})); + run(&mut s, "plugin.remove", json!({"id": id})); + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one +/// with it lists the selected ids. +#[test] +fn selected_ids_need_doc_read() { + let id = "test.events.noread"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let got = given(&mut s, id); + assert_eq!(got.len(), 1); + assert_eq!((got[0]["count"].clone(), got[0]["ids"].clone()), (json!(2), Value::Null)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, the selection changes of one frame are one event with the selection +/// the frame ended with, and changes that end where they started are none. +#[test] +fn selection_changes_in_one_frame_are_one_event() { + let id = "test.events.burst"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + for ids in [vec![a.0], vec![b.0], vec![], vec![a.0, b.0], vec![b.0]] { + run(&mut s, "select.set", json!({"ids": ids})); + } + assert!(given(&mut s, id).is_empty(), "nothing before the frame"); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"]); + assert_eq!(got[0]["ids"], json!([b.0])); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "back where the frame started"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// `layer.changed` names what changed: a new name is `options`, the same name again is no change, +/// another current layer is `current`, a moved layer `reordered` and a deleted one `deleted`. +#[test] +fn layer_changes_name_their_reasons() { + let id = "test.events.layers"; + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, id, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + let reasons = |s: &mut Session, cmd: &str, p: Value| { + run(s, cmd, p); + given(s, id).iter().map(|e| e["reasons"].clone()).collect::>() + }; + assert_eq!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})), [json!(["options"])]); + assert!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})).is_empty(), "same name, no change"); + assert_eq!(reasons(&mut s, "layer.setCurrent", json!({"id": first.0})), [json!(["current"])]); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [first.0], "target": second.0, "place": "above"})), [json!(["reordered"])]); + let deleted = reasons(&mut s, "layer.delete", json!({"ids": [second.0]})); + assert_eq!(deleted.len(), 1); + assert!(deleted[0].as_array().unwrap().contains(&json!("deleted")), "{deleted:?}"); + + // A sublayer moved past an object beside it is reordered; an object drawn beside it is not. + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let sub = NodeId(run(&mut s, "layer.newSublayer", json!({"parent": first.0, "name": "Sub"}))["id"].as_u64().unwrap()); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let r = rect(&mut s, 10.0); + assert!(given(&mut s, id).is_empty(), "drawing beside a sublayer moves no layer"); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [sub.0], "target": r.0, "place": "above"})), [json!(["reordered"])]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A handler may call a command listed for handlers, and is given its result; one that calls a +/// command that changes the document or the current layer, or a read not listed for handlers, is +/// refused with an error that names the event, and the selection, the current layer and the undo +/// history stay as the user left them. +#[test] +fn a_handler_only_reads() { + let (reads, edits) = ("test.events.reads", "test.events.edits"); + let (unlisted, layers) = ("test.events.unlisted", "test.events.layer"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let other = run(&mut s, "layer.new", json!({"name": "Other"}))["id"].as_u64().unwrap(); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + let expected = run(&mut s, "variable.list", json!({})); + // The read's result, copied with `vc_call_result`, is written as a log line. + let (imports, call) = calling("variable.list", "{}"); + let imports = format!(r#"{imports} (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32)))"#); + let handler = format!( + "(drop {call}) (drop (call $vc_log (i32.const 2) (i32.const 0x4000) (call $vc_call_result (i32.const 0x4000) (i32.const 0x4000)))) (i32.const 0)" + ); + install(&mut s, reads, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["variable.list"]); + assert!(!find_command("addon.cleanup.check").unwrap().journal, "a query the journal does not record"); + let (imports, handler) = calling("addon.cleanup.check", "{}"); + install(&mut s, unlisted, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["addon.cleanup.check"]); + let (imports, handler) = calling("select.all", "{}"); + install(&mut s, edits, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["select.all"]); + let (imports, handler) = calling("layer.setCurrent", &format!(r#"{{"id":{other}}}"#)); + install(&mut s, layers, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["layer.setCurrent"]); + let (undo, rows) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().layer_rows.clone()); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let notices = s.take_plugin_event_notices(); + let read: Vec = notices.iter().filter(|n| n.plugin == reads).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(read, [expected], "the read call succeeds and gives its result: {notices:?}"); + for (id, cmd) in [(unlisted, "addon.cleanup.check"), (edits, "select.all"), (layers, "layer.setCurrent")] { + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + } + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, [a], "the selection the user made"); + assert_eq!((st.active_layer, &st.layer_rows), (Some(first), &rows), "the current layer the user chose"); + assert_eq!(st.history.undo.len(), undo, "no undo step"); + let info = run(&mut s, "plugin.info", json!({"id": edits})); + assert!(info["lastEventError"].as_str().unwrap().contains("only reads"), "{info}"); + assert_eq!(info["eventsOff"], json!(false)); + assert_eq!(info["events"], json!(["selection.changed"])); + run(&mut s, "plugin.remove", json!({"id": reads})); + run(&mut s, "plugin.remove", json!({"id": unlisted})); + run(&mut s, "plugin.remove", json!({"id": edits})); + run(&mut s, "plugin.remove", json!({"id": layers})); +} + +/// A handler that calls a query the journal does not record but that changes the selection (Select +/// All Instances) is refused before the query runs: the document, its revision, selection and undo +/// history, and the session's paint and Appearance state, are as the user left them. +#[test] +fn a_handler_query_that_selects_is_refused_before_it_runs() { + let id = "test.events.selects"; + let (cmd, args) = ("symbol.selectInstances", r#"{"name":"Dot"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let dot = rect(&mut s, 10.0); + run(&mut s, "symbol.new", json!({"name": "Dot", "ids": [dot.0]})); + let b = rect(&mut s, 40.0); + run(&mut s, "select.none", json!({})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [b.0]})); + let st = s.doc().unwrap(); + let (doc, revision, undo) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (paint, appearance, fill_active) = (s.paint.clone(), format!("{:?}", s.active_appearance_item), s.fill_active); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + let st = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert_eq!((st.revision, st.history.undo.len()), (revision, undo), "the same revision and undo history"); + assert_eq!(st.selection.objects, [b], "the selection the user made"); + assert_eq!((&s.paint, format!("{:?}", s.active_appearance_item), s.fill_active), (&paint, appearance, fill_active)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A refused handler call leaves the Appearance panel's active row and the Fill or Stroke in +/// front as the user chose them, also when the query it called selected art. +#[test] +fn a_refused_handler_call_keeps_the_active_appearance_row() { + let id = "test.events.appearance"; + let (cmd, args) = ("addon.cleanup.show", r#"{"kind":"duplicateObjects","scope":"document"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 10.0)); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["layer.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + let fill_active = s.fill_active; + run(&mut s, "layer.new", json!({"name": "Other"})); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a layer.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + assert_eq!(s.doc().unwrap().selection.objects, [a], "the selection the user made"); + assert!(s.active_appearance_item.is_some(), "the active Appearance row"); + assert_eq!(s.fill_active, fill_active); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Module fields that import `vc_call` and hold `cmd` and `args`, and a `vc_event` body that calls +/// `cmd` with `args` and returns what the call returned. +fn calling(cmd: &str, args: &str) -> (String, String) { + let imports = format!( + r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "{}") (data (i32.const 0x2100) "{}")"#, + tpl::string(cmd), + tpl::string(args) + ); + let handler = format!("(call $vc_call (i32.const 0x2000) (i32.const {}) (i32.const 0x2100) (i32.const {}))", cmd.len(), args.len()); + (imports, handler) +} + +/// A handler that fails is reported once; after three failures in a row its events stop for the +/// session, while each selection the user makes stays. +#[test] +fn a_handler_that_keeps_failing_is_turned_off() { + let id = "test.events.failing"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", "unreachable", &[]); + let mut notices = Vec::new(); + for ids in [vec![a.0], vec![b.0], vec![a.0], vec![b.0], vec![a.0]] { + run(&mut s, "select.set", json!({"ids": ids.clone()})); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect::>(), ids, "the user's selection stays"); + notices.extend(s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text)); + } + assert_eq!(notices.len(), 2, "{notices:?}"); + assert!(notices[0].starts_with("its selection.changed handler failed") && notices[0].contains("trapped"), "{}", notices[0]); + assert!(notices[1].contains("after 3 failed handlers in a row"), "{}", notices[1]); + let info = run(&mut s, "plugin.info", json!({"id": id})); + assert_eq!(info["eventsOff"], json!(true)); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/plugins/src/events.rs b/crates/plugins/src/events.rs new file mode 100644 index 0000000000..53a5ad2a2a --- /dev/null +++ b/crates/plugins/src/events.rs @@ -0,0 +1,94 @@ +//! Events a plug-in may react to, from plug-in API level 2 on: its manifest's `events` names them +//! ([`Event`]) and lists the `events` permission, and the module exports +//! `vc_event(event_ptr: i32, event_len: i32) -> i32`. After a change has finished, the host calls +//! `vc_event` in a fresh instance with a small JSON object that names the event and the document +//! ([`crate::Plugin::run_event`]). A handler only reads: the host applies nothing it returns, and +//! a command call that would change a document is refused ([`crate::host`]). +//! +//! The limits are VectorCraft's own values: [`EVENT_FUEL`] instructions and +//! [`EVENT_WALL_TIME_MS`] for one handler, an event of at most [`MAX_EVENT_BYTES`], and +//! [`MAX_EVENT_IDS`] selected ids in a `selection.changed` event. + +/// The plug-in API level that adds `events`, the `events` permission and `vc_event`. +pub const EVENTS_API: u32 = 2; + +/// Instructions one handler may use, or the plug-in's own budget when that is smaller. +pub const EVENT_FUEL: u64 = 5_000_000; + +/// Wall-clock budget of one handler, in milliseconds, or the plug-in's own when that is shorter. +pub const EVENT_WALL_TIME_MS: u64 = 200; + +/// Largest event JSON the host hands a handler, in bytes. +pub const MAX_EVENT_BYTES: usize = 64 * 1024; + +/// Most selected object ids a `selection.changed` event lists; a larger selection sends the first +/// ones with `truncated: true` and its whole `count`. That many ids of the largest value still fit +/// in [`MAX_EVENT_BYTES`]. +pub const MAX_EVENT_IDS: usize = 2048; + +/// Failed handlers in a row after which the host stops calling a plug-in's handler until the app +/// starts again. +pub const MAX_EVENT_FAILURES: u32 = 3; + +/// One thing a plug-in may react to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Event { + /// The selection in a document changed: other objects, anchors or segments, or nothing. + SelectionChanged, + /// A file opened as a document (File › Open, a recent file, New from Template). + DocumentOpened, + /// A document was saved to its own file (Save, Save As). + DocumentSaved, + /// The current layer changed, or a layer was added, deleted, moved or given other options. + LayerChanged, +} + +impl Event { + /// Every event, in the order the docs list them. + pub const ALL: [Event; 4] = [Event::SelectionChanged, Event::DocumentOpened, Event::DocumentSaved, Event::LayerChanged]; + + /// Its name in a manifest's `events`, which is also the event's `type`. + pub fn name(self) -> &'static str { + match self { + Event::SelectionChanged => "selection.changed", + Event::DocumentOpened => "document.opened", + Event::DocumentSaved => "document.saved", + Event::LayerChanged => "layer.changed", + } + } + + /// The event named `name`. + pub fn parse(name: &str) -> Option { + Event::ALL.into_iter().find(|e| e.name() == name) + } + + /// Whether the event is still delivered when its document has closed before the delivery: + /// an open or a save is, a selection or layer change is not. + pub fn outlives_document(self) -> bool { + matches!(self, Event::DocumentOpened | Event::DocumentSaved) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_round_trip() { + for e in Event::ALL { + assert_eq!(Event::parse(e.name()), Some(e)); + } + assert_eq!(Event::parse("selection.change"), None); + assert_eq!(Event::parse(""), None); + } + + /// A `selection.changed` event that lists the most ids, each of the largest value, fits in the + /// largest event a handler is given. + #[test] + fn the_largest_selection_event_fits() { + let ids = vec![u64::MAX; MAX_EVENT_IDS]; + let event = serde_json::json!({"type": "selection.changed", "document": u64::MAX, "count": u64::MAX, "ids": ids, "truncated": true}); + let len = serde_json::to_vec(&event).unwrap().len(); + assert!(len <= MAX_EVENT_BYTES, "{len} bytes"); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..a77f243efb 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -31,12 +31,14 @@ //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host -//! runs through `vc_run` with the command's id in `_context`. +//! runs through `vc_run` with the command's id in `_context`. Any kind may also react to the +//! [`events`] its manifest names, through `vc_event`, without changing the document. #![forbid(unsafe_code)] pub mod deferred; pub mod dialog; pub mod effect; +pub mod events; pub mod export; pub mod host; pub mod import; @@ -51,6 +53,7 @@ pub mod storage; pub mod wat; pub use dialog::ParamUi; +pub use events::Event; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..493e0a3b63 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; +use crate::events::{EVENTS_API, Event}; use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; use crate::{Error, Result}; @@ -348,6 +349,11 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// The events it reacts to, by [`Event::name`]: only a module at `api` 2 or later whose + /// `permissions` list `events` lists any, and it exports `vc_event` ([`crate::events`]). Left + /// out or empty, it reacts to none. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "event_names")] + pub events: Vec, } impl Manifest { @@ -383,6 +389,7 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + events: Vec::new(), } } @@ -440,7 +447,42 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_events() + } + + /// `events` names each [`Event`] at most once, and a list needs `api` 2 or later and the + /// permission `events`, which needs a list. + fn validate_events(&self) -> Result<()> { + for (i, name) in self.events.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if Event::parse(name).is_none() { + return Err(Error::Manifest(format!( + "`events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed" + ))); + } + if self.events.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`events` lists `{shown}` twice"))); + } + } + let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Events.name())); + if self.events.is_empty() == listed { + return Err(Error::Manifest("`events` needs the permission `events`, and `events` needs a list of `events`".into())); + } + if listed && self.api < EVENTS_API { + return Err(Error::Manifest(format!("`events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API}"))); + } + Ok(()) + } + + /// The events it reacts to (`events`). + pub fn event_kinds(&self) -> Vec { + self.events.iter().filter_map(|n| Event::parse(n)).collect() + } + + /// Does it react to `event`? + pub fn reacts_to(&self, event: Event) -> bool { + self.events.iter().any(|n| n == event.name()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids @@ -733,6 +775,17 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`events` must be a list of event names, such as selection.changed"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads the `commands` list one entry at a time from the manifest itself, so each command's /// `params` keep their declaration order and a repeated parameter is refused. A malformed entry /// is an error that names it (its id when the id comes before the fault, otherwise its place in @@ -1394,6 +1447,52 @@ mod tests { assert!(Manifest::parse(manifest(MAX_PARAMS + 1, MAX_PARAMS).as_bytes()).is_err(), "too many in all"); } + /// Any kind at `api` 2 that lists the permission `events` names the events it reacts to; an + /// unknown or repeated name, a list without the permission or the permission without a list, + /// and a list at `api` 1 are refused, and the error names the fault. + #[test] + fn events_are_listed_with_their_permission_at_api_2() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","selection.changed"]}"#, + ) + .unwrap(); + assert_eq!(m.event_kinds(), [Event::LayerChanged, Event::SelectionChanged]); + assert!(m.reacts_to(Event::SelectionChanged) && !m.reacts_to(Event::DocumentSaved)); + assert_eq!(m.permissions(), [Permission::Events]); + assert_eq!(serde_json::to_value(&m).unwrap()["events"], json!(["layer.changed", "selection.changed"])); + let effect = + br#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","events"],"events":["document.saved"]}"#; + assert_eq!(Manifest::parse(effect).unwrap().event_kinds(), [Event::DocumentSaved]); + let importer = + br#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["q"],"permissions":["import.read","events"],"events":["document.opened"]}"#; + assert!(Manifest::parse(importer).is_ok()); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","events":null}"#).unwrap(); + assert!(plain.events.is_empty() && serde_json::to_value(&plain).unwrap().get("events").is_none()); + for (bad, says) in [ + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["selection.change"]}"#, + "unknown event `selection.change`", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","layer.changed"]}"#, + "lists `layer.changed` twice", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"events":["layer.changed"]}"#, "needs the permission `events`"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"events":["layer.changed"]}"#, + "needs the permission `events`", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","permissions":["events"],"events":["layer.changed"]}"#, "needs plug-in API level 2"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":"layer.changed"}"#, "must be a list"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[1]}"#, "must be a list"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + #[test] fn rejects_bad_manifests() { for bad in [ diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..01a0d00b3a 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -7,7 +7,8 @@ //! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of //! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`, //! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a -//! manifest lists them. +//! manifest lists them. Nor is `events`, which lets a plug-in of any kind react to the events its +//! manifest names ([`crate::events`]). use serde::{Deserialize, Serialize}; @@ -74,10 +75,14 @@ pub enum Permission { /// ([`crate::host::IMPORTS`]): a filter only. #[serde(rename = "commands")] Commands, + /// Run on its own after the changes its manifest's `events` names ([`crate::events`]), with + /// `vc_event`: any kind. + #[serde(rename = "events")] + Events, } /// Every permission this host grants, in the order prompts list them. -pub const ALL: [Permission; 10] = [ +pub const ALL: [Permission; 11] = [ Permission::DocRead, Permission::DocWrite, Permission::State, @@ -88,6 +93,7 @@ pub const ALL: [Permission; 10] = [ Permission::Settings, Permission::Cache, Permission::Commands, + Permission::Events, ]; /// The permissions of the host imports, which any kind may list and none implies; each needs plug-in @@ -109,6 +115,7 @@ impl Permission { Permission::Settings => "settings", Permission::Cache => "cache", Permission::Commands => "commands", + Permission::Events => "events", } } @@ -130,13 +137,14 @@ impl Permission { Permission::Settings => "Keep settings of its own", Permission::Cache => "Keep a cache of its own, which you can clear", Permission::Commands => "Run these commands", + Permission::Events => "Run on its own when the selection, a document or a layer changes", } } /// May a plug-in of `kind` that declares `commands` or not list it: one [`Permission::allowed`] - /// gives it, or one of the host imports' ([`HOST`]), which any kind may list. + /// gives it, one of the host imports' ([`HOST`]) or `events`, which any kind may list. pub fn applies(self, kind: Kind, commands: bool) -> bool { - HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) + self == Permission::Events || HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) } /// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 7c4262dd4e..699fe15161 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -219,6 +219,9 @@ fn wasm_err(e: wasmi::Error) -> Error { /// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error). type RunArgs = (i32, i32, i32, i32); +/// `vc_event(event_ptr, event_len) -> 0` (anything else: the handler failed). +type EventArgs = (i32, i32); + impl Plugin { /// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and /// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`]) @@ -269,6 +272,9 @@ impl Plugin { // The other exports must exist with the right types. live.func::("vc_alloc")?; live.func::("vc_run")?; + if !p.manifest.events.is_empty() { + live.func::("vc_event")?; + } Ok(p) } @@ -315,13 +321,19 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + self.instantiate_with(run, granted, report, self.limits.fuel_base) + } + + /// [`Plugin::instantiate`] with the start function given at most `start_fuel` instructions; + /// the instance's store holds what it left. + fn instantiate_with(&self, run: Run, granted: &[Permission], report: &mut Report, start_fuel: u64) -> Result { let limits = StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build(); let mut store = Store::new(&self.engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. - store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; + store.set_fuel(start_fuel.min(FUEL_SLICE)).map_err(wasm_err)?; let linker = host::linker(&self.engine, granted); let instance = match linker.instantiate_and_start(&mut store, &self.module) { Ok(instance) => instance, @@ -360,16 +372,34 @@ impl Plugin { params: P, fuel: u64, deadline: &Deadline, + bridge: Option<&mut Bridge<'_>>, + ) -> Result { + let mut budget = fuel; + self.call_budget(live, f, params, &mut budget, deadline, bridge) + } + + /// [`Plugin::call_with`] on at most `budget` instructions, which holds what the call left + /// unused when it returns `Ok`, for the next call to share. + fn call_budget( + &self, + live: &mut Live, + f: &TypedFunc, + params: P, + budget: &mut u64, + deadline: &Deadline, mut bridge: Option<&mut Bridge<'_>>, ) -> Result { - let mut left = fuel; + let mut left = *budget; let give = left.min(FUEL_SLICE); left -= give; live.store.set_fuel(give).map_err(wasm_err)?; let mut call = slice(live, &mut left, |store| f.call_resumable(store, params))?; loop { match call { - TypedResumableCall::Finished(r) => return Ok(r), + TypedResumableCall::Finished(r) => { + *budget = left.saturating_add(live.store.get_fuel().map_err(wasm_err)?); + return Ok(r); + } TypedResumableCall::HostTrap(inv) => { if inv.host_error().downcast_ref::().is_some() { return Err(stop_reason(&mut live.store)); @@ -505,4 +535,72 @@ impl Plugin { } live.read_packed(packed, "the output", limits.max_output_bytes) } + + /// Its limits for one event handler: at most [`crate::events::EVENT_FUEL`] instructions and + /// [`crate::events::EVENT_WALL_TIME_MS`], or its own budgets when they are smaller, and every + /// other limit as it is. + pub fn event_limits(&self) -> Limits { + Limits { + fuel_base: self.limits.fuel_base.min(crate::events::EVENT_FUEL), + wall_time_ms: self.limits.wall_time_ms.min(crate::events::EVENT_WALL_TIME_MS), + ..self.limits.clone() + } + } + + /// Calls `vc_event` with `event` (the event JSON) in a fresh instance under + /// [`Plugin::event_limits`] → `Ok` when it returned 0, and what it reported through the host + /// imports. With `bridge`, each `vc_call` of a command its `commandAllowlist` names is made with + /// it; a failed call fails the handler. A module that doesn't react to events, an event past + /// [`crate::events::MAX_EVENT_BYTES`] and Safe Mode run nothing. + pub fn run_event(&self, event: &[u8], bridge: Option<&mut Bridge<'_>>) -> (Result<()>, Report) { + let mut report = Report::default(); + if let Err(e) = crate::safe_mode::check() { + return (Err(e), report); + } + if self.manifest.events.is_empty() { + return (Err(Error::Abi("the module reacts to no events".into())), report); + } + if event.len() > crate::events::MAX_EVENT_BYTES { + let (len, max) = (event.len(), crate::events::MAX_EVENT_BYTES); + return (Err(Error::Limit(format!("event size ({len} bytes, limit {max})"))), report); + } + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.event_inner(event, &mut report, bridge))); + (run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report) + } + + fn event_inner(&self, event: &[u8], report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result<()> { + let limits = self.event_limits(); + let deadline = Deadline::new(limits.wall_time_ms); + let m = &self.manifest; + let run = Run::new(&m.id, false, true, deadline).with_storage(crate::registry::storage(&m.id)); + let mut live = self.instantiate_with(run, &m.permissions(), report, limits.fuel_base)?; + // The start function, `vc_alloc` and `vc_event` share the one budget. + let mut budget = live.store.get_fuel().map_err(wasm_err)?; + if bridge.is_some() { + live.store.data_mut().run.allow_calls(m.command_allowlist.clone()); + } + let out = (|| { + let alloc: TypedFunc = live.func("vc_alloc")?; + let handler: TypedFunc = live.func("vc_event")?; + let ptr = self.call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize; + if ptr == 0 { + return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into())); + } + let outside = || Error::Abi("vc_alloc returned a block outside memory".into()); + let end = ptr.checked_add(event.len()).ok_or_else(outside)?; + live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event); + let code = self.call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?; + deadline.check()?; + if code != 0 { + return Err(Error::Failed(format!("vc_event returned {code}"))); + } + Ok(()) + })(); + let state = &mut live.store.data_mut().run; + *report = std::mem::take(&mut state.report); + match (state.call_failure.take(), out) { + (Some(e), _) => Err(e), + (None, out) => out, + } + } } diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index 936d5d9e53..a1348242d7 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -34,6 +34,18 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { /// A `vc_run` body returning the input unchanged. pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))"; +/// A plug-in that reacts to events ([`crate::events`]): `manifest` (JSON that lists `events`), the +/// module fields `imports` before the others, a `vc_event` whose body is `handler` (parameters +/// `$ep $el`, result i32) and a `vc_run` that returns its input. +pub fn reacting(manifest: &str, imports: &str, handler: &str) -> String { + let extra = format!(r#"{imports} (func (export "vc_event") (param $ep i32) (param $el i32) (result i32) {handler})"#); + module(manifest, ECHO, &extra, 1) +} + +/// A `vc_event` body that writes the event it is given as an information log line (with +/// [`HOST_IMPORTS`]) and returns 0. +pub const LOG_EVENT: &str = "(drop (call $vc_log (i32.const 2) (local.get $ep) (local.get $el))) (i32.const 0)"; + /// A plug-in that always returns `output` (whatever it is given). pub fn returning(manifest: &str, output: &str) -> String { then_returning(manifest, "", output) diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index f4cb2e103b..bb28afd450 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1025,6 +1025,79 @@ fn a_plugin_reaches_only_its_own_storage() { registry::set_storage("test.storage.theirs", None); } +/// The manifest of an event plug-in `id` that writes log lines and reacts to `events` (JSON list). +fn reacting_manifest(id: &str, events: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#) +} + +/// A module that lists `events` needs a `vc_event` export of the right type; one that lists none +/// may leave it out. +#[test] +fn an_event_plugin_exports_vc_event() { + let manifest = reacting_manifest("test.events.export", r#"["selection.changed"]"#); + let e = Plugin::load(&build(&tpl::reporting(&manifest, "", INPUT)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let wrong = format!(r#"{} (func (export "vc_event") (param i32) (result i32) (i32.const 0))"#, tpl::HOST_IMPORTS); + let e = Plugin::load(&build(&tpl::module(&manifest, tpl::ECHO, &wrong, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok()); + assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event"); +} + +/// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a +/// handler past its instruction budget fail it. A module without events runs no handler. +#[test] +fn vc_event_is_given_the_event_and_its_code_is_checked() { + let manifest = reacting_manifest("test.events.run", r#"["layer.changed"]"#); + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).unwrap(); + let event = br#"{"type":"layer.changed","document":7}"#; + let (r, report) = p.run_event(event, None); + r.unwrap(); + assert_eq!(report.lines.iter().map(|l| l.text.as_str()).collect::>(), [std::str::from_utf8(event).unwrap()]); + for (handler, says) in [ + ("(i32.const 3)", "vc_event returned 3"), + ("unreachable", "trapped"), + // The instruction budget, or the time budget on a loaded machine. + ("(loop $l (br $l)) (i32.const 0)", "budget"), + ] { + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)), Limits::default()).unwrap(); + let e = p.run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains(says), "{handler}: {e}"); + } + let e = p.run_event(&vec![b' '; vectorcraft_plugins::events::MAX_EVENT_BYTES + 1], None).0.unwrap_err(); + assert!(e.to_string().contains("event size"), "{e}"); + let plain = Plugin::load(&ok_module(tpl::ECHO), Limits::default()).unwrap(); + assert!(plain.run_event(event, None).0.is_err()); + let limits = p.event_limits(); + assert_eq!((limits.fuel_base, limits.wall_time_ms), (vectorcraft_plugins::events::EVENT_FUEL, vectorcraft_plugins::events::EVENT_WALL_TIME_MS)); +} + +/// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the +/// handler alone fits it no longer when the start function has done as much first. +#[test] +fn a_handler_and_its_start_function_share_the_event_budget() { + let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#); + let burn = r#"(func $burn (param $k i32) (block $b (loop $l + (br_if $b (i32.eqz (local.get $k))) + (local.set $k (i32.sub (local.get $k) (i32.const 1))) + (br $l))))"#; + let plugin = |start: u32, handler: u32| { + let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS); + let body = format!("(call $burn (i32.const {handler})) (i32.const 0)"); + Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits::default()).unwrap() + }; + let event = br#"{"type":"layer.changed","document":1}"#; + // The most loop turns, doubling, that fit the budget in the handler alone: twice as many don't. + let mut k = 1u32 << 16; + while plugin(0, k * 2).run_event(event, None).0.is_ok() { + k *= 2; + assert!(k < 1 << 30, "a handler that never runs out of its budget"); + } + assert!(plugin(0, k).run_event(event, None).0.is_ok()); + let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains("budget"), "{e}"); +} + /// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped /// and reported. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..79296d8b40 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -55,6 +55,9 @@ impl VectorcraftApp { session.place_cursor_requests = true; // A script runs a slice per frame, so the window keeps drawing and Stop can be pressed. session.script_frames = true; + // Plug-in events are delivered by the frame: after the work that finished in the + // background, and at the end of the UI pass ([`VectorcraftApp::deliver_plugin_events`]). + session.plugin_event_frames = true; let views = session.documents().iter().map(View::of).collect(); let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); @@ -270,6 +273,25 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + let _ = self.deliver_plugin_events(); + } + + /// Hands the plug-ins that react to events the changes of this frame + /// ([`vectorcraft_engine::Session::deliver_plugin_events`]). The last warning or error a handler + /// wrote, or the last handler failure, shows in the status bar after the plug-in's name. → Whether + /// the status bar shows one. + fn deliver_plugin_events(&mut self) -> bool { + self.session.deliver_plugin_events(); + let shown = self + .session + .take_plugin_event_notices() + .into_iter() + .rev() + .find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn)); + let Some(n) = shown else { return false }; + let name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + self.status(format!("{name}: {}", n.text)); + true } /// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a @@ -362,8 +384,14 @@ impl VectorcraftApp { // them, even if the worker below finishes them during this same tick. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending())); screen_color::poll(self, ctx); + let script_was_running = self.session.script_running(); self.poll_finished_work(); crate::script_runs::poll(self); + if script_was_running && !self.session.script_running() { + // The work that waited for the script, and the plug-in events its changes give, are + // taken in the frame it ended in: no repaint is asked for once it has ended. + self.poll_finished_work(); + } // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); @@ -670,6 +698,12 @@ impl VectorcraftApp { // A command run by a menu, panel or dialog in this pass may have queued its text copy // after the UI phase's input flush. Publish it now for the same reason as there. self.flush_clipboard_out(&ctx); + // What the canvas, a panel or a dialog changed in this pass reaches the plug-ins that react + // to it now, since an idle app draws no further frame; a line a handler wrote shows in the + // next one. + if !self.session.script_running() && self.deliver_plugin_events() { + ctx.request_repaint(); + } if opening::long_operation_busy(self) { ctx.set_cursor_icon(egui::CursorIcon::Progress); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..0f4fb39940 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -720,6 +720,7 @@ impl PluginIntField { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + events: Vec::new(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..4014b51fc8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6690,6 +6690,7 @@ axis Y Axis Y ос Show its progress, see Cancel and write log lines Показване на напредъка, разпознаване на отказ и записване на редове в дневника Keep settings of its own Съхраняване на собствени настройки Keep a cache of its own, which you can clear Съхраняване на собствен кеш, който можете да изчистите + Run on its own when the selection, a document or a layer changes Изпълняване самостоятелно, когато се промени селекцията, документ или слой Run these commands on the document: {ids} Изпълняване на тези команди върху документа: {ids} Clear Plug-in Cache Изчистване на кеша на добавката # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..84fecd5884 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6718,6 +6718,7 @@ axis Y Axis Y osa Show its progress, see Cancel and write log lines Prikazati napredak, prepoznati otkazivanje i zapisivati redove dnevnika Keep settings of its own Čuvati vlastite postavke Keep a cache of its own, which you can clear Čuvati vlastitu predmemoriju koju možete očistiti + Run on its own when the selection, a document or a layer changes Pokretati se samostalno kada se promijeni odabir, dokument ili sloj Run these commands on the document: {ids} Izvršavati ove naredbe na dokumentu: {ids} Clear Plug-in Cache Očisti predmemoriju dodatka @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} dozvola `{permission}` zahtijeva nivo API-ja dodataka {PROGRESS_API}: navedite `api` {PROGRESS_API} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..f2a186f792 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7842,6 +7842,7 @@ variable-list-end {0}, {1} {0} i {1} Show its progress, see Cancel and write log lines Mostrar el progrés, detectar la cancel·lació i escriure línies de registre Keep settings of its own Desar una configuració pròpia Keep a cache of its own, which you can clear Desar una memòria cau pròpia, que podeu buidar + Run on its own when the selection, a document or a layer changes Executar-se per si sol quan canvia la selecció, un document o una capa Run these commands on the document: {ids} Executar aquestes ordres al document: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» inclou `{id}` a `commandAllowlist`, que un complement no pot cridar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7873,6 +7874,15 @@ variable-list-end {0}, {1} {0} i {1} @msg only a filter declares `inputs` només un filtre declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades +@msg `events` lists `{shown}` twice `events` inclou `{shown}` dues vegades +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anomena un esdeveniment desconegut `{shown}`: feu servir selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necessita el nivell d’API de complements {EVENTS_API}: indiqueu `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necessita el permís `events`, i `events` necessita una llista d’`events` +@msg event size ({len} bytes, limit {max}) mida de l’esdeveniment ({len} bytes, límit {max}) +@msg the module reacts to no events el mòdul no reacciona a cap esdeveniment +@msg vc_event returned {code} vc_event ha retornat {code} +@msg {name}: its {event} handler failed: {e} {name}: el seu gestor de {event} ha fallat: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: els seus esdeveniments estan desactivats fins que VectorCraft torni a iniciar-se, després de {count} gestors fallits seguits @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) pressupost de memòria (l’objecte {_1} necessita {size} bytes d’entrada, en queden {left}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..394d8b42a7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7452,6 +7452,7 @@ axis Y Axis osa Y Show its progress, see Cancel and write log lines Zobrazit průběh, rozpoznat zrušení a zapisovat řádky protokolu Keep settings of its own Uchovávat vlastní nastavení Keep a cache of its own, which you can clear Uchovávat vlastní mezipaměť, kterou můžete vymazat + Run on its own when the selection, a document or a layer changes Spouštět se samostatně, když se změní výběr, dokument nebo vrstva Run these commands on the document: {ids} Spouštět v dokumentu tyto příkazy: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ uvádí v `commandAllowlist` příkaz `{id}`, který zásuvný modul nesmí volat @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7483,6 +7484,15 @@ axis Y Axis osa Y @msg only a filter declares `inputs` `inputs` deklaruje pouze filtr @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát +@msg `events` lists `{shown}` twice `events` uvádí `{shown}` dvakrát +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` uvádí neznámou událost `{shown}`: použijte selection.changed, document.opened, document.saved nebo layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vyžaduje úroveň API zásuvných modulů {EVENTS_API}: uveďte `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potřebuje oprávnění `events` a `events` potřebuje seznam `events` +@msg event size ({len} bytes, limit {max}) velikost události ({len} bajtů, limit {max}) +@msg the module reacts to no events modul nereaguje na žádné události +@msg vc_event returned {code} vc_event vrátila {code} +@msg {name}: its {event} handler failed: {e} {name}: jeho obslužná rutina {event} selhala: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jeho události jsou vypnuté, dokud se VectorCraft znovu nespustí, po {count} neúspěšných obslužných rutinách za sebou @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) rozpočet paměti (objekt {_1} potřebuje {size} bajtů vstupu, zbývá {left}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..b8415a4299 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -695,6 +695,15 @@ liquify-list-end {0}, {1} {0} og {1} @msg only a filter declares `inputs` kun et filter angiver `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange +@msg `events` lists `{shown}` twice `events` angiver `{shown}` to gange +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` angiver en ukendt hændelse `{shown}`: brug selection.changed, document.opened, document.saved eller layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kræver plug-in-API-niveau {EVENTS_API}: angiv `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` kræver tilladelsen `events`, og `events` kræver en liste `events` +@msg event size ({len} bytes, limit {max}) hændelsesstørrelse ({len} byte, grænse {max}) +@msg the module reacts to no events modulet reagerer ikke på nogen hændelser +@msg vc_event returned {code} vc_event returnerede {code} +@msg {name}: its {event} handler failed: {e} {name}: dens {event}-handler mislykkedes: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dens hændelser er slået fra, indtil VectorCraft starter igen, efter {count} mislykkede handlere i træk @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage) @@ -9609,6 +9618,7 @@ axis Y Axis Y-akse Show its progress, see Cancel and write log lines Vise sin fremdrift, se en annullering og skrive logrækker Keep settings of its own Gemme sine egne indstillinger Keep a cache of its own, which you can clear Gemme sin egen cache, som du kan rydde + Run on its own when the selection, a document or a layer changes Køre af sig selv, når markeringen, et dokument eller et lag ændres Run these commands on the document: {ids} Køre disse kommandoer på dokumentet: {ids} Clear Plug-in Cache Ryd plug-in-cache # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..99a8424807 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7035,6 +7035,7 @@ axis Y Axis Y-Achse Show its progress, see Cancel and write log lines Den Fortschritt anzeigen, ein Abbrechen erkennen und Protokollzeilen schreiben Keep settings of its own Eigene Einstellungen speichern Keep a cache of its own, which you can clear Einen eigenen Cache anlegen, den Sie leeren können + Run on its own when the selection, a document or a layer changes Von selbst ausgeführt werden, wenn sich die Auswahl, ein Dokument oder eine Ebene ändert Run these commands on the document: {ids} Diese Befehle im Dokument ausführen: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ führt `{id}` in `commandAllowlist` auf, den ein Plug-in nicht aufrufen darf @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7066,6 +7067,15 @@ axis Y Axis Y-Achse @msg only a filter declares `inputs` nur ein Filter deklariert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf +@msg `events` lists `{shown}` twice `events` führt `{shown}` doppelt auf +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nennt ein unbekanntes Ereignis `{shown}`: verwenden Sie selection.changed, document.opened, document.saved oder layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` braucht die Plug-in-API-Stufe {EVENTS_API}: Geben Sie `api` {EVENTS_API} an +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` braucht die Berechtigung `events`, und `events` braucht eine Liste `events` +@msg event size ({len} bytes, limit {max}) Ereignisgröße ({len} Byte, Grenze {max}) +@msg the module reacts to no events das Modul reagiert auf keine Ereignisse +@msg vc_event returned {code} vc_event hat {code} zurückgegeben +@msg {name}: its {event} handler failed: {e} {name}: sein Handler für {event} ist fehlgeschlagen: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seine Ereignisse sind aus, bis VectorCraft neu startet, nach {count} fehlgeschlagenen Handlern in Folge @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) Speicherbudget (Objekt {_1} benötigt {size} Byte Eingabe, {left} verbleiben) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..34be251bb2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7442,6 +7442,7 @@ axis Y Axis Άξονας Y Show its progress, see Cancel and write log lines Εμφάνιση της προόδου, αναγνώριση της ακύρωσης και εγγραφή γραμμών καταγραφής Keep settings of its own Διατήρηση δικών του ρυθμίσεων Keep a cache of its own, which you can clear Διατήρηση δικής του κρυφής μνήμης, την οποία μπορείτε να εκκαθαρίσετε + Run on its own when the selection, a document or a layer changes Εκτέλεση από μόνο του όταν αλλάζει η επιλογή, ένα έγγραφο ή ένα επίπεδο Run these commands on the document: {ids} Εκτέλεση αυτών των εντολών στο έγγραφο: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call το «{name}» αναφέρει το `{id}` στο `commandAllowlist`, το οποίο ένα πρόσθετο δεν επιτρέπεται να καλέσει @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7473,6 +7474,15 @@ axis Y Axis Άξονας Y @msg only a filter declares `inputs` μόνο ένα φίλτρο δηλώνει `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance το `inputs` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές +@msg `events` lists `{shown}` twice το `events` αναφέρει το `{shown}` δύο φορές +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed το `events` αναφέρει άγνωστο συμβάν `{shown}`: χρησιμοποιήστε selection.changed, document.opened, document.saved ή layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} το `events` χρειάζεται το επίπεδο API προσθέτων {EVENTS_API}: δώστε `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` το `events` χρειάζεται το δικαίωμα `events`, και το `events` χρειάζεται μια λίστα `events` +@msg event size ({len} bytes, limit {max}) μέγεθος συμβάντος ({len} byte, όριο {max}) +@msg the module reacts to no events η λειτουργική μονάδα δεν αντιδρά σε κανένα συμβάν +@msg vc_event returned {code} η vc_event επέστρεψε {code} +@msg {name}: its {event} handler failed: {e} {name}: ο χειριστής {event} του απέτυχε: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: τα συμβάντα του είναι απενεργοποιημένα μέχρι να ξεκινήσει ξανά το VectorCraft, μετά από {count} αποτυχημένους χειριστές στη σειρά @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) προϋπολογισμός μνήμης (το αντικείμενο {_1} χρειάζεται {size} byte εισόδου, απομένουν {left}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..3e8a481554 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7428,6 +7428,7 @@ axis Y Axis Eje Y Show its progress, see Cancel and write log lines Mostrar su progreso, detectar la cancelación y escribir líneas de registro Keep settings of its own Guardar una configuración propia Keep a cache of its own, which you can clear Guardar una caché propia, que usted puede vaciar + Run on its own when the selection, a document or a layer changes Ejecutarse por sí solo cuando cambia la selección, un documento o una capa Run these commands on the document: {ids} Ejecutar estos comandos en el documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” incluye `{id}` en `commandAllowlist`, que un plugin no puede llamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7459,6 +7460,15 @@ axis Y Axis Eje Y @msg only a filter declares `inputs` solo un filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces +@msg `events` lists `{shown}` twice `events` incluye `{shown}` dos veces +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nombra un evento desconocido `{shown}`: use selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necesita el nivel de API de plugins {EVENTS_API}: indique `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necesita el permiso `events`, y `events` necesita una lista de `events` +@msg event size ({len} bytes, limit {max}) tamaño del evento ({len} bytes, límite {max}) +@msg the module reacts to no events el módulo no reacciona a ningún evento +@msg vc_event returned {code} vc_event devolvió {code} +@msg {name}: its {event} handler failed: {e} {name}: su controlador de {event} falló: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sus eventos están desactivados hasta que VectorCraft se inicie de nuevo, tras {count} controladores fallidos seguidos @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) presupuesto de memoria (el objeto {_1} necesita {size} bytes de entrada, quedan {left}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..8324910fae 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7519,6 +7519,7 @@ axis Y Axis Y-akseli Show its progress, see Cancel and write log lines Näyttää edistymisensä, havaita peruutuksen ja kirjoittaa lokirivejä Keep settings of its own Säilyttää omat asetuksensa Keep a cache of its own, which you can clear Säilyttää oman välimuistin, jonka voit tyhjentää + Run on its own when the selection, a document or a layer changes Käynnistyä itsestään, kun valinta, asiakirja tai taso muuttuu Run these commands on the document: {ids} Suorittaa nämä komennot asiakirjassa: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” luettelee `commandAllowlist`-luettelossa komennon `{id}`, jota laajennus ei saa kutsua @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7550,6 +7551,15 @@ axis Y Axis Y-akseli @msg only a filter declares `inputs` vain suodatin voi määrittää `inputs`-avaimen @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti +@msg `events` lists `{shown}` twice `events` luettelee kohteen `{shown}` kahdesti +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nimeää tuntemattoman tapahtuman `{shown}`: käytä arvoa selection.changed, document.opened, document.saved tai layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vaatii laajennus-API:n tason {EVENTS_API}: anna `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` tarvitsee käyttöoikeuden `events`, ja `events` tarvitsee `events`-luettelon +@msg event size ({len} bytes, limit {max}) tapahtuman koko ({len} tavua, raja {max}) +@msg the module reacts to no events moduuli ei reagoi mihinkään tapahtumaan +@msg vc_event returned {code} vc_event palautti {code} +@msg {name}: its {event} handler failed: {e} {name}: sen {event}-käsittelijä epäonnistui: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sen tapahtumat ovat pois päältä, kunnes VectorCraft käynnistyy uudelleen, {count} peräkkäin epäonnistuneen käsittelijän jälkeen @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) muistibudjetti (objekti {_1} tarvitsee {size} tavua syötettä, jäljellä {left}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..84b857b264 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7448,6 +7448,7 @@ axis Y Axis Axe Y Show its progress, see Cancel and write log lines Afficher sa progression, détecter l’annulation et écrire des lignes de journal Keep settings of its own Conserver ses propres réglages Keep a cache of its own, which you can clear Conserver son propre cache, que vous pouvez vider + Run on its own when the selection, a document or a layer changes S’exécuter de lui-même quand la sélection, un document ou un calque change Run these commands on the document: {ids} Exécuter ces commandes sur le document : {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call « {name} » indique `{id}` dans `commandAllowlist`, qu’un module externe ne peut pas appeler @msg vc_call `{shown}`: {why} vc_call `{shown}` : {why} @@ -7480,6 +7481,15 @@ axis Y Axis Axe Y @msg only a filter declares `inputs` seul un filtre déclare `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois +@msg `events` lists `{shown}` twice `events` mentionne `{shown}` deux fois +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` désigne un événement inconnu `{shown}`, utilisez selection.changed, document.opened, document.saved ou layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` nécessite le niveau d’API de module externe {EVENTS_API}, indiquez `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` a besoin de l’autorisation `events`, et `events` a besoin d’une liste `events` +@msg event size ({len} bytes, limit {max}) taille de l’événement ({len} octets, limite {max}) +@msg the module reacts to no events le module ne réagit à aucun événement +@msg vc_event returned {code} vc_event a renvoyé {code} +@msg {name}: its {event} handler failed: {e} {name} : son gestionnaire {event} a échoué : {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name} : ses événements sont désactivés jusqu’au prochain démarrage de VectorCraft, après {count} gestionnaires en échec d’affilée @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget mémoire (l’objet {_1} nécessite {size} octets d’entrée, il en reste {left}) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..69e14c4fd3 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2023,6 +2023,7 @@ Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો Keep a cache of its own, which you can clear તેનું પોતાનું કેશ રાખો, જે તમે સાફ કરી શકો છો + Run on its own when the selection, a document or a layer changes પસંદગી, દસ્તાવેજ અથવા લેયર બદલાય ત્યારે આપમેળે ચાલો Keep a link to an image file instead of only embedding it ઇમેજ ફાઇલને ફક્ત એમ્બેડ કરવાને બદલે તેની લિંક રાખો Keep both sides the same width બંને બાજુ સમાન પહોળાઈ રાખો Keep data of its own with the document દસ્તાવેજ સાથે પોતાનો ડેટા રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..e068bda2aa 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6636,6 +6636,7 @@ arrowhead Feather पंख Show its progress, see Cancel and write log lines अपनी प्रगति दिखाना, रद्द करने का अनुरोध देखना और लॉग पंक्तियाँ लिखना Keep settings of its own अपनी सेटिंग्स रखना Keep a cache of its own, which you can clear अपना कैश रखना, जिसे आप साफ़ कर सकते हैं + Run on its own when the selection, a document or a layer changes सिलेक्शन, कोई डॉक्यूमेंट या कोई लेयर बदलने पर अपने आप चलना Run these commands on the document: {ids} दस्तावेज़ पर ये कमांड चलाना: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” `commandAllowlist` में `{id}` सूचीबद्ध करता है, जिसे कोई प्लग-इन कॉल नहीं कर सकता @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -6667,6 +6668,15 @@ arrowhead Feather पंख @msg only a filter declares `inputs` केवल फ़िल्टर `inputs` घोषित करता है @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है +@msg `events` lists `{shown}` twice `events` में `{shown}` दो बार सूचीबद्ध है +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` में अज्ञात इवेंट `{shown}` है: selection.changed, document.opened, document.saved या layer.changed का उपयोग करें +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` के लिए प्लग-इन API स्तर {EVENTS_API} चाहिए: `api` {EVENTS_API} दें +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` को `events` अनुमति चाहिए, और `events` को `events` की सूची चाहिए +@msg event size ({len} bytes, limit {max}) इवेंट का आकार ({len} बाइट्स, सीमा {max}) +@msg the module reacts to no events मॉड्यूल किसी भी इवेंट पर प्रतिक्रिया नहीं करता +@msg vc_event returned {code} vc_event ने {code} लौटाया +@msg {name}: its {event} handler failed: {e} {name}: इसका {event} हैंडलर विफल हुआ: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: लगातार {count} हैंडलर विफल होने के बाद, VectorCraft के फिर से शुरू होने तक इसके इवेंट बंद हैं @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है @msg memory budget (object {_1} needs {size} bytes of input, {left} left) मेमोरी बजट (ऑब्जेक्ट {_1} को इनपुट के {size} बाइट चाहिए, {left} शेष हैं) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..d2eaaf10b8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7437,6 +7437,7 @@ axis Y Axis Y tengely Show its progress, see Cancel and write log lines Megjelenítheti az előrehaladását, észlelheti a megszakítást és naplósorokat írhat Keep settings of its own Saját beállításokat tárolhat Keep a cache of its own, which you can clear Saját gyorsítótárat tárolhat, amelyet Ön kiüríthet + Run on its own when the selection, a document or a layer changes Magától futhat, amikor a kijelölés, egy dokumentum vagy egy réteg megváltozik Run these commands on the document: {ids} Ezeket a parancsokat futtathatja a dokumentumon: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call a(z) „{name}” a(z) `{id}` parancsot sorolja fel a `commandAllowlist` listában, amelyet bővítmény nem hívhat meg @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7468,6 +7469,15 @@ axis Y Axis Y tengely @msg only a filter declares `inputs` `inputs` kulcsot csak szűrő adhat meg @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance az `inputs` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` +@msg `events` lists `{shown}` twice az `events` kétszer sorolja fel ezt: `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed az `events` ismeretlen eseményt nevez meg: `{shown}`; használja a selection.changed, document.opened, document.saved vagy layer.changed értéket +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} az `events` listához {EVENTS_API}. szintű bővítmény-API kell: adja meg az `api` {EVENTS_API} értéket +@msg `events` needs the permission `events`, and `events` needs a list of `events` az `events` listához az `events` engedély szükséges, az `events` engedélyhez pedig `events` lista +@msg event size ({len} bytes, limit {max}) esemény mérete ({len} bájt, korlát {max}) +@msg the module reacts to no events a modul egyetlen eseményre sem reagál +@msg vc_event returned {code} a vc_event {code} értéket adott vissza +@msg {name}: its {event} handler failed: {e} {name}: a(z) {event} kezelője sikertelen volt: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: az eseményei ki vannak kapcsolva a VectorCraft következő indításáig, {count} egymást követő sikertelen kezelő után @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges @msg memory budget (object {_1} needs {size} bytes of input, {left} left) memóriakeret (a(z) {_1} objektumnak {size} bájt bemenet kell, {left} maradt) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..936f46e0ad 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -577,6 +577,15 @@ @msg only a filter declares `inputs` hanya filter yang mendeklarasikan `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali +@msg `events` lists `{shown}` twice `events` mencantumkan `{shown}` dua kali +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` menyebut peristiwa yang tidak dikenal `{shown}`: gunakan selection.changed, document.opened, document.saved atau layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` memerlukan API plug-in tingkat {EVENTS_API}: berikan `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` memerlukan izin `events`, dan `events` memerlukan daftar `events` +@msg event size ({len} bytes, limit {max}) ukuran peristiwa ({len} byte, batas {max}) +@msg the module reacts to no events modul tidak bereaksi terhadap peristiwa apa pun +@msg vc_event returned {code} vc_event mengembalikan {code} +@msg {name}: its {event} handler failed: {e} {name}: handler {event}-nya gagal: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: event-nya dimatikan hingga VectorCraft dimulai lagi, setelah {count} handler gagal berturut-turut @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) anggaran memori (objek {_1} memerlukan {size} byte masukan, tersisa {left}) @@ -7394,6 +7403,7 @@ axis Y Axis Sumbu Y Show its progress, see Cancel and write log lines Menampilkan kemajuannya, mengenali pembatalan, dan menulis baris log Keep settings of its own Menyimpan pengaturannya sendiri Keep a cache of its own, which you can clear Menyimpan cache-nya sendiri, yang dapat Anda kosongkan + Run on its own when the selection, a document or a layer changes Berjalan sendiri saat seleksi, dokumen, atau lapisan berubah Run these commands on the document: {ids} Menjalankan perintah ini pada dokumen: {ids} Clear Plug-in Cache Kosongkan cache plug-in # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c3fbb39ac9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7074,6 +7074,7 @@ axis Y Axis Asse Y Show its progress, see Cancel and write log lines Mostrare il proprio avanzamento, rilevare l’annullamento e scrivere righe di registro Keep settings of its own Conservare impostazioni proprie Keep a cache of its own, which you can clear Conservare una cache propria, che è possibile svuotare + Run on its own when the selection, a document or a layer changes Eseguirsi da solo quando cambia la selezione, un documento o un livello Run these commands on the document: {ids} Eseguire questi comandi sul documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” elenca `{id}` in `commandAllowlist`, che un plug-in non può chiamare @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7105,6 +7106,15 @@ axis Y Axis Asse Y @msg only a filter declares `inputs` solo un filtro dichiara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte +@msg `events` lists `{shown}` twice `events` elenca `{shown}` due volte +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` indica un evento sconosciuto `{shown}`: usa selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` richiede il livello API dei plug-in {EVENTS_API}: indicare `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` richiede l’autorizzazione `events`, e `events` richiede un elenco `events` +@msg event size ({len} bytes, limit {max}) dimensione dell’evento ({len} byte, limite {max}) +@msg the module reacts to no events il modulo non reagisce ad alcun evento +@msg vc_event returned {code} vc_event ha restituito {code} +@msg {name}: its {event} handler failed: {e} {name}: il suo gestore di {event} non è riuscito: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: i suoi eventi sono disattivati finché VectorCraft non si riavvia, dopo {count} gestori non riusciti di fila @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget di memoria (l’oggetto {_1} richiede {size} byte di input, ne restano {left}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..f505fe6e6a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7149,6 +7149,7 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 進行状況の表示、キャンセルの検知、ログ行の書き込み Keep settings of its own 独自の設定の保持 Keep a cache of its own, which you can clear 消去できる独自のキャッシュの保持 + Run on its own when the selection, a document or a layer changes 選択、ドキュメント、またはレイヤーが変わったときの自動実行 Run these commands on the document: {ids} ドキュメントでのこれらのコマンドの実行: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」は `commandAllowlist` にプラグインが呼び出せない `{id}` を挙げています @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7180,6 +7181,15 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` `inputs` を宣言できるのはフィルターだけです @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています +@msg `events` lists `{shown}` twice `events` に `{shown}` が 2 回指定されています +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` に不明なイベント `{shown}` があります。selection.changed、document.opened、document.saved、layer.changed のいずれかを使ってください +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` にはプラグイン API レベル {EVENTS_API} が必要です。`api` {EVENTS_API} を指定してください +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` には権限 `events` が必要で、`events` には `events` のリストが必要です +@msg event size ({len} bytes, limit {max}) イベントサイズ ({len} バイト、上限 {max}) +@msg the module reacts to no events このモジュールはどのイベントにも反応しません +@msg vc_event returned {code} vc_event が {code} を返しました +@msg {name}: its {event} handler failed: {e} {name}: {event} のハンドラーが失敗しました: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: ハンドラーが {count} 回続けて失敗したため、VectorCraft を再起動するまでイベントはオフです @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です @msg memory budget (object {_1} needs {size} bytes of input, {left} left) メモリ予算 (オブジェクト {_1} には {size} バイトの入力が必要ですが、残りは {left} です) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..4f8df8bba8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9555,6 +9555,7 @@ axis Y Axis Y ღერძი Show its progress, see Cancel and write log lines პროგრესის ჩვენება, გაუქმების შემჩნევა და ჟურნალის სტრიქონების ჩაწერა Keep settings of its own საკუთარი პარამეტრების შენახვა Keep a cache of its own, which you can clear საკუთარი ქეშის შენახვა, რომლის გასუფთავებაც შეგიძლიათ + Run on its own when the selection, a document or a layer changes თავისით გაშვება, როცა იცვლება მონიშნული, დოკუმენტი ან შრე Run these commands on the document: {ids} ამ ბრძანებების გაშვება დოკუმენტზე: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ `commandAllowlist`-ში ასახელებს `{id}`-ს, რომლის გამოძახებაც პლაგინს არ შეუძლია @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -9586,6 +9587,15 @@ axis Y Axis Y ღერძი @msg only a filter declares `inputs` `inputs`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `events` lists `{shown}` twice `events`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` უცნობ მოვლენას ასახელებს `{shown}`: გამოიყენეთ selection.changed, document.opened, document.saved ან layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`-ს სჭირდება პლაგინის API-ის დონე {EVENTS_API}: მიუთითეთ `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`-ს სჭირდება ნებართვა `events`, ხოლო `events`-ს სჭირდება `events`-ის სია +@msg event size ({len} bytes, limit {max}) მოვლენის ზომა ({len} ბაიტი, ლიმიტი {max}) +@msg the module reacts to no events მოდული არცერთ მოვლენაზე არ რეაგირებს +@msg vc_event returned {code} vc_event-მა დააბრუნა {code} +@msg {name}: its {event} handler failed: {e} {name}: მისი {event} დამმუშავებელი ვერ შესრულდა: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: მისი მოვლენები გამორთულია VectorCraft-ის ხელახლა გაშვებამდე, ზედიზედ {count} წარუმატებელი დამმუშავებლის შემდეგ @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) მეხსიერების ბიუჯეტი (ობიექტს {_1} სჭირდება შეყვანის {size} ბაიტი, დარჩენილია {left}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..684c27a922 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7046,6 +7046,7 @@ axis Y Axis Y축 Show its progress, see Cancel and write log lines 진행률 표시, 취소 감지 및 로그 줄 쓰기 Keep settings of its own 자체 설정 보관 Keep a cache of its own, which you can clear 지울 수 있는 자체 캐시 보관 + Run on its own when the selection, a document or a layer changes 선택 영역, 문서 또는 레이어가 바뀔 때 자동 실행 Run these commands on the document: {ids} 문서에서 다음 명령 실행: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”의 `commandAllowlist`에 플러그인이 호출할 수 없는 `{id}`가 있습니다 @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7077,6 +7078,15 @@ axis Y Axis Y축 @msg only a filter declares `inputs` 필터만 `inputs`를 선언할 수 있습니다 @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `events` lists `{shown}` twice `events`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events`에 알 수 없는 이벤트 `{shown}`이(가) 있습니다. selection.changed, document.opened, document.saved 또는 layer.changed를 사용하세요 +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`에는 플러그인 API 수준 {EVENTS_API}이(가) 필요합니다. `api` {EVENTS_API}을(를) 지정하십시오 +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`에는 `events` 권한이 필요하고, `events`에는 `events` 목록이 필요합니다 +@msg event size ({len} bytes, limit {max}) 이벤트 크기({len}바이트, 제한 {max}) +@msg the module reacts to no events 이 모듈은 어떤 이벤트에도 반응하지 않습니다 +@msg vc_event returned {code} vc_event가 {code}을(를) 반환했습니다 +@msg {name}: its {event} handler failed: {e} {name}: {event} 처리기가 실패했습니다: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: 처리기가 {count}번 연속 실패하여 VectorCraft를 다시 시작할 때까지 이벤트가 꺼집니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 메모리 예산(개체 {_1}에 입력 {size}바이트가 필요하지만 {left}바이트 남음) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..685d671ff7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -541,6 +541,15 @@ liquify-list-end {0}, {1} {0} en {1} @msg only a filter declares `inputs` alleen een filter declareert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` noemt een onbekend objectsoort `{shown}`: gebruik type, image of symbolInstance @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer +@msg `events` lists `{shown}` twice `events` noemt `{shown}` twee keer +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` noemt een onbekende gebeurtenis `{shown}`: gebruik selection.changed, document.opened, document.saved of layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vereist plug-in-API-niveau {EVENTS_API}: geef `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` vereist de machtiging `events`, en `events` vereist een lijst `events` +@msg event size ({len} bytes, limit {max}) gebeurtenisgrootte ({len} bytes, limiet {max}) +@msg the module reacts to no events de module reageert op geen enkele gebeurtenis +@msg vc_event returned {code} vc_event gaf {code} terug +@msg {name}: its {event} handler failed: {e} {name}: de handler voor {event} is mislukt: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: de gebeurtenissen staan uit tot VectorCraft opnieuw start, na {count} mislukte handlers op rij @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) geheugenbudget (object {_1} heeft {size} bytes invoer nodig, {left} over) @@ -9447,6 +9456,7 @@ axis Y Axis Y-as Show its progress, see Cancel and write log lines De voortgang tonen, een annulering zien en logregels schrijven Keep settings of its own Eigen instellingen bewaren Keep a cache of its own, which you can clear Een eigen cache bewaren, die u kunt legen + Run on its own when the selection, a document or a layer changes Vanzelf worden uitgevoerd wanneer de selectie, een document of een laag verandert Run these commands on the document: {ids} Deze opdrachten op het document uitvoeren: {ids} Clear Plug-in Cache Plug-incache legen # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..f38ee32d93 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7307,6 +7307,7 @@ axis Y Axis Oś Y Show its progress, see Cancel and write log lines Pokazywać swój postęp, wykrywać anulowanie i zapisywać wiersze dziennika Keep settings of its own Przechowywać własne ustawienia Keep a cache of its own, which you can clear Przechowywać własną pamięć podręczną, którą możesz wyczyścić + Run on its own when the selection, a document or a layer changes Uruchamiać się samodzielnie, gdy zmieni się zaznaczenie, dokument lub warstwa Run these commands on the document: {ids} Uruchamiać w dokumencie te polecenia: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}” wymienia w `commandAllowlist` polecenie `{id}`, którego wtyczka nie może wywołać @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7338,6 +7339,15 @@ axis Y Axis Oś Y @msg only a filter declares `inputs` tylko filtr deklaruje `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy +@msg `events` lists `{shown}` twice `events` wymienia `{shown}` dwa razy +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` wymienia nieznane zdarzenie `{shown}`: użyj selection.changed, document.opened, document.saved lub layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` wymaga poziomu API wtyczek {EVENTS_API}: podaj `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potrzebuje uprawnienia `events`, a `events` potrzebuje listy `events` +@msg event size ({len} bytes, limit {max}) rozmiar zdarzenia ({len} bajtów, limit {max}) +@msg the module reacts to no events moduł nie reaguje na żadne zdarzenia +@msg vc_event returned {code} vc_event zwróciła {code} +@msg {name}: its {event} handler failed: {e} {name}: jego procedura obsługi {event} nie powiodła się: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jego zdarzenia są wyłączone do ponownego uruchomienia VectorCraft, po {count} nieudanych procedurach obsługi z rzędu @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budżet pamięci (obiekt {_1} wymaga {size} bajtów danych wejściowych, pozostało {left}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..71dc272146 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7351,6 +7351,7 @@ axis Y Axis Eixo Y Show its progress, see Cancel and write log lines Mostrar seu progresso, detectar o cancelamento e gravar linhas de log Keep settings of its own Guardar configurações próprias Keep a cache of its own, which you can clear Guardar um cache próprio, que você pode limpar + Run on its own when the selection, a document or a layer changes Executar-se sozinho quando a seleção, um documento ou uma camada muda Run these commands on the document: {ids} Executar estes comandos no documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” lista `{id}` em `commandAllowlist`, que um plug-in não pode chamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7382,6 +7383,15 @@ axis Y Axis Eixo Y @msg only a filter declares `inputs` somente um filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes +@msg `events` lists `{shown}` twice `events` lista `{shown}` duas vezes +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` cita um evento desconhecido `{shown}`: use selection.changed, document.opened, document.saved ou layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` exige o nível de API de plug-in {EVENTS_API}: informe `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` precisa da permissão `events`, e `events` precisa de uma lista de `events` +@msg event size ({len} bytes, limit {max}) tamanho do evento ({len} bytes, limite {max}) +@msg the module reacts to no events o módulo não reage a nenhum evento +@msg vc_event returned {code} vc_event retornou {code} +@msg {name}: its {event} handler failed: {e} {name}: seu manipulador de {event} falhou: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seus eventos estão desativados até o VectorCraft iniciar de novo, após {count} manipuladores com falha seguidos @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) orçamento de memória (o objeto {_1} precisa de {size} bytes de entrada, restam {left}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..da28f599bf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7074,6 +7074,7 @@ axis Y Axis Ось Y Show its progress, see Cancel and write log lines Показывать свой ход выполнения, замечать отмену и записывать строки журнала Keep settings of its own Хранить собственные настройки Keep a cache of its own, which you can clear Хранить собственный кэш, который можно очистить + Run on its own when the selection, a document or a layer changes Запускаться самостоятельно, когда меняется выделение, документ или слой Run these commands on the document: {ids} Выполнять в документе эти команды: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» указывает в `commandAllowlist` команду `{id}`, которую модуль вызывать не может @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7105,6 +7106,15 @@ axis Y Axis Ось Y @msg only a filter declares `inputs` `inputs` может объявлять только фильтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды +@msg `events` lists `{shown}` twice в `events` `{shown}` указано дважды +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано неизвестное событие `{shown}`: используйте selection.changed, document.opened, document.saved или layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` нужен уровень API модулей {EVENTS_API}: укажите `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` нужно разрешение `events`, а для `events` нужен список `events` +@msg event size ({len} bytes, limit {max}) размер события ({len} байт, предел {max}) +@msg the module reacts to no events модуль не реагирует ни на какие события +@msg vc_event returned {code} vc_event вернула {code} +@msg {name}: its {event} handler failed: {e} {name}: его обработчик {event} завершился ошибкой: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: его события отключены до следующего запуска VectorCraft после {count} неудачных обработчиков подряд @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет памяти (объекту {_1} нужно {size} байт входных данных, осталось {left}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..c83e6ef5f1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7464,6 +7464,7 @@ axis Y Axis Y-axel Show its progress, see Cancel and write log lines Visa sitt förlopp, se när det avbryts och skriva loggrader Keep settings of its own Spara egna inställningar Keep a cache of its own, which you can clear Spara en egen cache, som du kan tömma + Run on its own when the selection, a document or a layer changes Köras av sig själv när markeringen, ett dokument eller ett lager ändras Run these commands on the document: {ids} Köra dessa kommandon på dokumentet: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” anger `{id}` i `commandAllowlist`, som ett plugin inte får anropa @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7495,6 +7496,15 @@ axis Y Axis Y-axel @msg only a filter declares `inputs` bara ett filter anger `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger +@msg `events` lists `{shown}` twice `events` anger `{shown}` två gånger +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anger en okänd händelse `{shown}`: använd selection.changed, document.opened, document.saved eller layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kräver plugin-API-nivå {EVENTS_API}: ange `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` behöver behörigheten `events`, och `events` behöver en lista `events` +@msg event size ({len} bytes, limit {max}) händelsestorlek ({len} byte, gräns {max}) +@msg the module reacts to no events modulen reagerar inte på några händelser +@msg vc_event returned {code} vc_event returnerade {code} +@msg {name}: its {event} handler failed: {e} {name}: dess {event}-hanterare misslyckades: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dess händelser är avstängda tills VectorCraft startas igen, efter {count} misslyckade hanterare i rad @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) minnesbudget (objekt {_1} behöver {size} byte indata, {left} återstår) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..679e207708 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -949,6 +949,33 @@ fn artboard_add_button_tooltips_are_in_complete_catalogs() { } } +/// Install Plug-in… lists what each permission lets a plug-in do, so each complete catalog has a +/// row for the `events` permission's words. +#[test] +fn plugin_events_permission_words_are_in_complete_catalogs() { + let label = "Run on its own when the selection, a document or a layer changes"; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus || COMPLETE_MESSAGES.contains(&lang.code)) { + assert!(lang.catalog().plain(label).is_some_and(|t| !t.is_empty() && t != label), "{} is missing {label}", lang.code); + } +} + +/// The status bar's lines for a plug-in whose event handler failed, which the engine writes after +/// the plug-in's name, are translated in each language of [`COMPLETE_MESSAGES`]. +#[test] +fn plugin_event_handler_failures_are_translated() { + let failed = "Run Events: its selection.changed handler failed: vc_event returned 3"; + let off = "Run Events: its events are off until VectorCraft starts again, after 3 failed handlers in a row"; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in [failed, off] { + let shown = message(lang, s); + assert!(shown != s && shown.starts_with("Run Events") && shown.contains('3'), "{code}: {shown}"); + } + } + assert_eq!(message(de(), failed), "Run Events: sein Handler für selection.changed ist fehlgeschlagen: vc_event hat 3 zurückgegeben"); + assert_eq!(message(de(), off), "Run Events: seine Ereignisse sind aus, bis VectorCraft neu startet, nach 3 fehlgeschlagenen Handlern in Folge"); +} + /// Preferences › Performance › Use Monitor Profile for Canvas and the note under it. #[test] fn monitor_profile_labels_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..5beaea8907 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7524,6 +7524,7 @@ axis Y Axis Y ekseni Show its progress, see Cancel and write log lines İlerlemesini gösterme, iptali algılama ve günlük satırları yazma Keep settings of its own Kendi ayarlarını saklama Keep a cache of its own, which you can clear Temizleyebileceğiniz kendi önbelleğini saklama + Run on its own when the selection, a document or a layer changes Seçim, bir belge veya bir katman değiştiğinde kendiliğinden çalışma Run these commands on the document: {ids} Belgede şu komutları çalıştırma: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”, `commandAllowlist` içinde bir eklentinin çağıramayacağı `{id}` komutunu listeliyor @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7555,6 +7556,15 @@ axis Y Axis Y ekseni @msg only a filter declares `inputs` `inputs` yalnızca bir filtrede bildirilebilir @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor +@msg `events` lists `{shown}` twice `events` `{shown}` değerini iki kez listeliyor +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` bilinmeyen bir olay belirtiyor: `{shown}`; selection.changed, document.opened, document.saved veya layer.changed kullanın +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` için eklenti API düzeyi {EVENTS_API} gerekir: `api` {EVENTS_API} verin +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` için `events` izni, `events` izni için de bir `events` listesi gerekir +@msg event size ({len} bytes, limit {max}) olay boyutu ({len} bayt, sınır {max}) +@msg the module reacts to no events modül hiçbir olaya tepki vermiyor +@msg vc_event returned {code} vc_event {code} döndürdü +@msg {name}: its {event} handler failed: {e} {name}: {event} işleyicisi başarısız oldu: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: art arda {count} işleyici başarısız olduğundan, VectorCraft yeniden başlayana kadar olayları kapalı @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir @msg memory budget (object {_1} needs {size} bytes of input, {left} left) bellek bütçesi (nesne {_1} için {size} bayt girdi gerekiyor, {left} kaldı) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d3db0a5137 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7056,6 +7056,7 @@ axis Y Axis Вісь Y Show its progress, see Cancel and write log lines Показувати свій поступ, помічати скасування і записувати рядки журналу Keep settings of its own Зберігати власні налаштування Keep a cache of its own, which you can clear Зберігати власний кеш, який можна очистити + Run on its own when the selection, a document or a layer changes Запускатися самостійно, коли змінюється виділення, документ або шар Run these commands on the document: {ids} Виконувати в документі ці команди: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» вказує в `commandAllowlist` команду `{id}`, яку модуль викликати не може @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7087,6 +7088,15 @@ axis Y Axis Вісь Y @msg only a filter declares `inputs` `inputs` може оголошувати лише фільтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі +@msg `events` lists `{shown}` twice в `events` `{shown}` указано двічі +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано невідому подію `{shown}`: використовуйте selection.changed, document.opened, document.saved або layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` потрібен рівень API модулів {EVENTS_API}: укажіть `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` потрібен дозвіл `events`, а для `events` потрібен список `events` +@msg event size ({len} bytes, limit {max}) розмір події ({len} байтів, межа {max}) +@msg the module reacts to no events модуль не реагує на жодні події +@msg vc_event returned {code} vc_event повернула {code} +@msg {name}: its {event} handler failed: {e} {name}: його обробник {event} завершився помилкою: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: його події вимкнено до наступного запуску VectorCraft після {count} невдалих обробників поспіль @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет пам’яті (об’єкту {_1} потрібно {size} байтів вхідних даних, залишилося {left}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..806f7f509b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7103,6 +7103,7 @@ axis Y Axis Trục Y Show its progress, see Cancel and write log lines Hiển thị tiến độ, nhận biết yêu cầu hủy và ghi các dòng nhật ký Keep settings of its own Lưu cài đặt riêng Keep a cache of its own, which you can clear Lưu bộ nhớ đệm riêng mà bạn có thể xóa + Run on its own when the selection, a document or a layer changes Tự chạy khi vùng chọn, một tài liệu hoặc một lớp thay đổi Run these commands on the document: {ids} Chạy các lệnh này trên tài liệu: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” liệt kê `{id}` trong `commandAllowlist`, lệnh mà plug-in không được gọi @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7134,6 +7135,15 @@ axis Y Axis Trục Y @msg only a filter declares `inputs` chỉ bộ lọc mới khai báo `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần +@msg `events` lists `{shown}` twice `events` liệt kê `{shown}` hai lần +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nêu một sự kiện không xác định `{shown}`: dùng selection.changed, document.opened, document.saved hoặc layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` cần API plug-in cấp {EVENTS_API}: hãy đặt `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` cần quyền `events`, và `events` cần một danh sách `events` +@msg event size ({len} bytes, limit {max}) kích thước sự kiện ({len} byte, giới hạn {max}) +@msg the module reacts to no events mô-đun không phản ứng với sự kiện nào +@msg vc_event returned {code} vc_event trả về {code} +@msg {name}: its {event} handler failed: {e} {name}: trình xử lý {event} của nó đã thất bại: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: các sự kiện của nó bị tắt cho đến khi VectorCraft khởi động lại, sau {count} trình xử lý thất bại liên tiếp @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) ngân sách bộ nhớ (đối tượng {_1} cần {size} byte đầu vào, còn lại {left}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..f752620e19 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7284,6 +7284,7 @@ axis Y Axis Y 轴 Show its progress, see Cancel and write log lines 显示进度、检测取消请求并写入日志行 Keep settings of its own 保存自己的设置 Keep a cache of its own, which you can clear 保存自己的缓存,您可以清除它 + Run on its own when the selection, a document or a layer changes 在所选对象、文档或图层发生变化时自动运行 Run these commands on the document: {ids} 在文档上运行这些命令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”在 `commandAllowlist` 中列出了增效工具不能调用的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7315,6 +7316,15 @@ axis Y Axis Y 轴 @msg only a filter declares `inputs` 只有滤镜才能声明 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` +@msg `events` lists `{shown}` twice `events` 列出了两次 `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:请使用 selection.changed、document.opened、document.saved 或 layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效工具 API 级别 {EVENTS_API}:请设置 `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要权限 `events`,而 `events` 需要 `events` 列表 +@msg event size ({len} bytes, limit {max}) 事件大小({len} 字节,上限 {max}) +@msg the module reacts to no events 该模块不响应任何事件 +@msg vc_event returned {code} vc_event 返回了 {code} +@msg {name}: its {event} handler failed: {e} {name}:其 {event} 处理程序失败:{e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:处理程序连续 {count} 次失败,其事件已关闭,直到 VectorCraft 再次启动 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 内存预算(对象 {_1} 需要 {size} 字节的输入,剩余 {left}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..d941e2cae4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7105,6 +7105,7 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 顯示進度、偵測取消要求並寫入記錄行 Keep settings of its own 保存自己的設定 Keep a cache of its own, which you can clear 保存自己的快取,您可以清除它 + Run on its own when the selection, a document or a layer changes 在選取範圍、文件或圖層變更時自動執行 Run these commands on the document: {ids} 在文件上執行這些指令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」在 `commandAllowlist` 中列出了增效模組不能呼叫的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7136,6 +7137,15 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` 只有濾鏡才能宣告 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` +@msg `events` lists `{shown}` twice `events` 列出了兩次 `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:請使用 selection.changed、document.opened、document.saved 或 layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效模組 API 層級 {EVENTS_API}:請設定 `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要權限 `events`,而 `events` 需要 `events` 清單 +@msg event size ({len} bytes, limit {max}) 事件大小({len} 位元組,上限 {max}) +@msg the module reacts to no events 此模組不回應任何事件 +@msg vc_event returned {code} vc_event 傳回了 {code} +@msg {name}: its {event} handler failed: {e} {name}:其 {event} 處理常式失敗:{e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:處理常式連續 {count} 次失敗,其事件已關閉,直到 VectorCraft 再次啟動 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 記憶體預算(物件 {_1} 需要 {size} 位元組的輸入,剩餘 {left}) diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 180c459453..2d20911711 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -239,6 +239,7 @@ fn permission_words(name: &str, commands: &[String]) -> String { Some(permissions::Permission::Progress) => tl!("Show its progress, see Cancel and write log lines"), Some(permissions::Permission::Settings) => tl!("Keep settings of its own"), Some(permissions::Permission::Cache) => tl!("Keep a cache of its own, which you can clear"), + Some(permissions::Permission::Events) => tl!("Run on its own when the selection, a document or a layer changes"), None => return permissions::display_text(name, permissions::MAX_SHOWN_FIELD), }; words.to_string() diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..ed18dd4015 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -720,3 +720,43 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); app.run("plugin.remove", json!({"id": id})).unwrap(); } + +/// A selection made in the UI pass, after the frame's background work (as a click on the canvas or +/// a panel makes it), reaches a plug-in that reacts to `selection.changed` before that pass ends: +/// nothing is left for a later delivery. +#[test] +fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { + let mut app = app(); + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.ui_pass_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Pass Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + // The handler writes the event as an information line, which the status bar does not show, so + // the plug-in leaves the status bar of other tests' sessions alone. + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + let pass = |app: &mut VectorcraftApp, select: bool| { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + app.tick(ui.ctx()); + if select { + app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); + } + app.ui(ui); + }); + out.textures_delta.clear(); + }; + // Fonts install on the first pass and are ready on the second. + pass(&mut app, false); + pass(&mut app, false); + pass(&mut app, true); + app.session.deliver_plugin_events(); + let left: Vec = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); + assert!(left.is_empty(), "delivered in the pass that made the change, not later: {left:?}"); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1, "the selection was made"); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..addee8c79a 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -244,6 +244,38 @@ fn finished_background_work_waits_for_the_run_to_end() { assert!(app.opening.activate.is_empty()); } +/// The selection a script changes reaches a plug-in that reacts to `selection.changed` in the +/// frame the script ends in: once it has ended, nothing asks for another frame. +#[test] +fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { + use vectorcraft_plugins::wat as tpl; + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.script_run_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Run Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + // The handler writes the event it is given as a warning, which the status bar shows. + let warn = "(drop (call $vc_log (i32.const 1) (local.get $ep) (local.get $el))) (i32.const 0)"; + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, warn)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + app.poll_finished_work(); + let source = format!("{DRAW} vc.run('select.all', {{}});"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + let ctx = egui::Context::default(); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + } + assert!(!app.session.script_running(), "the script did not end"); + assert!(app.ui.status.starts_with("Run Events: "), "{}", app.ui.status); + assert!(app.ui.status.contains("selection.changed"), "{}", app.ui.status); +} + #[test] fn quitting_asks_to_stop_and_stop_undoes_the_run() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..ed02d61332 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13262,7 +13262,10 @@ while it runs, through `vc_call`: the calls and its output are one undo step, an fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in, switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as -`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A live-effect plug-in is an effect with +`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A plug-in at API level 2 +whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given `selection.changed`, +`document.opened`, `document.saved` and `layer.changed` events through `vc_event` once the change has finished; +its handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). A live-effect plug-in is an effect with id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..8aba315c74 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -210,6 +210,7 @@ capability model proposed for PhotoCraft plug-ins | `settings` | all | Keep settings of its own between runs and sessions ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `cache` | all | Keep a cache of its own, which the user can clear ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `commands` | filter | Run the commands its `commandAllowlist` lists on the document ([command calls](#command-calls)). Needs `api` 2. | +| `events` | all | Run on its own when the selection, a document or a layer changes, for the `events` it names ([events](#events-api-level-2)). Needs `api` 2. | - A manifest without `permissions` gets the ones its kind implies, as plug-ins did before the key existed: a filter `doc.read`, `doc.write` and `state`; an effect `doc.read` and `effect.render`, and also `doc.write` and `state` @@ -219,9 +220,9 @@ capability model proposed for PhotoCraft plug-ins - An effect, an exporter or an importer that lists permissions lists all of its implied ones (`doc.read` and `effect.render`; `doc.read` and `export.write`; `import.read`). An effect with commands may add `doc.write` and `state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`. - Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a - name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api` - below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is + Any kind may add `progress`, `settings`, `cache` and `events`, which no kind implies. An unknown name, a name listed + twice, a name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache`, `commands` or + `events` with an `api` below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is installed, and the error names it. - **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of the file and each permission in plain words, and install it once the user clicks OK, if the file still has the @@ -371,6 +372,7 @@ pointers are offsets into the module's memory. | `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). | | `vc_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. | | `vc_run` | `(input, input_len, params, params_len) -> i64` | Runs the plug-in on the input JSON with the parameters JSON; returns `(len << 32) \| ptr` of the output JSON, or a negative error code. | +| `vc_event` | `(event, event_len) -> i32` | Only in a module whose manifest lists [`events`](#events-api-level-2): reacts to the event JSON; returns `0` when it handled it, anything else when it failed. | ### Host imports (API level 2) @@ -491,7 +493,8 @@ arguments as a JSON object, the params the command takes from any request: `-3` when the arguments are not a JSON object, `-4` when `commandAllowlist` doesn't list the id, `-5` when no command has the id, `-6` when a plug-in may not call the command, `-7` when the command can't run now (nothing is selected), `-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from -the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed). +the module's start function, in a run that isn't a filter's run on a document or an [event](#events-api-level-2) +handler, or after a call in the run failed). - Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, traps, runs @@ -522,6 +525,57 @@ the module's start function, in a run that isn't a filter's run on a document, o - A filter that calls commands runs on the app's main thread, so it can't ask for a heavy budget: a manifest with `commandAllowlist` and `budget: "heavy"` is refused. +### Events (API level 2) + +A plug-in of any kind whose manifest gives `"api": 2`, lists the `events` permission and names events in `events` +exports `vc_event`, and VectorCraft calls it after each change of those kinds: + +```json +{"id": "org.example.watch", "name": "Watch", "kind": "filter", "api": 2, + "permissions": ["doc.read", "events"], "events": ["selection.changed", "document.saved"]} +``` + +| Event | When | The event JSON | +|---|---|---| +| `selection.changed` | The selection in a document changed: other objects, anchors or segments, or nothing (`count` 0). | `{"type", "document", "count", "ids", "truncated"}`: `ids` lists the selected objects, at most 2,048 of them (`truncated` is then `true`), and is `null` without `doc.read`. | +| `document.opened` | A file opened as a document (File › Open, Open Recent, New from Template). A new blank document is not one. | `{"type", "document"}` | +| `document.saved` | Save or Save As wrote the document's own file. Save a Copy, a template and an export are not. | `{"type", "document"}` | +| `layer.changed` | The current layer changed, or a layer or sublayer was added, deleted, moved or given other options. | `{"type", "document", "layer", "reasons"}`: `layer` is the current layer's id (`null` when there is none), `reasons` lists any of `current`, `added`, `deleted`, `reordered` and `options`. `reordered` means a layer's or sublayer's place among the rows beside it changed, also when an object moved past it. | + +`document` is a number that names the open document for the rest of the session. No event carries a path, a file name +or the document's contents. + +- VectorCraft calls `vc_event(event, event_len)` in a fresh instance with the UTF-8 event JSON in a block from + `vc_alloc`, after the change has finished: after the command, after Undo or Redo, after the file was written or the + document opened. Nothing happens while a drag is still being previewed, for a failed command, or for a command that + leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past + events, also none that were waiting for the next delivery when it was installed. A change made to a document opened + or created since the last delivery is an event at the next one, after that document's `document.opened`. +- Changes between two deliveries are one event with the state they ended with. The desktop app delivers in each + frame, after the work that finished in the background and again at the end of the frame, after the canvas, panels + and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does + not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app + and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP + deliver after each request. Opens and saves are each their own event, in order, and are delivered even when the + document closed before the delivery. At most 32 events wait; past that the oldest is dropped. +- A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a + `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active + document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`, + `symbol.list`, `text.getRange`, `transparency.info` and `variable.list`. A call of any other command fails with `-6` + before it runs, the error names the event (`a selection.changed handler only reads: …`), and the handler fails. + Afterwards VectorCraft puts back every document, its selection, current layer and undo history, which document is + active, and the session state a command call can change (paint defaults, the Appearance panel's active row, + preferences); a call that changed a document is refused the same way. An event raised while a handler runs waits + for the next delivery: handlers never run inside one another. +- A handler gets at most 5,000,000 instructions and 200 ms, or its plug-in's own budget when that is smaller, for the + module's start function, `vc_alloc` and `vc_event` together; its settings, cache and log lines work as in a run. + These limits are VectorCraft's own values. A handler that returns anything but `0`, traps or runs out of budget + leaves the change it was told of as it is. Every failure goes to the log, and the first failure in a row also shows + in the status bar; after 3 failures in a row, the plug-in gets no more events until VectorCraft + starts again or another module is installed with its id. A warning or error line a handler writes with `vc_log` + shows in the status bar after the plug-in's name. `plugin.info` gives `eventsOff` and `lastEventError`. +- In Safe Mode no handler runs. When no installed plug-in names an event, VectorCraft does not compare anything. + ### Manifest ```json @@ -574,6 +628,11 @@ the module's start function, in a run that isn't a filter's run on a document, o it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. +- `events` (any kind at `api` 2, and only with the `events` permission, which needs it): the + [events](#events-api-level-2) the plug-in reacts to, any of `"selection.changed"`, `"document.opened"`, + `"document.saved"` and `"layer.changed"`, each at most once. The module then exports `vc_event`. An unknown or + repeated name, an entry that isn't a string, `api` 1, a list without the permission, the permission without a list, + and a missing or wrongly typed `vc_event` are refused when the module is installed, and the error names the fault. - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults are also clamped diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..540f5e8b1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2654,6 +2654,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: changes between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. From 50dcc11e4dd7da5fd6410c91e7a228a4f4ca9b8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:19:15 -0800 Subject: [PATCH 02/60] Plug-ins: keep waiting events to the changes each plug-in was given - A waiting event names each recipient by its installation serial too, so a module that another session removed and installed again is not given an event from before. - A merged layer.changed keeps the reasons per plug-in: one installed between two changes is given only the later change's reasons. - Delivery waits while an interaction is open; the events go out at the first delivery after it ends. - A failed top-level request still delivers what finished before the failure, such as a save in a command.batch whose later step fails. A document.opened for a document that the rollback closes again (a batch, or a failed command of a script or a plug-in call) is dropped. - An event's handler checks the deadline before vc_alloc and before vc_event. - The shared-budget test uses a small instruction budget and checks for an instruction-budget error, and the UI test removes its plug-in when it ends. --- crates/engine/src/cmd/fileio/batch.rs | 3 + crates/engine/src/plugin_events.rs | 118 ++++++++++++++++------- crates/engine/src/script/mod.rs | 5 + crates/engine/src/session/execute.rs | 3 + crates/engine/src/tests/plugin_events.rs | 90 +++++++++++++++++ crates/plugins/src/runtime.rs | 3 + crates/plugins/tests/abi.rs | 23 +++-- crates/ui-egui/src/tests/script_run.rs | 11 +++ docs/plugins.md | 3 +- 9 files changed, 213 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 93670cefd9..316fae8573 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -25,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); let active = s.active; + let opens = s.plugin_events_mark(); s.batch_stash = Some(vec![]); let mut grouped = Vec::with_capacity(cmds.len()); // The Type tool keeps what the steps' Undo and Redo change in it, to put back on a rollback. @@ -39,6 +40,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } Err(e) => { roll_back(s, start, &stash); + // The documents the steps opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(opens); s.notify_text_tool("batch.rollBack"); s.active = active; s.sync_front_profiles(); diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 9951904991..552d93bd21 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -7,9 +7,10 @@ //! - A check runs after each top-level command, or when a frontend that sets //! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame. //! Changes between two checks are one event: a burst of selection changes is one -//! `selection.changed` with the final selection. No check runs while an interaction is open (a -//! drag being previewed). A document opened or created since the last check is compared with how -//! it was when the command that added it ended ([`Session::plugin_events_see_new_documents`]). +//! `selection.changed` with the final selection. No check or delivery runs while an interaction +//! is open (a drag being previewed); waiting events wait for it to end. A document opened or +//! created since the last check is compared with how it was when the command that added it ended +//! ([`Session::plugin_events_see_new_documents`]). //! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a //! handler runs waits for the next delivery: handlers never run inside one another. //! - A handler only reads. The host applies nothing it returns, and it may call only the commands @@ -48,22 +49,36 @@ struct Seen { layer: Option, } -/// A plug-in an event is for: its id and the hash of its module. -type Recipient = (String, String); +/// A plug-in an event is for: its id, the hash of its module and its installation +/// ([`Plugin::serial`]), so a module removed and installed again is another recipient. +type Recipient = (String, String, u64); /// The recipient `p` is. fn recipient(p: &Plugin) -> Recipient { - (p.id().to_string(), p.hash().to_string()) + (p.id().to_string(), p.hash().to_string(), p.serial()) } -/// An event waiting for delivery: what changed, in which document, for `layer.changed` why, and -/// the plug-ins it is for: those installed when it happened. +/// An event waiting for delivery: what changed, in which document, and the plug-ins it is for +/// (those installed when it happened), each with the reasons of a `layer.changed` it was given. #[derive(Clone, Debug, PartialEq)] struct Pending { event: Event, document: u64, - reasons: Vec<&'static str>, - to: Vec, + to: Vec<(Recipient, Vec<&'static str>)>, + /// When it was queued ([`PluginEvents::queued`] then). + seq: u64, +} + +impl Pending { + /// Whether this event is for `r`. + fn is_for(&self, r: &Recipient) -> bool { + self.to.iter().any(|(x, _)| x == r) + } + + /// The reasons of a `layer.changed` that `r` is given. + fn reasons_for(&self, r: &Recipient) -> &[&'static str] { + self.to.iter().find(|(x, _)| x == r).map_or(&[], |(_, reasons)| reasons.as_slice()) + } } /// One plug-in's failed handlers in a row, for the module with `hash`. @@ -95,6 +110,8 @@ pub struct PluginEvents { /// The plug-ins that reacted to events when `seen` was taken. seen_by: Vec, pending: VecDeque, + /// How many events have been queued as their own entry. + queued: u64, dispatching: bool, failures: BTreeMap, notices: VecDeque, @@ -119,24 +136,30 @@ impl PluginEvents { subs } - /// Queues `event` for document `uid`, for the plug-ins `to`. A `selection.changed` or - /// `layer.changed` already waiting for that document takes it in (a layer event adds the new - /// reasons to its own, and the new plug-ins to its own); past [`MAX_PENDING`] the oldest event is - /// dropped. + /// Queues `event` for document `uid`, for the plug-ins `to`, with the reasons of a + /// `layer.changed`. A `selection.changed` or `layer.changed` already waiting for that document + /// takes it in: each plug-in in `to` is added, or adds the new reasons to the ones it was given, + /// so a plug-in is given only the reasons of the changes it was given. Past [`MAX_PENDING`] the + /// oldest event is dropped. fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec) { if matches!(event, Event::SelectionChanged | Event::LayerChanged) && let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid) { - for r in reasons { - if !p.reasons.contains(&r) { - p.reasons.push(r); - } - } - p.reasons.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); for r in to { - if !p.to.contains(&r) { - p.to.push(r); + let i = match p.to.iter().position(|(x, _)| *x == r) { + Some(i) => i, + None => { + p.to.push((r, Vec::new())); + p.to.len() - 1 + } + }; + let given = &mut p.to[i].1; + for reason in &reasons { + if !given.contains(reason) { + given.push(*reason); + } } + given.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); } return; } @@ -145,7 +168,9 @@ impl PluginEvents { { log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); } - self.pending.push_back(Pending { event, document: uid, reasons, to }); + let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued }); + self.queued += 1; } fn notice(&mut self, n: Notice) { @@ -247,6 +272,18 @@ impl Session { self.plugin_events.queue(event, uid, Vec::new(), to); } + /// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far. + pub(crate) fn plugin_events_mark(&self) -> u64 { + self.plugin_events.queued + } + + /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback + /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The + /// saves stay, since the files they wrote stay written. + pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { + self.plugin_events.pending.retain(|p| p.event != Event::DocumentOpened || p.seq < mark); + } + /// Compares each open document with how the last check saw it and queues the events its changes /// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the /// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in @@ -264,7 +301,7 @@ impl Session { } let installed: Vec = subs.iter().map(|p| recipient(p)).collect(); self.plugin_events.pending.retain_mut(|p| { - p.to.retain(|r| installed.contains(r)); + p.to.retain(|(r, _)| installed.contains(r)); !p.to.is_empty() }); if self.docs.iter().any(|d| d.interaction.is_some()) { @@ -300,13 +337,14 @@ impl Session { /// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the /// handlers of the events waiting, oldest first, one handler at a time. While a handler runs, - /// this returns at once: what the handler's calls change waits for the next delivery. + /// this returns at once: what the handler's calls change waits for the next delivery. While an + /// interaction is open, the events wait for the first delivery after it ends. pub fn deliver_plugin_events(&mut self) { if self.plugin_events.dispatching { return; } self.check_plugin_events(); - if self.plugin_events.pending.is_empty() { + if self.plugin_events.pending.is_empty() || self.docs.iter().any(|d| d.interaction.is_some()) { return; } let subs = self.plugin_events.subscribers(); @@ -319,7 +357,7 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } - for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.to.contains(&recipient(s))) { + for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.is_for(&recipient(s))) { if self.plugin_events.failures_of(plugin).disabled { continue; } @@ -348,7 +386,7 @@ impl Session { } Event::LayerChanged => { v["layer"] = json!(st.active_layer.map(|l| l.0)); - v["reasons"] = json!(p.reasons); + v["reasons"] = json!(p.reasons_for(&recipient(plugin))); } Event::DocumentOpened | Event::DocumentSaved => {} } @@ -449,27 +487,33 @@ impl Session { mod tests { use super::*; + /// Waiting selection and layer events of a document merge; each plug-in keeps the reasons of + /// the changes it was given. #[test] fn waiting_selection_and_layer_events_of_a_document_merge() { + let (a, b): (Recipient, Recipient) = (("a".into(), "1".into(), 1), ("b".into(), "2".into(), 2)); let mut e = PluginEvents::default(); - e.queue(Event::SelectionChanged, 1, vec![], vec![]); - e.queue(Event::LayerChanged, 1, vec!["options"], vec![]); - e.queue(Event::SelectionChanged, 1, vec![], vec![]); - e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![]); - e.queue(Event::SelectionChanged, 2, vec![], vec![]); - e.queue(Event::DocumentSaved, 1, vec![], vec![]); - e.queue(Event::DocumentSaved, 1, vec![], vec![]); - let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons.clone())).collect(); + e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["options"], vec![a.clone()]); + e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["deleted", "current"], vec![a.clone(), b.clone()]); + e.queue(Event::SelectionChanged, 2, vec![], vec![a.clone()]); + e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); + e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); + let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons_for(&a).to_vec())).collect(); assert_eq!( got, [ (Event::SelectionChanged, 1, vec![]), - (Event::LayerChanged, 1, vec!["current", "options"]), + (Event::LayerChanged, 1, vec!["current", "deleted", "options"]), (Event::SelectionChanged, 2, vec![]), (Event::DocumentSaved, 1, vec![]), (Event::DocumentSaved, 1, vec![]), ] ); + assert_eq!(e.pending[1].reasons_for(&b), ["current", "deleted"], "only the change it was given"); + assert!(!e.pending[0].is_for(&b)); } /// While a handler runs, a delivery returns at once; the change waits for the next one, which diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..2d15652731 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -642,6 +642,8 @@ pub(crate) struct Savepoint { pending_paint: Option, choices: Choices, journal: usize, + /// The plug-in events queued before the command ([`Session::plugin_events_mark`]). + plugin_events: u64, } impl Savepoint { @@ -676,6 +678,7 @@ impl Savepoint { pending_paint: s.pending_paint.clone(), choices: Choices::of(s), journal: s.journal.len(), + plugin_events: s.plugin_events_mark(), } } @@ -728,6 +731,8 @@ impl Savepoint { s.pending_paint = self.pending_paint; self.choices.put(s); s.journal.truncate(self.journal); + // The documents the command opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(self.plugin_events); s.sync_front_profiles(); exact } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 19cd41fdb0..9f4591423f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -206,6 +206,9 @@ impl Session { // A failed or panicked command's documents are put back: type is drawn in their // composite fonts again, not in those the command set. cmd::compositefonts::sync(self); + // Plug-ins still hear of what finished before the failure, such as a save in a batch + // whose later step failed. + self.plugin_events_after_command(); } let r = r?; if self.depth == 0 { diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index df8dd04cb4..6ee0e8342b 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -238,6 +238,96 @@ fn a_module_installed_again_gets_no_event_from_before_its_removal() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A save waiting in one session is not given to the same module that another session removed and +/// installed again before this session's delivery. +#[test] +fn a_module_installed_again_by_another_session_gets_no_earlier_event() { + let id = "test.events.again_elsewhere"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-elsewhere-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("elsewhere.vectorcraft").to_string_lossy()})); + let mut other = session(); + run(&mut other, "plugin.remove", json!({"id": id})); + install(&mut other, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed between two layer changes waiting for the same delivery is given only the +/// reason of the change after its install; the plug-in installed before is given both. +#[test] +fn a_plugin_installed_between_layer_changes_gets_only_the_later_reason() { + let (early, late) = ("test.events.reasons_early", "test.events.reasons_late"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, early, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + run(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})); + install(&mut s, late, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let reasons = |id: &str| -> Vec { + notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str::(&n.text).unwrap()["reasons"].clone()).collect() + }; + assert_eq!(reasons(early), [json!(["current", "options"])]); + assert_eq!(reasons(late), [json!(["current"])], "the rename came before this install"); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// A save waiting for delivery is held while an interaction is open, and given at the first +/// delivery after it ends. +#[test] +fn waiting_events_are_held_while_an_interaction_is_open() { + let id = "test.events.interaction"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-interaction-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("interaction.vectorcraft").to_string_lossy()})); + s.begin_interaction("Move").unwrap(); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "not while the interaction is open"); + s.cancel_interaction().unwrap(); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save in a batch whose later step fails is still given to the plug-in when the request ends; +/// an open in that batch, which the rollback closes again, is not. +#[test] +fn a_save_before_a_failed_batch_step_is_delivered() { + let id = "test.events.failed_batch"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-batch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("failed-batch.vectorcraft").to_string_lossy().into_owned(); + let steps = json!([ + {"command": "document.save", "params": {"path": path}}, + {"command": "document.open", "params": {"path": path}}, + {"command": "no.such.command", "params": {}} + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert!(std::path::Path::new(&path).exists(), "the save was written"); + assert_eq!(s.documents().len(), 1, "the opened document was closed again"); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 699fe15161..54e315b2cf 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -582,6 +582,8 @@ impl Plugin { let out = (|| { let alloc: TypedFunc = live.func("vc_alloc")?; let handler: TypedFunc = live.func("vc_event")?; + // The start function may have used the time: neither call runs past it. + deadline.check()?; let ptr = self.call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize; if ptr == 0 { return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into())); @@ -589,6 +591,7 @@ impl Plugin { let outside = || Error::Abi("vc_alloc returned a block outside memory".into()); let end = ptr.checked_add(event.len()).ok_or_else(outside)?; live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event); + deadline.check()?; let code = self.call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?; deadline.check()?; if code != 0 { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index bb28afd450..146118162e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1073,7 +1073,9 @@ fn vc_event_is_given_the_event_and_its_code_is_checked() { } /// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the -/// handler alone fits it no longer when the start function has done as much first. +/// handler alone fits it no longer when the start function has done as much first. The budget is +/// 200,000 instructions, which run in far less than the 200 ms an event is given, so the run that +/// fails is stopped by its instruction budget. #[test] fn a_handler_and_its_start_function_share_the_event_budget() { let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#); @@ -1084,18 +1086,23 @@ fn a_handler_and_its_start_function_share_the_event_budget() { let plugin = |start: u32, handler: u32| { let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS); let body = format!("(call $burn (i32.const {handler})) (i32.const 0)"); - Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits::default()).unwrap() + Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap() }; let event = br#"{"type":"layer.changed","document":1}"#; - // The most loop turns, doubling, that fit the budget in the handler alone: twice as many don't. - let mut k = 1u32 << 16; - while plugin(0, k * 2).run_event(event, None).0.is_ok() { - k *= 2; + // The most loop turns, doubling, that fit the budget in the handler alone: twice as many run out + // of instructions. + let mut k = 1u32 << 8; + let e = loop { + match plugin(0, k * 2).run_event(event, None).0 { + Ok(()) => k *= 2, + Err(e) => break e.to_string(), + } assert!(k < 1 << 30, "a handler that never runs out of its budget"); - } + }; + assert!(e.contains("instruction budget"), "{e}"); assert!(plugin(0, k).run_event(event, None).0.is_ok()); let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string(); - assert!(e.contains("budget"), "{e}"); + assert!(e.contains("instruction budget"), "{e}"); } /// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index addee8c79a..03917c635f 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -249,10 +249,21 @@ fn finished_background_work_waits_for_the_run_to_end() { #[test] fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { use vectorcraft_plugins::wat as tpl; + + /// Removes the plug-in when the test ends, failed or not: the registry serves every session in + /// the process. + struct Remove(&'static str); + impl Drop for Remove { + fn drop(&mut self) { + vectorcraft_plugins::registry::remove(self.0); + } + } + let mut app = app(); app.session.prefs.show_external_script_warning = false; app.session.allow_plugin_grants_from_requests(); let id = "test.UI.script_run_events"; + let _remove = Remove(id); let grant = json!(["progress", "events"]); let manifest = format!(r#"{{"id":"{id}","name":"Run Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); // The handler writes the event it is given as a warning, which the status bar shows. diff --git a/docs/plugins.md b/docs/plugins.md index 8aba315c74..e50e2455e1 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -556,7 +556,8 @@ or the document's contents. and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP - deliver after each request. Opens and saves are each their own event, in order, and are delivered even when the + deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its + `document.saved`. Opens and saves are each their own event, in order, and are delivered even when the document closed before the delivery. At most 32 events wait; past that the oldest is dropped. - A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active From 01ec822509dfd2adde186cf25f543aed4c29ad9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:41:53 -0800 Subject: [PATCH 03/60] Plug-ins: drop the open events of a script run that fails A script that opens a document and then throws, runs out of budget or is abandoned loses that document with its working copy, so its waiting document.opened event is now dropped when the run ends. The saves it made before failing are still delivered, and so is a document the frontend opened while the run was paused. --- crates/engine/src/plugin_events.rs | 24 ++++++++++++- crates/engine/src/script/mod.rs | 4 +++ crates/engine/src/tests/plugin_events.rs | 43 ++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 552d93bd21..555f2ac308 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -67,6 +67,9 @@ struct Pending { to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, + /// Queued by a command of the running script, whose run has not ended yet + /// ([`Session::plugin_events_script_ended`]). + by_script: bool, } impl Pending { @@ -169,7 +172,7 @@ impl PluginEvents { log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); } let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); - self.pending.push_back(Pending { event, document: uid, to, seq: self.queued }); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, by_script: false }); self.queued += 1; } @@ -270,6 +273,25 @@ impl Session { return; } self.plugin_events.queue(event, uid, Vec::new(), to); + // An open or a save is queued as its own entry, the newest. + if self.script_in_run + && let Some(p) = self.plugin_events.pending.back_mut() + { + p.by_script = true; + } + } + + /// At the end of a script's run. When the run failed (`kept` false), drops the waiting + /// `document.opened` events its commands queued, since the documents they opened were discarded + /// with its working copy. Its saves stay, since the files they wrote stay written, and so do the + /// events of documents a frontend opened while the run was paused. + pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { + if !kept { + self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + } + for p in &mut self.plugin_events.pending { + p.by_script = false; + } } /// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 2d15652731..83f6b588d3 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1910,6 +1910,8 @@ impl Session { lost }); drop(lost); + // The job's working copy went with it, with the documents the run opened. + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2182,6 +2184,7 @@ impl Session { let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); self.end_job(job, e.kind == RunErrorKind::Internal); + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2271,6 +2274,7 @@ impl Session { host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); + self.plugin_events_script_ended(true); self.script_report = Some(report.clone()); Ok(report) } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 6ee0e8342b..9f757b020e 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -328,6 +328,49 @@ fn a_save_before_a_failed_batch_step_is_delivered() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A document a script opened before it failed is discarded with the run's working copy, so the +/// plug-in is not told of it. The save the script made before failing is still given, and so is a +/// document the frontend opened while the run was paused. +#[test] +fn a_failed_script_gives_its_save_but_not_its_open() { + let id = "test.events.failed_script"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-script-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("failed-script.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + assert!(s.docs.iter().all(|d| d.uid == doc || d.uid == front), "the script's document was discarded"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc}), json!({"type": "document.opened", "document": front})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] From 199c580ca4331554758e44cb044bcda5f6cb4cb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:27:30 -0800 Subject: [PATCH 04/60] Scripts: pathItems.removeAll() refuses paths on a locked artboard pathItems.removeAll() deleted paths on a locked artboard, while pageItems.removeAll() and remove() throw for them. It now throws the same error and deletes nothing when any path, a path in a group included, is on a locked artboard. --- crates/engine/src/script/dom/paths.rs | 15 +++++++++---- crates/engine/src/tests/script_dom_paths.rs | 25 +++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 9c4bb604fe..21d8307867 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -67,7 +67,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; @@ -340,18 +340,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before +/// anything is deleted, as `pageItems.removeAll()` is stopped. 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, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index ca995ed913..aac4579cbd 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -97,6 +97,31 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes +/// nothing, as `pageItems.removeAll()` and `remove()` do. +#[test] +fn path_items_remove_all_refuses_paths_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()) && e.contains(&b.0.to_string()), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); +} + #[test] fn shape_creators_use_documented_defaults_and_y_up() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index af1ddb276f..21fb6ff4c4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2804,7 +2804,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot themselves, such as a text frame's `contents`, are not defined yet and read as `undefined`. - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, - `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new + `getByName(name)`, `removeAll()` (when any path is on a locked artboard, it throws + `cannot delete objects on a locked artboard` and deletes nothing), `add()` (a path with no points, from `path.create`, painted as new art; when new art has no fill and no stroke, the path has neither), and the shape creators `rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`, From da2fc57f35bd1b1eadcfb5f74c1e651e94be1ca3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:47:24 -0800 Subject: [PATCH 05/60] Scripts: pathItems reads a path by name as pageItems does pathItems["name"] read as undefined and "name" in pathItems was false even when a path had that name, while pageItems gives the object getByName gives. pathItems now does the same: a read with a name nothing has throws Not found, and the in test is false for it. --- crates/engine/src/script/dom/paths.rs | 13 ++++++++++--- crates/engine/src/tests/script_dom_paths.rs | 16 ++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 21d8307867..823ed46d41 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -67,9 +67,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, - point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, + editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -310,8 +310,15 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } +/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return match items_by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined), + r => r, + }; + } 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)))) diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index aac4579cbd..edd359282e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -97,6 +97,22 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// `pathItems` read with a name gives what `getByName` gives, and throws as it does for no match, +/// as `pageItems` does. +#[test] +fn path_items_read_with_a_name_give_the_named_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems, m = [];\ + vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ + try { p['nosuch']; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); +} + /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 21fb6ff4c4..e8d3818991 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2803,7 +2803,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a text frame's `contents`, are not defined yet and read as `undefined`. - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the - order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, + order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `[name]` (read as + `pageItems["name"]` is read), `index(key)`, `getByName(name)`, `removeAll()` (when any path is on a locked artboard, it throws `cannot delete objects on a locked artboard` and deletes nothing), `add()` (a path with no points, from `path.create`, painted as new art; when new art has no fill and no stroke, the path has neither), and the shape creators From ab75ac0c13e25eaa61848dd518edabfa19b252e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:19:22 -0800 Subject: [PATCH 06/60] Plug-ins: a module with a manifest section that lists events must export vc_event Changes on main needed the events code and its tests to follow them. - A module that carries its manifest in the `vc_manifest` custom section is loaded without being instantiated, and its exports are checked by `check_exports`. That check now also requires `vc_event` with the type (param i32 i32) (result i32) when the manifest lists `events`, as the instantiated path already did. The `an_event_plugin_exports_vc_event` test covers a sectioned module without `vc_event`, with the wrong type and with the right one. - JavaScript plug-ins have no `vc_event`, so their manifest may not list the permission `events`, next to `settings`, `cache` and `commands`. The JavaScript bundle test and docs/plugins.md say so. - The craft UI framework port removed `VectorcraftApp::begin_host_iteration`, so the two UI-pass event tests no longer call it. - On the framework, the whole window draws only on a context with the framework's runtime installed. `a_change_made_in_a_ui_pass_is_delivered_in_that_pass` drew it on a plain `egui::Context`, where the runtime panics ("the runtime plugin's hooks did not run for the previous pass") and the test did not finish. It now draws its passes with `testing::ui_context` and `testing::part_frame`, as the window tests on main do. --- crates/plugins/src/js.rs | 2 ++ crates/plugins/src/manifest.rs | 4 ++-- crates/plugins/src/runtime.rs | 10 +++++++--- crates/plugins/tests/abi.rs | 10 ++++++++++ crates/ui-egui/src/tests/plugins.rs | 8 +++----- crates/ui-egui/src/tests/script_run.rs | 1 - docs/plugins.md | 4 ++-- 7 files changed, 26 insertions(+), 13 deletions(-) diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs index a8fa158c41..b10506011f 100644 --- a/crates/plugins/src/js.rs +++ b/crates/plugins/src/js.rs @@ -460,6 +460,8 @@ mod tests { assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.events", ok, json!({"api": 2, "permissions": ["events"], "events": ["selection.changed"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("can't list the permission `events`")), "{e:?}"); let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 5b06ed24c5..611d51ebbf 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -704,7 +704,7 @@ impl Manifest { } /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions - /// it lists only `progress`: its realm has no settings, cache or command calls. + /// it lists only `progress`: its realm has no settings, cache, command calls or `vc_event`. fn validate_runtime(&self) -> Result<()> { if self.runtime == Runtime::Wasm { return Ok(()); @@ -714,7 +714,7 @@ impl Manifest { return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); } let listed = self.permissions.as_deref().unwrap_or_default(); - for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + for p in [Permission::Settings, Permission::Cache, Permission::Commands, Permission::Events] { if listed.iter().any(|n| n == p.name()) { let name = p.name(); return Err(Error::Manifest(format!( diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 9dd6d574e7..ce8ca5e32c 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -322,8 +322,9 @@ fn check_tables(bytes: &[u8]) -> Result<()> { } /// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose -/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types. -fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { +/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types, and +/// `vc_event` with its type when `events` is set (the manifest lists events). +fn check_exports(module: &Module, max_memory_bytes: usize, events: bool) -> Result<()> { use ValType::{I32, I64}; let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone()); let Some(ExternType::Memory(memory)) = export("memory") else { @@ -341,6 +342,9 @@ fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}"))); } } + if events && !matches!(export("vc_event"), Some(ExternType::Func(f)) if f.params() == [I32, I32] && f.results() == [I32]) { + return Err(Error::Abi("the module lists `events`, so it must export `vc_event` with the type (param i32 i32) (result i32)".into())); + } Ok(()) } @@ -428,7 +432,7 @@ impl Plugin { } } None => { - check_exports(&module, p.limits.max_memory_bytes)?; + check_exports(&module, p.limits.max_memory_bytes, !p.manifest.events.is_empty())?; check_tables(bytes)?; } } diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 634762ef4e..206faa721e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1264,6 +1264,16 @@ fn an_event_plugin_exports_vc_event() { assert!(e.to_string().contains("vc_event"), "{e}"); assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok()); assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event"); + // A module whose manifest is in its custom section is checked without being instantiated. + let section = + r#"{"id":"test.events.section","name":"T","kind":"filter","api":2,"permissions":["events"],"events":["selection.changed"],"abi":1}"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, "", 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let one_param = r#"(func (export "vc_event") (param i32) (result i32) (i32.const 0))"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, one_param, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let handler = r#"(func (export "vc_event") (param i32 i32) (result i32) (i32.const 0))"#; + assert!(Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, handler, 1)), Limits::default()).is_ok()); } /// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 1eb8f2081a..53e4f89f33 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -838,20 +838,18 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); app.run("select.none", json!({})).unwrap(); - let ctx = egui::Context::default(); + let ctx = crate::testing::ui_context(); let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); let pass = |app: &mut VectorcraftApp, select: bool| { - app.begin_host_iteration(); - let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |app, ui| { app.tick(ui.ctx()); if select { app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); } app.ui(ui); }); - out.textures_delta.clear(); }; - // Fonts install on the first pass and are ready on the second. + // The window lays itself out in the first two passes. pass(&mut app, false); pass(&mut app, false); pass(&mut app, true); diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index a5bd95e881..91803e6b70 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -343,7 +343,6 @@ fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { if !app.session.script_running() { break; } - app.begin_host_iteration(); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); out.textures_delta.clear(); } diff --git a/docs/plugins.md b/docs/plugins.md index 385925d30f..1646097587 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1308,8 +1308,8 @@ function run(input, params) { The manifest has the keys of a module's [manifest](#manifest), with `"runtime": "js"` and `script`, a file name of 1 to 128 bytes ending in `.js`, without a folder or `:`, and not starting with `.`. Left out, `runtime` is WebAssembly, so existing modules load as before; a module's own manifest may not give `"js"`. A JavaScript plug-in is a filter (`kind` -`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache` or -`commands`, so it has no `commandAllowlist`. +`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache`, +`commands` or `events`, so it has no `commandAllowlist` and no `events`. `plugin.install {path}` and `plugin.inspect {path}` take the `.vcplugin` file, and File › Open and `plugin.reload` install it like a `.wasm` file. The host refuses a manifest without `script`, with `source`, or with a `runtime` other From c04c53ca6cb612a92a61ffe611afa439e206cc1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:24:17 -0800 Subject: [PATCH 07/60] Plug-ins: hold a running script's events and deliver window-key changes in their pass A delivery between a script's slices no longer gives the opens and saves the script queued; they wait until the run ends, so a run that fails never gives the opens of documents it discarded. The desktop app now delivers after the window keys run, so a selection Escape changes when it leaves isolation mode reaches plug-ins in that pass, and the handlers' time counts toward the frame time. The docs state the per-document grouping and the script rule. --- crates/engine/src/plugin_events.rs | 22 +++++++++--- crates/engine/src/tests/plugin_events.rs | 44 ++++++++++++++++++++++++ crates/ui-egui/src/app.rs | 17 +++++---- crates/ui-egui/src/tests/plugins.rs | 33 ++++++++++++++++++ docs/plugins.md | 12 ++++--- docs/target-app-parity.md | 2 +- 6 files changed, 115 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 555f2ac308..f853198ebb 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -281,10 +281,12 @@ impl Session { } } - /// At the end of a script's run. When the run failed (`kept` false), drops the waiting - /// `document.opened` events its commands queued, since the documents they opened were discarded - /// with its working copy. Its saves stay, since the files they wrote stay written, and so do the - /// events of documents a frontend opened while the run was paused. + /// At the end of a script's run. The opens and saves its commands queued wait until then, also + /// through deliveries between its slices ([`Session::deliver_plugin_events`]). When the run + /// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since + /// the documents they opened were discarded with its working copy. Its saves stay, since the + /// files they wrote stay written, and so do the events of documents a frontend opened while the + /// run was paused. The next delivery gives what is left in the order it was queued. pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { if !kept { self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); @@ -375,7 +377,15 @@ impl Session { // as it was found. let depth = self.depth; self.depth += 1; + // An open or a save a running script queued waits for the end of the run + // ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its + // slices: a run that fails discards the documents it opened. + let mut held = VecDeque::new(); while let Some(p) = self.plugin_events.pending.pop_front() { + if p.by_script { + held.push_back(p); + continue; + } if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } @@ -386,6 +396,10 @@ impl Session { self.run_handler(plugin, &p); } } + // The held events are older than any a handler's calls queued meanwhile. + while let Some(p) = held.pop_back() { + self.plugin_events.pending.push_front(p); + } self.depth = depth; self.plugin_events.dispatching = false; } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 9f757b020e..66b8804a58 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -371,6 +371,50 @@ fn a_failed_script_gives_its_save_but_not_its_open() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A delivery between a script's slices, as a frontend makes one for a command it runs while the +/// script is paused, gives the frontend's open but holds the open and the save the script queued +/// until the run ends: the run fails, so its open is never given, and its save is given after it. +#[test] +fn a_delivery_between_script_slices_holds_the_script_events() { + let id = "test.events.between_slices"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-between-slices-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("between-slices.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.opened", "document": front})], "only the frontend's open, while the run is paused"); + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})], "the script's save, and not its open"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d75c545869..d1998ecd1e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -673,6 +673,17 @@ impl VectorcraftApp { self.handle_input(&ctx); self.ui_frame(ui); self.window_keys(&ctx); + // What the canvas, a panel, a dialog or a window key changed in this pass reaches + // the plug-ins that react to it now, since an idle app draws no further frame; a + // line a handler wrote shows in the next one. The handlers' time counts toward the + // frame-time sample of a pass egui presents. + let t0 = monotonic_ms(); + if !self.session.script_running() && self.deliver_plugin_events() { + ctx.request_repaint(); + } + if !ctx.will_discard() { + self.perf.frame_ms += monotonic_ms() - t0; + } }) }) { self.session.set_replaying(false); @@ -757,12 +768,6 @@ impl VectorcraftApp { // A command run by a menu, panel or dialog in this pass may have queued its text copy // after the input. Publish it now: an idle web host may have no further frame to run it in. self.flush_clipboard_out(); - // What the canvas, a panel or a dialog changed in this pass reaches the plug-ins that react - // to it now, since an idle app draws no further frame; a line a handler wrote shows in the - // next one. - if !self.session.script_running() && self.deliver_plugin_events() { - ctx.request_repaint(); - } crate::cursors::request_busy(self, &ctx); // A pass egui will discard and rerun is not a presented frame: it must not become the // frame-time sample, and it must not issue a capture of what it drew. diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 27508fb744..455493afaf 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -1065,6 +1065,39 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// Escape leaving isolation mode restores the selection from before entry after the window's +/// panels and dialogs are drawn; the plug-in that reacts to `selection.changed` is still given the +/// change in that pass. +#[test] +fn a_selection_a_window_key_changes_is_delivered_in_that_pass() { + let mut app = app(); + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.window_key_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Key Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 40, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("object.isolate", json!({"id": g})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let ctx = crate::testing::ui_context(); + super::synthetic::key_frame(&mut app, &ctx, vec![]); + super::synthetic::key_frame(&mut app, &ctx, vec![]); + app.session.deliver_plugin_events(); + let _ = app.session.take_plugin_event_notices(); + let before = app.session.doc().unwrap().selection.objects.clone(); + let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + super::synthetic::key_frame(&mut app, &ctx, vec![esc]); + assert_ne!(app.session.doc().unwrap().selection.objects, before, "Escape left isolation and restored the selection"); + app.session.deliver_plugin_events(); + let left: Vec = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); + assert!(left.is_empty(), "delivered in the pass of the key, not later: {left:?}"); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + /// The approval names a plug-in whose manifest translates its name in the UI language and also /// gives the manifest's own name, both escaped; a language without a translation shows the /// manifest's name alone. What OK installs stays bound to the id and hash shown. diff --git a/docs/plugins.md b/docs/plugins.md index be672b22b5..cbcdc68d8c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -873,14 +873,18 @@ or the document's contents. leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past events, also none that were waiting for the next delivery when it was installed. A change made to a document opened or created since the last delivery is an event at the next one, after that document's `document.opened`. -- Changes between two deliveries are one event with the state they ended with. The desktop app delivers in each - frame, after the work that finished in the background and again at the end of the frame, after the canvas, panels - and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does +- The selection changes of one document between two deliveries are one `selection.changed` with the state they ended + with, and its layer changes are one `layer.changed`; each document's events are separate. The desktop app delivers + in each frame, after the work that finished in the background and again at the end of the frame, after the canvas, + panels, dialogs and window keys have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its `document.saved`. Opens and saves are each their own event, in order, and are delivered even when the - document closed before the delivery. At most 32 events wait; past that the oldest is dropped. + document closed before the delivery. The opens and saves of a running script wait until its run ends, also + through any delivery between its slices. The desktop app does not deliver while a script runs; a frontend that + does can give its own opens and saves made while the run was paused before the script's earlier ones. A run that fails gives its saves and none of its opens. At most 32 + events wait; past that the oldest is dropped. - A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2a01dc47..96e6748b6a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2836,7 +2836,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. -- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: changes between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. From 975c43a680432dc408f0b449ca1bdcc571e8eb96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:51:27 -0800 Subject: [PATCH 08/60] Plug-ins: correct the plugin.install fields and event delivery in docs/mcp.md docs/mcp.md now says that plugin.install lists only unknownCommands, and that a plug-in receives only the event kinds its manifest's events list names. The translated catalog rows for the event strings are removed; feature pull requests add English only. --- crates/ui-egui/src/i18n/bg.tsv | 1 - crates/ui-egui/src/i18n/bs.tsv | 1 - crates/ui-egui/src/i18n/ca.tsv | 10 ---------- crates/ui-egui/src/i18n/cs.tsv | 10 ---------- crates/ui-egui/src/i18n/da.tsv | 10 ---------- crates/ui-egui/src/i18n/de.tsv | 10 ---------- crates/ui-egui/src/i18n/el.tsv | 10 ---------- crates/ui-egui/src/i18n/es.tsv | 10 ---------- crates/ui-egui/src/i18n/fi.tsv | 10 ---------- crates/ui-egui/src/i18n/fr.tsv | 10 ---------- crates/ui-egui/src/i18n/gu.tsv | 1 - crates/ui-egui/src/i18n/hi.tsv | 10 ---------- crates/ui-egui/src/i18n/hu.tsv | 10 ---------- crates/ui-egui/src/i18n/id.tsv | 10 ---------- crates/ui-egui/src/i18n/it.tsv | 10 ---------- crates/ui-egui/src/i18n/ja.tsv | 10 ---------- crates/ui-egui/src/i18n/ka.tsv | 10 ---------- crates/ui-egui/src/i18n/ko.tsv | 10 ---------- crates/ui-egui/src/i18n/nl.tsv | 10 ---------- crates/ui-egui/src/i18n/pl.tsv | 10 ---------- crates/ui-egui/src/i18n/pt-br.tsv | 10 ---------- crates/ui-egui/src/i18n/ru.tsv | 10 ---------- crates/ui-egui/src/i18n/sv.tsv | 10 ---------- crates/ui-egui/src/i18n/tr.tsv | 10 ---------- crates/ui-egui/src/i18n/uk.tsv | 10 ---------- crates/ui-egui/src/i18n/vi.tsv | 10 ---------- crates/ui-egui/src/i18n/zh-hans.tsv | 10 ---------- crates/ui-egui/src/i18n/zh-hant.tsv | 10 ---------- docs/mcp.md | 7 ++++--- 29 files changed, 4 insertions(+), 256 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 7ad579423d..b7ad3eb99b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7405,7 +7405,6 @@ axis Y Axis Y ос Show its progress, see Cancel and write log lines Показване на напредъка, разпознаване на отказ и записване на редове в дневника Keep settings of its own Съхраняване на собствени настройки Keep a cache of its own, which you can clear Съхраняване на собствен кеш, който можете да изчистите - Run on its own when the selection, a document or a layer changes Изпълняване самостоятелно, когато се промени селекцията, документ или слой Run these commands on the document: {ids} Изпълняване на тези команди върху документа: {ids} Clear Plug-in Cache Изчистване на кеша на добавката # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b42abae79d..b125e378f5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6762,7 +6762,6 @@ axis Y Axis Y osa Show its progress, see Cancel and write log lines Prikazati napredak, prepoznati otkazivanje i zapisivati redove dnevnika Keep settings of its own Čuvati vlastite postavke Keep a cache of its own, which you can clear Čuvati vlastitu predmemoriju koju možete očistiti - Run on its own when the selection, a document or a layer changes Pokretati se samostalno kada se promijeni odabir, dokument ili sloj Run these commands on the document: {ids} Izvršavati ove naredbe na dokumentu: {ids} Clear Plug-in Cache Očisti predmemoriju dodatka @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} dozvola `{permission}` zahtijeva nivo API-ja dodataka {PROGRESS_API}: navedite `api` {PROGRESS_API} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a1f357f9e9..555080655a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7922,7 +7922,6 @@ variable-list-end {0}, {1} {0} i {1} Show its progress, see Cancel and write log lines Mostrar el progrés, detectar la cancel·lació i escriure línies de registre Keep settings of its own Desar una configuració pròpia Keep a cache of its own, which you can clear Desar una memòria cau pròpia, que podeu buidar - Run on its own when the selection, a document or a layer changes Executar-se per si sol quan canvia la selecció, un document o una capa Run these commands on the document: {ids} Executar aquestes ordres al document: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» inclou `{id}` a `commandAllowlist`, que un complement no pot cridar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7956,15 +7955,6 @@ variable-list-end {0}, {1} {0} i {1} @msg only a filter declares `inputs` només un filtre declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades -@msg `events` lists `{shown}` twice `events` inclou `{shown}` dues vegades -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anomena un esdeveniment desconegut `{shown}`: feu servir selection.changed, document.opened, document.saved o layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necessita el nivell d’API de complements {EVENTS_API}: indiqueu `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necessita el permís `events`, i `events` necessita una llista d’`events` -@msg event size ({len} bytes, limit {max}) mida de l’esdeveniment ({len} bytes, límit {max}) -@msg the module reacts to no events el mòdul no reacciona a cap esdeveniment -@msg vc_event returned {code} vc_event ha retornat {code} -@msg {name}: its {event} handler failed: {e} {name}: el seu gestor de {event} ha fallat: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: els seus esdeveniments estan desactivats fins que VectorCraft torni a iniciar-se, després de {count} gestors fallits seguits @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` @msg only a filter declares `writes` només un filtre declara `writes` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3bf50bbad7..8d11266cdd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7533,7 +7533,6 @@ axis Y Axis osa Y Show its progress, see Cancel and write log lines Zobrazit průběh, rozpoznat zrušení a zapisovat řádky protokolu Keep settings of its own Uchovávat vlastní nastavení Keep a cache of its own, which you can clear Uchovávat vlastní mezipaměť, kterou můžete vymazat - Run on its own when the selection, a document or a layer changes Spouštět se samostatně, když se změní výběr, dokument nebo vrstva Run these commands on the document: {ids} Spouštět v dokumentu tyto příkazy: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ uvádí v `commandAllowlist` příkaz `{id}`, který zásuvný modul nesmí volat @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7567,15 +7566,6 @@ axis Y Axis osa Y @msg only a filter declares `inputs` `inputs` deklaruje pouze filtr @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát -@msg `events` lists `{shown}` twice `events` uvádí `{shown}` dvakrát -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` uvádí neznámou událost `{shown}`: použijte selection.changed, document.opened, document.saved nebo layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vyžaduje úroveň API zásuvných modulů {EVENTS_API}: uveďte `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potřebuje oprávnění `events` a `events` potřebuje seznam `events` -@msg event size ({len} bytes, limit {max}) velikost události ({len} bajtů, limit {max}) -@msg the module reacts to no events modul nereaguje na žádné události -@msg vc_event returned {code} vc_event vrátila {code} -@msg {name}: its {event} handler failed: {e} {name}: jeho obslužná rutina {event} selhala: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jeho události jsou vypnuté, dokud se VectorCraft znovu nespustí, po {count} neúspěšných obslužných rutinách za sebou @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` @msg only a filter declares `writes` `writes` deklaruje pouze filtr diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 86e3898446..9820804ff0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -732,15 +732,6 @@ liquify-list-end {0}, {1} {0} og {1} @msg only a filter declares `inputs` kun et filter angiver `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange -@msg `events` lists `{shown}` twice `events` angiver `{shown}` to gange -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` angiver en ukendt hændelse `{shown}`: brug selection.changed, document.opened, document.saved eller layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kræver plug-in-API-niveau {EVENTS_API}: angiv `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` kræver tilladelsen `events`, og `events` kræver en liste `events` -@msg event size ({len} bytes, limit {max}) hændelsesstørrelse ({len} byte, grænse {max}) -@msg the module reacts to no events modulet reagerer ikke på nogen hændelser -@msg vc_event returned {code} vc_event returnerede {code} -@msg {name}: its {event} handler failed: {e} {name}: dens {event}-handler mislykkedes: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dens hændelser er slået fra, indtil VectorCraft starter igen, efter {count} mislykkede handlere i træk @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` @msg only a filter declares `writes` kun et filter angiver `writes` @@ -9773,7 +9764,6 @@ axis Y Axis Y-akse Show its progress, see Cancel and write log lines Vise sin fremdrift, se en annullering og skrive logrækker Keep settings of its own Gemme sine egne indstillinger Keep a cache of its own, which you can clear Gemme sin egen cache, som du kan rydde - Run on its own when the selection, a document or a layer changes Køre af sig selv, når markeringen, et dokument eller et lag ændres Run these commands on the document: {ids} Køre disse kommandoer på dokumentet: {ids} Clear Plug-in Cache Ryd plug-in-cache # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 93a3791445..d29f3c46c0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7114,7 +7114,6 @@ axis Y Axis Y-Achse Show its progress, see Cancel and write log lines Den Fortschritt anzeigen, ein Abbrechen erkennen und Protokollzeilen schreiben Keep settings of its own Eigene Einstellungen speichern Keep a cache of its own, which you can clear Einen eigenen Cache anlegen, den Sie leeren können - Run on its own when the selection, a document or a layer changes Von selbst ausgeführt werden, wenn sich die Auswahl, ein Dokument oder eine Ebene ändert Run these commands on the document: {ids} Diese Befehle im Dokument ausführen: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ führt `{id}` in `commandAllowlist` auf, den ein Plug-in nicht aufrufen darf @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7148,15 +7147,6 @@ axis Y Axis Y-Achse @msg only a filter declares `inputs` nur ein Filter deklariert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf -@msg `events` lists `{shown}` twice `events` führt `{shown}` doppelt auf -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nennt ein unbekanntes Ereignis `{shown}`: verwenden Sie selection.changed, document.opened, document.saved oder layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` braucht die Plug-in-API-Stufe {EVENTS_API}: Geben Sie `api` {EVENTS_API} an -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` braucht die Berechtigung `events`, und `events` braucht eine Liste `events` -@msg event size ({len} bytes, limit {max}) Ereignisgröße ({len} Byte, Grenze {max}) -@msg the module reacts to no events das Modul reagiert auf keine Ereignisse -@msg vc_event returned {code} vc_event hat {code} zurückgegeben -@msg {name}: its {event} handler failed: {e} {name}: sein Handler für {event} ist fehlgeschlagen: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seine Ereignisse sind aus, bis VectorCraft neu startet, nach {count} fehlgeschlagenen Handlern in Folge @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` @msg only a filter declares `writes` nur ein Filter deklariert `writes` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 5793976fc4..e4a651342a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7525,7 +7525,6 @@ axis Y Axis Άξονας Y Show its progress, see Cancel and write log lines Εμφάνιση της προόδου, αναγνώριση της ακύρωσης και εγγραφή γραμμών καταγραφής Keep settings of its own Διατήρηση δικών του ρυθμίσεων Keep a cache of its own, which you can clear Διατήρηση δικής του κρυφής μνήμης, την οποία μπορείτε να εκκαθαρίσετε - Run on its own when the selection, a document or a layer changes Εκτέλεση από μόνο του όταν αλλάζει η επιλογή, ένα έγγραφο ή ένα επίπεδο Run these commands on the document: {ids} Εκτέλεση αυτών των εντολών στο έγγραφο: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call το «{name}» αναφέρει το `{id}` στο `commandAllowlist`, το οποίο ένα πρόσθετο δεν επιτρέπεται να καλέσει @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7559,15 +7558,6 @@ axis Y Axis Άξονας Y @msg only a filter declares `inputs` μόνο ένα φίλτρο δηλώνει `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance το `inputs` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές -@msg `events` lists `{shown}` twice το `events` αναφέρει το `{shown}` δύο φορές -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed το `events` αναφέρει άγνωστο συμβάν `{shown}`: χρησιμοποιήστε selection.changed, document.opened, document.saved ή layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} το `events` χρειάζεται το επίπεδο API προσθέτων {EVENTS_API}: δώστε `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` το `events` χρειάζεται το δικαίωμα `events`, και το `events` χρειάζεται μια λίστα `events` -@msg event size ({len} bytes, limit {max}) μέγεθος συμβάντος ({len} byte, όριο {max}) -@msg the module reacts to no events η λειτουργική μονάδα δεν αντιδρά σε κανένα συμβάν -@msg vc_event returned {code} η vc_event επέστρεψε {code} -@msg {name}: its {event} handler failed: {e} {name}: ο χειριστής {event} του απέτυχε: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: τα συμβάντα του είναι απενεργοποιημένα μέχρι να ξεκινήσει ξανά το VectorCraft, μετά από {count} αποτυχημένους χειριστές στη σειρά @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` @msg only a filter declares `writes` μόνο ένα φίλτρο δηλώνει `writes` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c28838db0b..008a0b6483 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7511,7 +7511,6 @@ axis Y Axis Eje Y Show its progress, see Cancel and write log lines Mostrar su progreso, detectar la cancelación y escribir líneas de registro Keep settings of its own Guardar una configuración propia Keep a cache of its own, which you can clear Guardar una caché propia, que usted puede vaciar - Run on its own when the selection, a document or a layer changes Ejecutarse por sí solo cuando cambia la selección, un documento o una capa Run these commands on the document: {ids} Ejecutar estos comandos en el documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” incluye `{id}` en `commandAllowlist`, que un plugin no puede llamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7545,15 +7544,6 @@ axis Y Axis Eje Y @msg only a filter declares `inputs` solo un filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces -@msg `events` lists `{shown}` twice `events` incluye `{shown}` dos veces -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nombra un evento desconocido `{shown}`: use selection.changed, document.opened, document.saved o layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necesita el nivel de API de plugins {EVENTS_API}: indique `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necesita el permiso `events`, y `events` necesita una lista de `events` -@msg event size ({len} bytes, limit {max}) tamaño del evento ({len} bytes, límite {max}) -@msg the module reacts to no events el módulo no reacciona a ningún evento -@msg vc_event returned {code} vc_event devolvió {code} -@msg {name}: its {event} handler failed: {e} {name}: su controlador de {event} falló: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sus eventos están desactivados hasta que VectorCraft se inicie de nuevo, tras {count} controladores fallidos seguidos @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` @msg only a filter declares `writes` solo un filtro declara `writes` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 52c17b0d07..ffbeb6f49b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7602,7 +7602,6 @@ axis Y Axis Y-akseli Show its progress, see Cancel and write log lines Näyttää edistymisensä, havaita peruutuksen ja kirjoittaa lokirivejä Keep settings of its own Säilyttää omat asetuksensa Keep a cache of its own, which you can clear Säilyttää oman välimuistin, jonka voit tyhjentää - Run on its own when the selection, a document or a layer changes Käynnistyä itsestään, kun valinta, asiakirja tai taso muuttuu Run these commands on the document: {ids} Suorittaa nämä komennot asiakirjassa: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” luettelee `commandAllowlist`-luettelossa komennon `{id}`, jota laajennus ei saa kutsua @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7636,15 +7635,6 @@ axis Y Axis Y-akseli @msg only a filter declares `inputs` vain suodatin voi määrittää `inputs`-avaimen @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti -@msg `events` lists `{shown}` twice `events` luettelee kohteen `{shown}` kahdesti -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nimeää tuntemattoman tapahtuman `{shown}`: käytä arvoa selection.changed, document.opened, document.saved tai layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vaatii laajennus-API:n tason {EVENTS_API}: anna `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` tarvitsee käyttöoikeuden `events`, ja `events` tarvitsee `events`-luettelon -@msg event size ({len} bytes, limit {max}) tapahtuman koko ({len} tavua, raja {max}) -@msg the module reacts to no events moduuli ei reagoi mihinkään tapahtumaan -@msg vc_event returned {code} vc_event palautti {code} -@msg {name}: its {event} handler failed: {e} {name}: sen {event}-käsittelijä epäonnistui: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sen tapahtumat ovat pois päältä, kunnes VectorCraft käynnistyy uudelleen, {count} peräkkäin epäonnistuneen käsittelijän jälkeen @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` @msg only a filter declares `writes` vain suodatin voi määrittää `writes`-avaimen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dc7c27f2c1..7e03e3b7c4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7529,7 +7529,6 @@ axis Y Axis Axe Y Show its progress, see Cancel and write log lines Afficher sa progression, détecter l’annulation et écrire des lignes de journal Keep settings of its own Conserver ses propres réglages Keep a cache of its own, which you can clear Conserver son propre cache, que vous pouvez vider - Run on its own when the selection, a document or a layer changes S’exécuter de lui-même quand la sélection, un document ou un calque change Run these commands on the document: {ids} Exécuter ces commandes sur le document : {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call « {name} » indique `{id}` dans `commandAllowlist`, qu’un module externe ne peut pas appeler @msg vc_call `{shown}`: {why} vc_call `{shown}` : {why} @@ -7564,15 +7563,6 @@ axis Y Axis Axe Y @msg only a filter declares `inputs` seul un filtre déclare `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois -@msg `events` lists `{shown}` twice `events` mentionne `{shown}` deux fois -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` désigne un événement inconnu `{shown}`, utilisez selection.changed, document.opened, document.saved ou layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` nécessite le niveau d’API de module externe {EVENTS_API}, indiquez `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` a besoin de l’autorisation `events`, et `events` a besoin d’une liste `events` -@msg event size ({len} bytes, limit {max}) taille de l’événement ({len} octets, limite {max}) -@msg the module reacts to no events le module ne réagit à aucun événement -@msg vc_event returned {code} vc_event a renvoyé {code} -@msg {name}: its {event} handler failed: {e} {name} : son gestionnaire {event} a échoué : {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name} : ses événements sont désactivés jusqu’au prochain démarrage de VectorCraft, après {count} gestionnaires en échec d’affilée @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` @msg only a filter declares `writes` seul un filtre déclare `writes` diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c14d54ee4..497ef4d6d8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2039,7 +2039,6 @@ Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો Keep a cache of its own, which you can clear તેનું પોતાનું કેશ રાખો, જે તમે સાફ કરી શકો છો - Run on its own when the selection, a document or a layer changes પસંદગી, દસ્તાવેજ અથવા લેયર બદલાય ત્યારે આપમેળે ચાલો Keep a link to an image file instead of only embedding it ઇમેજ ફાઇલને ફક્ત એમ્બેડ કરવાને બદલે તેની લિંક રાખો Keep both sides the same width બંને બાજુ સમાન પહોળાઈ રાખો Keep data of its own with the document દસ્તાવેજ સાથે પોતાનો ડેટા રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5acd19bcd8..8ad28968c5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6686,7 +6686,6 @@ arrowhead Feather पंख Show its progress, see Cancel and write log lines अपनी प्रगति दिखाना, रद्द करने का अनुरोध देखना और लॉग पंक्तियाँ लिखना Keep settings of its own अपनी सेटिंग्स रखना Keep a cache of its own, which you can clear अपना कैश रखना, जिसे आप साफ़ कर सकते हैं - Run on its own when the selection, a document or a layer changes सिलेक्शन, कोई डॉक्यूमेंट या कोई लेयर बदलने पर अपने आप चलना Run these commands on the document: {ids} दस्तावेज़ पर ये कमांड चलाना: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” `commandAllowlist` में `{id}` सूचीबद्ध करता है, जिसे कोई प्लग-इन कॉल नहीं कर सकता @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -6720,15 +6719,6 @@ arrowhead Feather पंख @msg only a filter declares `inputs` केवल फ़िल्टर `inputs` घोषित करता है @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है -@msg `events` lists `{shown}` twice `events` में `{shown}` दो बार सूचीबद्ध है -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` में अज्ञात इवेंट `{shown}` है: selection.changed, document.opened, document.saved या layer.changed का उपयोग करें -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` के लिए प्लग-इन API स्तर {EVENTS_API} चाहिए: `api` {EVENTS_API} दें -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` को `events` अनुमति चाहिए, और `events` को `events` की सूची चाहिए -@msg event size ({len} bytes, limit {max}) इवेंट का आकार ({len} बाइट्स, सीमा {max}) -@msg the module reacts to no events मॉड्यूल किसी भी इवेंट पर प्रतिक्रिया नहीं करता -@msg vc_event returned {code} vc_event ने {code} लौटाया -@msg {name}: its {event} handler failed: {e} {name}: इसका {event} हैंडलर विफल हुआ: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: लगातार {count} हैंडलर विफल होने के बाद, VectorCraft के फिर से शुरू होने तक इसके इवेंट बंद हैं @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है @msg only a filter declares `writes` केवल फ़िल्टर `writes` घोषित करता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index da7fda0f8d..3116815efa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7518,7 +7518,6 @@ axis Y Axis Y tengely Show its progress, see Cancel and write log lines Megjelenítheti az előrehaladását, észlelheti a megszakítást és naplósorokat írhat Keep settings of its own Saját beállításokat tárolhat Keep a cache of its own, which you can clear Saját gyorsítótárat tárolhat, amelyet Ön kiüríthet - Run on its own when the selection, a document or a layer changes Magától futhat, amikor a kijelölés, egy dokumentum vagy egy réteg megváltozik Run these commands on the document: {ids} Ezeket a parancsokat futtathatja a dokumentumon: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call a(z) „{name}” a(z) `{id}` parancsot sorolja fel a `commandAllowlist` listában, amelyet bővítmény nem hívhat meg @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7552,15 +7551,6 @@ axis Y Axis Y tengely @msg only a filter declares `inputs` `inputs` kulcsot csak szűrő adhat meg @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance az `inputs` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` -@msg `events` lists `{shown}` twice az `events` kétszer sorolja fel ezt: `{shown}` -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed az `events` ismeretlen eseményt nevez meg: `{shown}`; használja a selection.changed, document.opened, document.saved vagy layer.changed értéket -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} az `events` listához {EVENTS_API}. szintű bővítmény-API kell: adja meg az `api` {EVENTS_API} értéket -@msg `events` needs the permission `events`, and `events` needs a list of `events` az `events` listához az `events` engedély szükséges, az `events` engedélyhez pedig `events` lista -@msg event size ({len} bytes, limit {max}) esemény mérete ({len} bájt, korlát {max}) -@msg the module reacts to no events a modul egyetlen eseményre sem reagál -@msg vc_event returned {code} a vc_event {code} értéket adott vissza -@msg {name}: its {event} handler failed: {e} {name}: a(z) {event} kezelője sikertelen volt: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: az eseményei ki vannak kapcsolva a VectorCraft következő indításáig, {count} egymást követő sikertelen kezelő után @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges @msg only a filter declares `writes` `writes` kulcsot csak szűrő adhat meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7a7852a3e2..b159d2bfb7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -613,15 +613,6 @@ @msg only a filter declares `inputs` hanya filter yang mendeklarasikan `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali -@msg `events` lists `{shown}` twice `events` mencantumkan `{shown}` dua kali -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` menyebut peristiwa yang tidak dikenal `{shown}`: gunakan selection.changed, document.opened, document.saved atau layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` memerlukan API plug-in tingkat {EVENTS_API}: berikan `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` memerlukan izin `events`, dan `events` memerlukan daftar `events` -@msg event size ({len} bytes, limit {max}) ukuran peristiwa ({len} byte, batas {max}) -@msg the module reacts to no events modul tidak bereaksi terhadap peristiwa apa pun -@msg vc_event returned {code} vc_event mengembalikan {code} -@msg {name}: its {event} handler failed: {e} {name}: handler {event}-nya gagal: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: event-nya dimatikan hingga VectorCraft dimulai lagi, setelah {count} handler gagal berturut-turut @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` @msg only a filter declares `writes` hanya filter yang mendeklarasikan `writes` @@ -7555,7 +7546,6 @@ axis Y Axis Sumbu Y Show its progress, see Cancel and write log lines Menampilkan kemajuannya, mengenali pembatalan, dan menulis baris log Keep settings of its own Menyimpan pengaturannya sendiri Keep a cache of its own, which you can clear Menyimpan cache-nya sendiri, yang dapat Anda kosongkan - Run on its own when the selection, a document or a layer changes Berjalan sendiri saat seleksi, dokumen, atau lapisan berubah Run these commands on the document: {ids} Menjalankan perintah ini pada dokumen: {ids} Clear Plug-in Cache Kosongkan cache plug-in # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5333bdc0b3..d6b341a367 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7153,7 +7153,6 @@ axis Y Axis Asse Y Show its progress, see Cancel and write log lines Mostrare il proprio avanzamento, rilevare l’annullamento e scrivere righe di registro Keep settings of its own Conservare impostazioni proprie Keep a cache of its own, which you can clear Conservare una cache propria, che è possibile svuotare - Run on its own when the selection, a document or a layer changes Eseguirsi da solo quando cambia la selezione, un documento o un livello Run these commands on the document: {ids} Eseguire questi comandi sul documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” elenca `{id}` in `commandAllowlist`, che un plug-in non può chiamare @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7187,15 +7186,6 @@ axis Y Axis Asse Y @msg only a filter declares `inputs` solo un filtro dichiara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte -@msg `events` lists `{shown}` twice `events` elenca `{shown}` due volte -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` indica un evento sconosciuto `{shown}`: usa selection.changed, document.opened, document.saved o layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` richiede il livello API dei plug-in {EVENTS_API}: indicare `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` richiede l’autorizzazione `events`, e `events` richiede un elenco `events` -@msg event size ({len} bytes, limit {max}) dimensione dell’evento ({len} byte, limite {max}) -@msg the module reacts to no events il modulo non reagisce ad alcun evento -@msg vc_event returned {code} vc_event ha restituito {code} -@msg {name}: its {event} handler failed: {e} {name}: il suo gestore di {event} non è riuscito: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: i suoi eventi sono disattivati finché VectorCraft non si riavvia, dopo {count} gestori non riusciti di fila @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` @msg only a filter declares `writes` solo un filtro dichiara `writes` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b9f738160e..48f6dd36cf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7228,7 +7228,6 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 進行状況の表示、キャンセルの検知、ログ行の書き込み Keep settings of its own 独自の設定の保持 Keep a cache of its own, which you can clear 消去できる独自のキャッシュの保持 - Run on its own when the selection, a document or a layer changes 選択、ドキュメント、またはレイヤーが変わったときの自動実行 Run these commands on the document: {ids} ドキュメントでのこれらのコマンドの実行: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」は `commandAllowlist` にプラグインが呼び出せない `{id}` を挙げています @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7262,15 +7261,6 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` `inputs` を宣言できるのはフィルターだけです @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています -@msg `events` lists `{shown}` twice `events` に `{shown}` が 2 回指定されています -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` に不明なイベント `{shown}` があります。selection.changed、document.opened、document.saved、layer.changed のいずれかを使ってください -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` にはプラグイン API レベル {EVENTS_API} が必要です。`api` {EVENTS_API} を指定してください -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` には権限 `events` が必要で、`events` には `events` のリストが必要です -@msg event size ({len} bytes, limit {max}) イベントサイズ ({len} バイト、上限 {max}) -@msg the module reacts to no events このモジュールはどのイベントにも反応しません -@msg vc_event returned {code} vc_event が {code} を返しました -@msg {name}: its {event} handler failed: {e} {name}: {event} のハンドラーが失敗しました: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: ハンドラーが {count} 回続けて失敗したため、VectorCraft を再起動するまでイベントはオフです @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です @msg only a filter declares `writes` `writes` を宣言できるのはフィルターだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5af6b8a652..cbb58ee5ab 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9640,7 +9640,6 @@ axis Y Axis Y ღერძი Show its progress, see Cancel and write log lines პროგრესის ჩვენება, გაუქმების შემჩნევა და ჟურნალის სტრიქონების ჩაწერა Keep settings of its own საკუთარი პარამეტრების შენახვა Keep a cache of its own, which you can clear საკუთარი ქეშის შენახვა, რომლის გასუფთავებაც შეგიძლიათ - Run on its own when the selection, a document or a layer changes თავისით გაშვება, როცა იცვლება მონიშნული, დოკუმენტი ან შრე Run these commands on the document: {ids} ამ ბრძანებების გაშვება დოკუმენტზე: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ `commandAllowlist`-ში ასახელებს `{id}`-ს, რომლის გამოძახებაც პლაგინს არ შეუძლია @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -9674,15 +9673,6 @@ axis Y Axis Y ღერძი @msg only a filter declares `inputs` `inputs`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი -@msg `events` lists `{shown}` twice `events`-ში `{shown}` ორჯერაა ჩამოთვლილი -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` უცნობ მოვლენას ასახელებს `{shown}`: გამოიყენეთ selection.changed, document.opened, document.saved ან layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`-ს სჭირდება პლაგინის API-ის დონე {EVENTS_API}: მიუთითეთ `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`-ს სჭირდება ნებართვა `events`, ხოლო `events`-ს სჭირდება `events`-ის სია -@msg event size ({len} bytes, limit {max}) მოვლენის ზომა ({len} ბაიტი, ლიმიტი {max}) -@msg the module reacts to no events მოდული არცერთ მოვლენაზე არ რეაგირებს -@msg vc_event returned {code} vc_event-მა დააბრუნა {code} -@msg {name}: its {event} handler failed: {e} {name}: მისი {event} დამმუშავებელი ვერ შესრულდა: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: მისი მოვლენები გამორთულია VectorCraft-ის ხელახლა გაშვებამდე, ზედიზედ {count} წარუმატებელი დამმუშავებლის შემდეგ @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` @msg only a filter declares `writes` `writes`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f5e2ff281b..bd430d2fc1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7125,7 +7125,6 @@ axis Y Axis Y축 Show its progress, see Cancel and write log lines 진행률 표시, 취소 감지 및 로그 줄 쓰기 Keep settings of its own 자체 설정 보관 Keep a cache of its own, which you can clear 지울 수 있는 자체 캐시 보관 - Run on its own when the selection, a document or a layer changes 선택 영역, 문서 또는 레이어가 바뀔 때 자동 실행 Run these commands on the document: {ids} 문서에서 다음 명령 실행: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”의 `commandAllowlist`에 플러그인이 호출할 수 없는 `{id}`가 있습니다 @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7159,15 +7158,6 @@ axis Y Axis Y축 @msg only a filter declares `inputs` 필터만 `inputs`를 선언할 수 있습니다 @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 -@msg `events` lists `{shown}` twice `events`에 `{shown}`이(가) 두 번 나열되어 있습니다 -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events`에 알 수 없는 이벤트 `{shown}`이(가) 있습니다. selection.changed, document.opened, document.saved 또는 layer.changed를 사용하세요 -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`에는 플러그인 API 수준 {EVENTS_API}이(가) 필요합니다. `api` {EVENTS_API}을(를) 지정하십시오 -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`에는 `events` 권한이 필요하고, `events`에는 `events` 목록이 필요합니다 -@msg event size ({len} bytes, limit {max}) 이벤트 크기({len}바이트, 제한 {max}) -@msg the module reacts to no events 이 모듈은 어떤 이벤트에도 반응하지 않습니다 -@msg vc_event returned {code} vc_event가 {code}을(를) 반환했습니다 -@msg {name}: its {event} handler failed: {e} {name}: {event} 처리기가 실패했습니다: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: 처리기가 {count}번 연속 실패하여 VectorCraft를 다시 시작할 때까지 이벤트가 꺼집니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 @msg only a filter declares `writes` 필터만 `writes`를 선언할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2c32ec717a..20365f1488 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -575,15 +575,6 @@ liquify-list-end {0}, {1} {0} en {1} @msg only a filter declares `inputs` alleen een filter declareert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` noemt een onbekend objectsoort `{shown}`: gebruik type, image of symbolInstance @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer -@msg `events` lists `{shown}` twice `events` noemt `{shown}` twee keer -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` noemt een onbekende gebeurtenis `{shown}`: gebruik selection.changed, document.opened, document.saved of layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vereist plug-in-API-niveau {EVENTS_API}: geef `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` vereist de machtiging `events`, en `events` vereist een lijst `events` -@msg event size ({len} bytes, limit {max}) gebeurtenisgrootte ({len} bytes, limiet {max}) -@msg the module reacts to no events de module reageert op geen enkele gebeurtenis -@msg vc_event returned {code} vc_event gaf {code} terug -@msg {name}: its {event} handler failed: {e} {name}: de handler voor {event} is mislukt: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: de gebeurtenissen staan uit tot VectorCraft opnieuw start, na {count} mislukte handlers op rij @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` @msg only a filter declares `writes` alleen een filter declareert `writes` @@ -9617,7 +9608,6 @@ axis Y Axis Y-as Show its progress, see Cancel and write log lines De voortgang tonen, een annulering zien en logregels schrijven Keep settings of its own Eigen instellingen bewaren Keep a cache of its own, which you can clear Een eigen cache bewaren, die u kunt legen - Run on its own when the selection, a document or a layer changes Vanzelf worden uitgevoerd wanneer de selectie, een document of een laag verandert Run these commands on the document: {ids} Deze opdrachten op het document uitvoeren: {ids} Clear Plug-in Cache Plug-incache legen # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index be3c2a0666..4a22a1dd93 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7386,7 +7386,6 @@ axis Y Axis Oś Y Show its progress, see Cancel and write log lines Pokazywać swój postęp, wykrywać anulowanie i zapisywać wiersze dziennika Keep settings of its own Przechowywać własne ustawienia Keep a cache of its own, which you can clear Przechowywać własną pamięć podręczną, którą możesz wyczyścić - Run on its own when the selection, a document or a layer changes Uruchamiać się samodzielnie, gdy zmieni się zaznaczenie, dokument lub warstwa Run these commands on the document: {ids} Uruchamiać w dokumencie te polecenia: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}” wymienia w `commandAllowlist` polecenie `{id}`, którego wtyczka nie może wywołać @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7420,15 +7419,6 @@ axis Y Axis Oś Y @msg only a filter declares `inputs` tylko filtr deklaruje `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy -@msg `events` lists `{shown}` twice `events` wymienia `{shown}` dwa razy -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` wymienia nieznane zdarzenie `{shown}`: użyj selection.changed, document.opened, document.saved lub layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` wymaga poziomu API wtyczek {EVENTS_API}: podaj `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potrzebuje uprawnienia `events`, a `events` potrzebuje listy `events` -@msg event size ({len} bytes, limit {max}) rozmiar zdarzenia ({len} bajtów, limit {max}) -@msg the module reacts to no events moduł nie reaguje na żadne zdarzenia -@msg vc_event returned {code} vc_event zwróciła {code} -@msg {name}: its {event} handler failed: {e} {name}: jego procedura obsługi {event} nie powiodła się: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jego zdarzenia są wyłączone do ponownego uruchomienia VectorCraft, po {count} nieudanych procedurach obsługi z rzędu @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` @msg only a filter declares `writes` tylko filtr deklaruje `writes` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4a7e033cc5..6d910ce85f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7432,7 +7432,6 @@ axis Y Axis Eixo Y Show its progress, see Cancel and write log lines Mostrar seu progresso, detectar o cancelamento e gravar linhas de log Keep settings of its own Guardar configurações próprias Keep a cache of its own, which you can clear Guardar um cache próprio, que você pode limpar - Run on its own when the selection, a document or a layer changes Executar-se sozinho quando a seleção, um documento ou uma camada muda Run these commands on the document: {ids} Executar estes comandos no documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” lista `{id}` em `commandAllowlist`, que um plug-in não pode chamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7466,15 +7465,6 @@ axis Y Axis Eixo Y @msg only a filter declares `inputs` somente um filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes -@msg `events` lists `{shown}` twice `events` lista `{shown}` duas vezes -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` cita um evento desconhecido `{shown}`: use selection.changed, document.opened, document.saved ou layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` exige o nível de API de plug-in {EVENTS_API}: informe `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` precisa da permissão `events`, e `events` precisa de uma lista de `events` -@msg event size ({len} bytes, limit {max}) tamanho do evento ({len} bytes, limite {max}) -@msg the module reacts to no events o módulo não reage a nenhum evento -@msg vc_event returned {code} vc_event retornou {code} -@msg {name}: its {event} handler failed: {e} {name}: seu manipulador de {event} falhou: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seus eventos estão desativados até o VectorCraft iniciar de novo, após {count} manipuladores com falha seguidos @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` @msg only a filter declares `writes` somente um filtro declara `writes` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 151d5d5256..60906af64a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7155,7 +7155,6 @@ axis Y Axis Ось Y Show its progress, see Cancel and write log lines Показывать свой ход выполнения, замечать отмену и записывать строки журнала Keep settings of its own Хранить собственные настройки Keep a cache of its own, which you can clear Хранить собственный кэш, который можно очистить - Run on its own when the selection, a document or a layer changes Запускаться самостоятельно, когда меняется выделение, документ или слой Run these commands on the document: {ids} Выполнять в документе эти команды: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» указывает в `commandAllowlist` команду `{id}`, которую модуль вызывать не может @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7189,15 +7188,6 @@ axis Y Axis Ось Y @msg only a filter declares `inputs` `inputs` может объявлять только фильтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды -@msg `events` lists `{shown}` twice в `events` `{shown}` указано дважды -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано неизвестное событие `{shown}`: используйте selection.changed, document.opened, document.saved или layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` нужен уровень API модулей {EVENTS_API}: укажите `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` нужно разрешение `events`, а для `events` нужен список `events` -@msg event size ({len} bytes, limit {max}) размер события ({len} байт, предел {max}) -@msg the module reacts to no events модуль не реагирует ни на какие события -@msg vc_event returned {code} vc_event вернула {code} -@msg {name}: its {event} handler failed: {e} {name}: его обработчик {event} завершился ошибкой: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: его события отключены до следующего запуска VectorCraft после {count} неудачных обработчиков подряд @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` @msg only a filter declares `writes` `writes` может объявлять только фильтр diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 21f2954bb4..bf7420d255 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7535,7 +7535,6 @@ axis Y Axis Y-axel Show its progress, see Cancel and write log lines Visa sitt förlopp, se när det avbryts och skriva loggrader Keep settings of its own Spara egna inställningar Keep a cache of its own, which you can clear Spara en egen cache, som du kan tömma - Run on its own when the selection, a document or a layer changes Köras av sig själv när markeringen, ett dokument eller ett lager ändras Run these commands on the document: {ids} Köra dessa kommandon på dokumentet: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” anger `{id}` i `commandAllowlist`, som ett plugin inte får anropa @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7569,15 +7568,6 @@ axis Y Axis Y-axel @msg only a filter declares `inputs` bara ett filter anger `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger -@msg `events` lists `{shown}` twice `events` anger `{shown}` två gånger -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anger en okänd händelse `{shown}`: använd selection.changed, document.opened, document.saved eller layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kräver plugin-API-nivå {EVENTS_API}: ange `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` behöver behörigheten `events`, och `events` behöver en lista `events` -@msg event size ({len} bytes, limit {max}) händelsestorlek ({len} byte, gräns {max}) -@msg the module reacts to no events modulen reagerar inte på några händelser -@msg vc_event returned {code} vc_event returnerade {code} -@msg {name}: its {event} handler failed: {e} {name}: dess {event}-hanterare misslyckades: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dess händelser är avstängda tills VectorCraft startas igen, efter {count} misslyckade hanterare i rad @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` @msg only a filter declares `writes` bara ett filter anger `writes` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3584b85291..830b60e56b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7605,7 +7605,6 @@ axis Y Axis Y ekseni Show its progress, see Cancel and write log lines İlerlemesini gösterme, iptali algılama ve günlük satırları yazma Keep settings of its own Kendi ayarlarını saklama Keep a cache of its own, which you can clear Temizleyebileceğiniz kendi önbelleğini saklama - Run on its own when the selection, a document or a layer changes Seçim, bir belge veya bir katman değiştiğinde kendiliğinden çalışma Run these commands on the document: {ids} Belgede şu komutları çalıştırma: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”, `commandAllowlist` içinde bir eklentinin çağıramayacağı `{id}` komutunu listeliyor @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7639,15 +7638,6 @@ axis Y Axis Y ekseni @msg only a filter declares `inputs` `inputs` yalnızca bir filtrede bildirilebilir @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor -@msg `events` lists `{shown}` twice `events` `{shown}` değerini iki kez listeliyor -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` bilinmeyen bir olay belirtiyor: `{shown}`; selection.changed, document.opened, document.saved veya layer.changed kullanın -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` için eklenti API düzeyi {EVENTS_API} gerekir: `api` {EVENTS_API} verin -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` için `events` izni, `events` izni için de bir `events` listesi gerekir -@msg event size ({len} bytes, limit {max}) olay boyutu ({len} bayt, sınır {max}) -@msg the module reacts to no events modül hiçbir olaya tepki vermiyor -@msg vc_event returned {code} vc_event {code} döndürdü -@msg {name}: its {event} handler failed: {e} {name}: {event} işleyicisi başarısız oldu: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: art arda {count} işleyici başarısız olduğundan, VectorCraft yeniden başlayana kadar olayları kapalı @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir @msg only a filter declares `writes` `writes` yalnızca bir filtrede bildirilebilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 233929fc1b..09a9e4bf6d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7135,7 +7135,6 @@ axis Y Axis Вісь Y Show its progress, see Cancel and write log lines Показувати свій поступ, помічати скасування і записувати рядки журналу Keep settings of its own Зберігати власні налаштування Keep a cache of its own, which you can clear Зберігати власний кеш, який можна очистити - Run on its own when the selection, a document or a layer changes Запускатися самостійно, коли змінюється виділення, документ або шар Run these commands on the document: {ids} Виконувати в документі ці команди: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» вказує в `commandAllowlist` команду `{id}`, яку модуль викликати не може @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7169,15 +7168,6 @@ axis Y Axis Вісь Y @msg only a filter declares `inputs` `inputs` може оголошувати лише фільтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі -@msg `events` lists `{shown}` twice в `events` `{shown}` указано двічі -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано невідому подію `{shown}`: використовуйте selection.changed, document.opened, document.saved або layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` потрібен рівень API модулів {EVENTS_API}: укажіть `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` потрібен дозвіл `events`, а для `events` потрібен список `events` -@msg event size ({len} bytes, limit {max}) розмір події ({len} байтів, межа {max}) -@msg the module reacts to no events модуль не реагує на жодні події -@msg vc_event returned {code} vc_event повернула {code} -@msg {name}: its {event} handler failed: {e} {name}: його обробник {event} завершився помилкою: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: його події вимкнено до наступного запуску VectorCraft після {count} невдалих обробників поспіль @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` @msg only a filter declares `writes` `writes` може оголошувати лише фільтр diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3251b61524..bc63725d0f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7184,7 +7184,6 @@ axis Y Axis Trục Y Show its progress, see Cancel and write log lines Hiển thị tiến độ, nhận biết yêu cầu hủy và ghi các dòng nhật ký Keep settings of its own Lưu cài đặt riêng Keep a cache of its own, which you can clear Lưu bộ nhớ đệm riêng mà bạn có thể xóa - Run on its own when the selection, a document or a layer changes Tự chạy khi vùng chọn, một tài liệu hoặc một lớp thay đổi Run these commands on the document: {ids} Chạy các lệnh này trên tài liệu: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” liệt kê `{id}` trong `commandAllowlist`, lệnh mà plug-in không được gọi @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7218,15 +7217,6 @@ axis Y Axis Trục Y @msg only a filter declares `inputs` chỉ bộ lọc mới khai báo `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần -@msg `events` lists `{shown}` twice `events` liệt kê `{shown}` hai lần -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nêu một sự kiện không xác định `{shown}`: dùng selection.changed, document.opened, document.saved hoặc layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` cần API plug-in cấp {EVENTS_API}: hãy đặt `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` cần quyền `events`, và `events` cần một danh sách `events` -@msg event size ({len} bytes, limit {max}) kích thước sự kiện ({len} byte, giới hạn {max}) -@msg the module reacts to no events mô-đun không phản ứng với sự kiện nào -@msg vc_event returned {code} vc_event trả về {code} -@msg {name}: its {event} handler failed: {e} {name}: trình xử lý {event} của nó đã thất bại: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: các sự kiện của nó bị tắt cho đến khi VectorCraft khởi động lại, sau {count} trình xử lý thất bại liên tiếp @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` @msg only a filter declares `writes` chỉ bộ lọc mới khai báo `writes` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e4d122520a..9b7e1c7bbc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7365,7 +7365,6 @@ axis Y Axis Y 轴 Show its progress, see Cancel and write log lines 显示进度、检测取消请求并写入日志行 Keep settings of its own 保存自己的设置 Keep a cache of its own, which you can clear 保存自己的缓存,您可以清除它 - Run on its own when the selection, a document or a layer changes 在所选对象、文档或图层发生变化时自动运行 Run these commands on the document: {ids} 在文档上运行这些命令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”在 `commandAllowlist` 中列出了增效工具不能调用的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7399,15 +7398,6 @@ axis Y Axis Y 轴 @msg only a filter declares `inputs` 只有滤镜才能声明 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` -@msg `events` lists `{shown}` twice `events` 列出了两次 `{shown}` -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:请使用 selection.changed、document.opened、document.saved 或 layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效工具 API 级别 {EVENTS_API}:请设置 `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要权限 `events`,而 `events` 需要 `events` 列表 -@msg event size ({len} bytes, limit {max}) 事件大小({len} 字节,上限 {max}) -@msg the module reacts to no events 该模块不响应任何事件 -@msg vc_event returned {code} vc_event 返回了 {code} -@msg {name}: its {event} handler failed: {e} {name}:其 {event} 处理程序失败:{e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:处理程序连续 {count} 次失败,其事件已关闭,直到 VectorCraft 再次启动 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` @msg only a filter declares `writes` 只有滤镜才能声明 `writes` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9fdb9c2d32..2e3bae2d60 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7184,7 +7184,6 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 顯示進度、偵測取消要求並寫入記錄行 Keep settings of its own 保存自己的設定 Keep a cache of its own, which you can clear 保存自己的快取,您可以清除它 - Run on its own when the selection, a document or a layer changes 在選取範圍、文件或圖層變更時自動執行 Run these commands on the document: {ids} 在文件上執行這些指令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」在 `commandAllowlist` 中列出了增效模組不能呼叫的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7218,15 +7217,6 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` 只有濾鏡才能宣告 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` -@msg `events` lists `{shown}` twice `events` 列出了兩次 `{shown}` -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:請使用 selection.changed、document.opened、document.saved 或 layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效模組 API 層級 {EVENTS_API}:請設定 `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要權限 `events`,而 `events` 需要 `events` 清單 -@msg event size ({len} bytes, limit {max}) 事件大小({len} 位元組,上限 {max}) -@msg the module reacts to no events 此模組不回應任何事件 -@msg vc_event returned {code} vc_event 傳回了 {code} -@msg {name}: its {event} handler failed: {e} {name}:其 {event} 處理常式失敗:{e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:處理常式連續 {count} 次失敗,其事件已關閉,直到 VectorCraft 再次啟動 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` @msg only a filter declares `writes` 只有濾鏡才能宣告 `writes` diff --git a/docs/mcp.md b/docs/mcp.md index 37378a385f..1c39001b62 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15201,9 +15201,10 @@ while it runs, through `vc_call`: the calls and its output are one undo step, an fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in, switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as -`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A plug-in at API level 2 -whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given `selection.changed`, -`document.opened`, `document.saved` and `layer.changed` events through `vc_event` once the change has finished; +`refusedCommands` and ids no command has as `unknownCommands`; `plugin.install` also lists the `unknownCommands`. A plug-in +at API level 2 whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given the events +of the kinds its `events` list names, from `selection.changed`, `document.opened`, `document.saved` and `layer.changed`, +through `vc_event` once the change has finished; its handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). A live-effect plug-in is an effect with id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` From 9d175f4e857fdbcec24296c1ea4b7f25fd2ab1f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:46:20 -0800 Subject: [PATCH 09/60] Scripts: pathItems.removeAll() refuses paths on a locked artboard pathItems.removeAll() deleted paths on a locked artboard, while pageItems.removeAll() and remove() throw for them. It now throws the same error and deletes nothing when any path, a path in a group included, is on a locked artboard. Applied on main's paths module, whose import list now also names ON_LOCKED_ARTBOARD. --- crates/engine/src/script/dom/paths.rs | 19 +++++++++++----- crates/engine/src/tests/script_dom_paths.rs | 25 +++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4f6bb203e..bd015204f0 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -67,9 +67,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, coordinate, doc_of, - edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, - on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, + Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value, + coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, + named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -434,18 +434,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before +/// anything is deleted, as `pageItems.removeAll()` is stopped. 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, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 87f1c4f9ab..0df78310e1 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -98,6 +98,31 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes +/// nothing, as `pageItems.removeAll()` and `remove()` do. +#[test] +fn path_items_remove_all_refuses_paths_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()) && e.contains(&b.0.to_string()), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); +} + #[test] fn shape_creators_use_documented_defaults_and_y_up() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..e26accec83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3098,7 +3098,8 @@ through `$`: themselves that this page does not describe are not defined yet and read as `undefined`. - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, - `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new + `getByName(name)`, `removeAll()` (when any path is on a locked artboard, it throws + `cannot delete objects on a locked artboard` and deletes nothing), `add()` (a path with no points, from `path.create`, painted as new art; when new art has no fill and no stroke, the path has neither), and the shape creators `rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`, From e861b20a33f10e95fe9e7afb3fdc28448d7f7e43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:46:54 -0800 Subject: [PATCH 10/60] Scripts: pathItems reads a path by name as pageItems does pathItems["name"] read as undefined and "name" in pathItems was false even when a path had that name, while pageItems gives the object getByName gives. pathItems now does the same: a read with a name nothing has throws Not found, and the in test is false for it. Applied on main's paths module, keeping its import list. --- crates/engine/src/script/dom/paths.rs | 7 +++++++ crates/engine/src/tests/script_dom_paths.rs | 16 ++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index bd015204f0..fdd850e9a0 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -404,8 +404,15 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } +/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return match items_by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined), + r => r, + }; + } 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)))) diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 0df78310e1..b842932244 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -98,6 +98,22 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// `pathItems` read with a name gives what `getByName` gives, and throws as it does for no match, +/// as `pageItems` does. +#[test] +fn path_items_read_with_a_name_give_the_named_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems, m = [];\ + vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ + try { p['nosuch']; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); +} + /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e26accec83..65adfa8627 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3097,7 +3097,8 @@ through `$`: those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves that this page does not describe are not defined yet and read as `undefined`. - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the - order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, + order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `[name]` (read as + `pageItems["name"]` is read), `index(key)`, `getByName(name)`, `removeAll()` (when any path is on a locked artboard, it throws `cannot delete objects on a locked artboard` and deletes nothing), `add()` (a path with no points, from `path.create`, painted as new art; when new art has no fill and no stroke, the path has neither), and the shape creators From 330aa4dffbc538222a9c7f52232c58d2f674a059 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:27:06 -0800 Subject: [PATCH 11/60] Plug-ins: deliver events after headless gestures and bound handlers per frame - Headless tool gestures deliver plug-in events once their actions finish, and a drag set aside by a command holds events until it ends. - Documents added in a batch are compared with their state when added. - Background plug-in loads record the event baseline when they install, or after commit or cancel when a drag is open. - Layer snapshots are compared by id through a map. - Each desktop frame runs at most four handlers across background delivery and every UI pass, and asks for another frame while handlers remain queued. --- crates/engine/src/lib.rs | 3 +- crates/engine/src/plugin_events.rs | 146 ++++++++++++--- crates/engine/src/session/documents.rs | 5 +- crates/engine/src/session/edit.rs | 4 + crates/engine/src/session/execute.rs | 7 +- crates/engine/src/store.rs | 2 + crates/engine/src/tests/plugin_events.rs | 216 +++++++++++++++++++++++ crates/engine/src/tooling.rs | 2 + crates/ui-egui/src/app.rs | 29 +-- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 11 files changed, 377 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 773f547802..0d185dcb5f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -393,7 +393,8 @@ pub struct Session { /// check ([`plugin_events`]). pub(crate) plugin_events: plugin_events::PluginEvents, /// The frontend delivers plug-in events by the frame ([`Session::deliver_plugin_events`]). Off, - /// each top-level command delivers them when it ends. + /// each top-level command delivers them when it ends. When on, the frontend calls + /// [`Session::begin_plugin_event_frame`] once before each frame's deliveries. pub plugin_event_frames: bool, /// The warnings of the previews that settling an interaction applied, while a top-level command /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index f853198ebb..e2e60f445f 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -9,10 +9,14 @@ //! Changes between two checks are one event: a burst of selection changes is one //! `selection.changed` with the final selection. No check or delivery runs while an interaction //! is open (a drag being previewed); waiting events wait for it to end. A document opened or -//! created since the last check is compared with how it was when the command that added it ended +//! created since the last check is compared with how it was when it was added //! ([`Session::plugin_events_see_new_documents`]). +//! A check after commit or cancel records the settled state for plug-ins installed during the interaction. //! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a //! handler runs waits for the next delivery: handlers never run inside one another. +//! A frontend frame runs at most [`MAX_FRAME_HANDLERS`] handlers across all its deliveries, +//! after [`Session::begin_plugin_event_frame`] resets the budget. Runnable recipients still +//! waiting request another frame through the delivery's return value. //! - A handler only reads. The host applies nothing it returns, and it may call only the commands //! in [`super::cmd::plugin_call::EVENT_READS`]; any other call is refused with an error that names //! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]). @@ -21,7 +25,8 @@ //! until the session ends, or until another module is installed under its id. //! - When no installed plug-in reacts to events, a check returns before comparing anything. -use std::collections::{BTreeMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::hash::Hash; use std::sync::Arc; use serde_json::{Value, json}; @@ -35,6 +40,9 @@ use crate::Session; /// Most events that wait for delivery. pub const MAX_PENDING: usize = 32; +/// Most handlers called across all deliveries in one frontend frame. +pub const MAX_FRAME_HANDLERS: usize = 4; + /// Most notices kept for the frontend to show; older ones are dropped. pub const MAX_NOTICES: usize = 64; @@ -116,6 +124,7 @@ pub struct PluginEvents { /// How many events have been queued as their own entry. queued: u64, dispatching: bool, + frame_handlers: usize, failures: BTreeMap, notices: VecDeque, /// The installed plug-ins that react to events, as of a registry revision. @@ -195,7 +204,7 @@ impl PluginEvents { /// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its /// contents (for comparing its options) and the ids of the rows directly in it, in order. -type LayerRow = (NodeId, Option, vectorcraft_doc::Node, Vec); +type LayerRow = (Id, Option, vectorcraft_doc::Node, Vec); /// Each layer and sublayer of `doc`, in order. fn layer_rows(doc: &Document) -> Vec { @@ -247,18 +256,28 @@ fn layer_reasons(before: &Arc, layer_before: Option, after: &A return reasons; } let (old, new) = (layer_rows(before), layer_rows(after)); - if new.iter().any(|(id, ..)| !old.iter().any(|(o, ..)| o == id)) { + reasons.extend(layer_row_reasons(&old, &new, || layers_moved_among_rows(before, &old, after, &new))); + reasons +} + +/// Compares layer membership, order and options by id. +fn layer_row_reasons(old: &[LayerRow], new: &[LayerRow], moved: impl FnOnce() -> bool) -> Vec<&'static str> { + let mut reasons = Vec::new(); + let old_by_id: HashMap> = old.iter().map(|r| (r.0, r)).collect(); + let new_by_id: HashMap> = new.iter().map(|r| (r.0, r)).collect(); + if new.iter().any(|r| !old_by_id.contains_key(&r.0)) { reasons.push("added"); } - if old.iter().any(|(id, ..)| !new.iter().any(|(n, ..)| n == id)) { + if old.iter().any(|r| !new_by_id.contains_key(&r.0)) { reasons.push("deleted"); } - let kept = - |rows: &[LayerRow], other: &[LayerRow]| rows.iter().filter(|r| other.iter().any(|o| o.0 == r.0)).map(|r| (r.0, r.1)).collect::>(); - if kept(&old, &new) != kept(&new, &old) || layers_moved_among_rows(before, &old, after, &new) { + let kept = |rows: &[LayerRow], other: &HashMap>| { + rows.iter().filter(|r| other.contains_key(&r.0)).map(|r| (r.0, r.1)).collect::>() + }; + if kept(old, &new_by_id) != kept(new, &old_by_id) || moved() { reasons.push("reordered"); } - if old.iter().any(|r| new.iter().any(|o| o.0 == r.0 && o.2 != r.2)) { + if old.iter().any(|r| new_by_id.get(&r.0).is_some_and(|o| o.2 != r.2)) { reasons.push("options"); } reasons @@ -315,7 +334,7 @@ impl Session { /// change may have come before it. A waiting event is no longer for a plug-in that is not /// installed now, so a module removed and installed again is not given it. Nothing is compared /// while an interaction is open, nor when no plug-in reacts to events. - fn check_plugin_events(&mut self) { + fn check_plugin_events(&mut self, interaction_ended: bool) { let subs = self.plugin_events.subscribers(); if subs.is_empty() { self.plugin_events.seen.clear(); @@ -328,7 +347,7 @@ impl Session { p.to.retain(|(r, _)| installed.contains(r)); !p.to.is_empty() }); - if self.docs.iter().any(|d| d.interaction.is_some()) { + if self.holds_interaction() || (self.in_tool_actions && !interaction_ended) || self.docs.iter().any(|d| d.interaction.is_some()) { return; } let mut events = std::mem::take(&mut self.plugin_events); @@ -359,17 +378,31 @@ impl Session { self.plugin_events = events; } + /// Resets the handler budget for a frontend frame. Call once before the frame's deliveries, + /// including background work and all UI passes, when [`Session::plugin_event_frames`] is on. + pub fn begin_plugin_event_frame(&mut self) { + self.plugin_events.frame_handlers = 0; + } + /// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the /// handlers of the events waiting, oldest first, one handler at a time. While a handler runs, /// this returns at once: what the handler's calls change waits for the next delivery. While an /// interaction is open, the events wait for the first delivery after it ends. - pub fn deliver_plugin_events(&mut self) { + /// A set-aside interaction also holds events. A frontend frame calls at most + /// [`MAX_FRAME_HANDLERS`] handlers across all deliveries since [`Session::begin_plugin_event_frame`] + /// and keeps the remaining recipients for later frames. Returns whether runnable handlers + /// remain queued, so the frontend can request another frame even when no handler wrote a notice. + pub fn deliver_plugin_events(&mut self) -> bool { if self.plugin_events.dispatching { - return; + return false; } - self.check_plugin_events(); - if self.plugin_events.pending.is_empty() || self.docs.iter().any(|d| d.interaction.is_some()) { - return; + self.check_plugin_events(false); + if self.plugin_events.pending.is_empty() + || self.holds_interaction() + || self.in_tool_actions + || self.docs.iter().any(|d| d.interaction.is_some()) + { + return false; } let subs = self.plugin_events.subscribers(); self.plugin_events.dispatching = true; @@ -381,7 +414,10 @@ impl Session { // ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its // slices: a run that fails discards the documents it opened. let mut held = VecDeque::new(); - while let Some(p) = self.plugin_events.pending.pop_front() { + let mut budget = if self.plugin_event_frames { MAX_FRAME_HANDLERS.saturating_sub(self.plugin_events.frame_handlers) } else { usize::MAX }; + let waiting = self.plugin_events.pending.len(); + for _ in 0..waiting { + let Some(mut p) = self.plugin_events.pending.pop_front() else { break }; if p.by_script { held.push_back(p); continue; @@ -389,11 +425,30 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } - for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.is_for(&recipient(s))) { - if self.plugin_events.failures_of(plugin).disabled { + for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event)) { + let r = recipient(plugin); + if !p.is_for(&r) { continue; } + if self.plugin_events.failures_of(plugin).disabled { + p.to.retain(|(to, _)| *to != r); + continue; + } + if budget == 0 { + break; + } self.run_handler(plugin, &p); + p.to.retain(|(to, _)| *to != r); + budget -= 1; + if self.plugin_event_frames { + self.plugin_events.frame_handlers += 1; + } + } + if !p.to.is_empty() { + held.push_back(p); + } + if budget == 0 { + break; } } // The held events are older than any a handler's calls queued meanwhile. @@ -402,6 +457,11 @@ impl Session { } self.depth = depth; self.plugin_events.dispatching = false; + self.plugin_events.pending.iter().any(|p| { + !p.by_script + && (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)) + && subs.iter().any(|plugin| p.is_for(&recipient(plugin)) && !self.plugin_event_status(plugin).0) + }) } /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a @@ -471,8 +531,8 @@ impl Session { /// Takes each open document the last check didn't see, one opened or created since, as it is /// now, so the next check compares it with this state: a change made to it before the next - /// delivery gives its event. Called after each top-level command and when a document is added - /// outside one. Nothing is kept when no plug-in reacted to events at the last check, nor for a + /// delivery gives its event. Called when a document is added and after each top-level command. + /// Nothing is kept when no plug-in reacted to events at the last check, nor for a /// document in an interaction. pub(crate) fn plugin_events_see_new_documents(&mut self) { if self.plugin_events.seen_by.is_empty() { @@ -500,7 +560,15 @@ impl Session { /// before the next delivery. pub(crate) fn plugins_changed_for_events(&mut self) { if !self.plugin_events.dispatching { - self.check_plugin_events(); + self.check_plugin_events(false); + } + } + + /// Records the settled document state after an interaction ends, including subscribers + /// installed during its previews. Tool actions may still be finishing; handlers wait for them. + pub(crate) fn plugin_events_interaction_ended(&mut self) { + if !self.plugin_events.dispatching { + self.check_plugin_events(true); } } @@ -523,6 +591,40 @@ impl Session { mod tests { use super::*; + #[test] + fn layer_comparison_indexes_ids_instead_of_scanning_each_snapshot() { + use std::cell::Cell; + use std::hash::Hasher; + + #[derive(Clone, Copy)] + struct Counted<'a> { + value: u64, + comparisons: &'a Cell, + } + impl PartialEq for Counted<'_> { + fn eq(&self, other: &Self) -> bool { + self.comparisons.set(self.comparisons.get() + 1); + self.value == other.value + } + } + impl Eq for Counted<'_> {} + impl Hash for Counted<'_> { + fn hash(&self, state: &mut H) { + self.value.hash(state); + } + } + + let comparisons = Cell::new(0); + let doc = Document::new(100.0, 100.0); + let node = (*doc.layers[0]).clone(); + let old: Vec>> = + (0..1024).map(|value| (Counted { value, comparisons: &comparisons }, None, node.clone(), Vec::new())).collect(); + let mut new = old.clone(); + new.last_mut().unwrap().2.name = Some("Notes".into()); + assert_eq!(layer_row_reasons(&old, &new, || false), ["options"]); + assert!(comparisons.get() < old.len() * 32, "{} id comparisons for {} layers", comparisons.get(), old.len()); + } + /// Waiting selection and layer events of a document merge; each plug-in keeps the reasons of /// the changes it was given. #[test] diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 464c980811..7812055955 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -420,10 +420,7 @@ impl Session { { self.begin_named_undo_group(label); } - if self.depth == 0 { - // Inside a command, this happens once the command has finished. - self.plugin_events_see_new_documents(); - } + self.plugin_events_see_new_documents(); i } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index d5d62e607c..653ff993fd 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -662,6 +662,9 @@ impl Session { if let Some(before) = before { self.reveal_since(&before); } + if r.is_ok() { + self.plugin_events_interaction_ended(); + } r } @@ -794,6 +797,7 @@ impl Session { if !used_defaults_only { self.inherit_new_art(); } + self.plugin_events_interaction_ended(); Ok(()) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 6ea516023b..cee09379c9 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -132,6 +132,9 @@ impl Session { if self.script_in_run && self.depth > 0 && r.is_ok() { crate::script::note_style_lists(self); } + if self.depth == 0 { + self.plugin_events_after_command(); + } r } @@ -255,9 +258,6 @@ impl Session { // A failed or panicked command's documents are put back: type is drawn in their // composite fonts again, not in those the command set. cmd::compositefonts::sync(self); - // Plug-ins still hear of what finished before the failure, such as a save in a batch - // whose later step failed. - self.plugin_events_after_command(); } let r = r?; if self.depth == 0 { @@ -301,7 +301,6 @@ impl Session { self.journal_in_undo_groups(doc, &grouped, journal); self.trim_histories(); self.after_command(Some(id)); - self.plugin_events_after_command(); } else if matches!(id, "edit.undo" | "edit.redo") { // A step of `command.batch`: the tool hears of it as it does of the command alone. self.notify_text_tool(id); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 1437e9c56c..17a88c7c65 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -1223,11 +1223,13 @@ impl Session { } /// Installs what `load` has loaded so far, without waiting, in `turn`. + /// Records the installed plug-ins' event baseline now, or after an open interaction ends. fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) { match load { PluginLoad::Stored(load) => self.install_stored_plugins(load, turn), PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn), } + self.plugins_changed_for_events(); } /// Ends `load` once [`PluginLoad::done`], in `turn` → its report. diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 66b8804a58..0ab0becd00 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -46,6 +46,222 @@ fn types(events: &[Value]) -> Vec<&str> { events.iter().map(|e| e["type"].as_str().unwrap()).collect() } +#[test] +fn a_headless_gesture_delivers_events_when_its_actions_finish() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let id = "test.events.headless_gesture"; + for real_time in [true, false] { + let mut s = session(); + s.prefs.real_time_drawing = real_time; + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("rectangle", view).unwrap(); + for (kind, x, y) in [(PointerKind::Down, 50.0, 50.0), (PointerKind::Drag, 100.0, 100.0)] { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + assert!(given(&mut s, id).is_empty(), "the drag is still open"); + s.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 100.0), view).unwrap(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"]); + assert_eq!(got[0]["ids"], json!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>())); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the event is delivered once"); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +#[test] +fn a_set_aside_drag_holds_events_and_their_baseline() { + use vectorcraft_plugins::events::Event; + let id = "test.events.held_drag"; + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed","document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.begin_interaction("Move").unwrap(); + s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true; + s.outside_interaction("select.set", &json!({"ids": [r.0]}), |s| { + assert!(s.holds_interaction()); + assert!(s.docs.iter().all(|d| d.interaction.is_none())); + s.active_mut().unwrap().selection.objects = vec![r]; + s.deliver_plugin_events(); + assert!(given(s, id).is_empty(), "the drag is set aside"); + Ok(Value::Null) + }) + .unwrap(); + s.cancel_interaction().unwrap(); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["document.saved"], "the temporary selection did not advance the baseline"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn batch_steps_compare_new_documents_with_their_initial_state() { + let id = "test.events.batch_new"; + let mut s = session(); + install(&mut s, id, r#"["selection.changed","document.opened","layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].clone(); + for first in [ + json!({"command": "file.new", "params": {}}), + json!({"command": "document.open", "params": {"name": "batch.vectorcraft", "dataBase64": data}}), + ] { + let opened = first["command"] == "document.open"; + run( + &mut s, + "command.batch", + json!({"commands": [first, {"command": "layer.new", "params": {"name": "Notes"}}, + {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 10, "height": 10}}]}), + ); + let got = given(&mut s, id); + let expected = + if opened { vec!["document.opened", "selection.changed", "layer.changed"] } else { vec!["selection.changed", "layer.changed"] }; + assert_eq!(types(&got), expected); + assert!(got.iter().all(|e| e["document"] == s.doc().unwrap().uid)); + assert!(got.last().unwrap()["reasons"].as_array().unwrap().contains(&json!("added"))); + } + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn background_installs_record_the_baseline_before_the_next_edit() { + let id = "test.events.background_baseline"; + let folder = crate::tests_links::Folder::new("event-background-baseline"); + let mut writer = session(); + writer.attach_plugin_store(folder.0.clone()); + install(&mut writer, id, r#"["selection.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + assert!(vectorcraft_plugins::registry::remove(id)); + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + assert!(given(&mut s, id).is_empty(), "changes before loading are not replayed"); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["selection.changed"]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn background_installs_during_a_drag_record_the_settled_baseline() { + let id = "test.events.background_drag_baseline"; + let folder = crate::tests_links::Folder::new("event-background-drag-baseline"); + let mut writer = session(); + writer.attach_plugin_store(folder.0.clone()); + install(&mut writer, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + assert!(vectorcraft_plugins::registry::remove(id)); + for commit in [false, true] { + for tool_actions in [false, true] { + for edit_before_delivery in [true, false] { + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + s.begin_interaction("Select").unwrap(); + s.preview("select.set", &json!({"ids": [r.0]})).unwrap(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + assert!(!s.deliver_plugin_events(), "the preview holds delivery"); + assert!(given(&mut s, id).is_empty()); + s.in_tool_actions = tool_actions; + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + s.in_tool_actions = false; + if !edit_before_delivery { + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "neither the preview nor its rollback is replayed"); + } + let ids = if commit { vec![] } else { vec![r.0] }; + run(&mut s, "select.set", json!({"ids": ids})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"], "commit={commit}, tool_actions={tool_actions}"); + assert_eq!(got[0]["ids"], json!(ids)); + assert!(vectorcraft_plugins::registry::remove(id)); + } + } + } +} + +#[test] +fn silent_handlers_report_when_another_frame_is_needed() { + use vectorcraft_plugins::events::Event; + let id = "test.events.silent_pending"; + let mut s = session(); + install(&mut s, id, r#"["document.saved"]"#, &[], "", "(i32.const 0)", &[]); + s.plugin_event_frames = true; + let doc = s.doc().unwrap().uid; + for _ in 0..=crate::plugin_events::MAX_FRAME_HANDLERS { + s.note_plugin_event(Event::DocumentSaved, doc); + } + s.begin_plugin_event_frame(); + assert!(s.deliver_plugin_events(), "silent handlers still need another frame"); + assert!(s.take_plugin_event_notices().is_empty()); + s.begin_plugin_event_frame(); + assert!(!s.deliver_plugin_events(), "the next frame drains the remaining handler"); + assert!(s.take_plugin_event_notices().is_empty()); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn deliveries_in_one_frame_share_the_handler_budget() { + use vectorcraft_plugins::events::Event; + let id = "test.events.shared_frame_budget"; + let mut s = session(); + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let doc = s.doc().unwrap().uid; + for _ in 0..(crate::plugin_events::MAX_FRAME_HANDLERS * 2) { + s.note_plugin_event(Event::DocumentSaved, doc); + } + s.begin_plugin_event_frame(); + assert!(s.deliver_plugin_events()); + assert_eq!(given(&mut s, id).len(), crate::plugin_events::MAX_FRAME_HANDLERS); + assert!(s.deliver_plugin_events(), "the UI pass still has queued handlers"); + assert!(given(&mut s, id).is_empty(), "background delivery already used this frame's budget"); + s.begin_plugin_event_frame(); + assert!(!s.deliver_plugin_events()); + assert_eq!(given(&mut s, id).len(), crate::plugin_events::MAX_FRAME_HANDLERS); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn frame_delivery_bounds_handlers_and_resumes_remaining_recipients() { + use vectorcraft_plugins::events::Event; + let mut s = session(); + s.plugin_event_frames = true; + let ids: Vec = (0..=crate::plugin_events::MAX_FRAME_HANDLERS).map(|i| format!("test.events.frame_budget_{i}")).collect(); + for id in &ids { + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + } + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.note_plugin_event(Event::DocumentSaved, doc); + let mut delivered = Vec::new(); + for _ in 0..(ids.len() * 2) { + s.begin_plugin_event_frame(); + s.deliver_plugin_events(); + let notices: Vec<_> = s.take_plugin_event_notices().into_iter().filter(|n| ids.contains(&n.plugin)).collect(); + assert!(notices.len() <= crate::plugin_events::MAX_FRAME_HANDLERS); + delivered.extend(notices.into_iter().map(|n| n.plugin)); + } + assert_eq!(delivered.len(), ids.len() * 2); + for id in &ids { + assert_eq!(delivered.iter().filter(|got| *got == id).count(), 2, "{id}"); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + /// A selection change, a new layer, a save and an open each reach the plug-in that names them once, /// after the change, with the document they happened in; a plug-in that names only `document.saved` /// is given only the save. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index c5d2905963..65673881e5 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1819,6 +1819,7 @@ impl Session { } /// Apply tool actions. Errors from previews are reported but keep the interaction alive. + /// Headless sessions deliver plug-in events after the outer actions finish. pub fn apply_actions(&mut self, acts: Vec) -> Result> { // The tool acts on its own interaction, which a command from outside it may have set aside. if !acts.is_empty() { @@ -1847,6 +1848,7 @@ impl Session { self.back_to_painter = outer_painter; if !outer && self.depth == 0 { self.trim_histories(); + self.plugin_events_after_command(); } r } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d88121d42d..0f313192dd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -361,10 +361,11 @@ impl VectorcraftApp { /// Applies the work that finished off the UI thread. It stays pending while a script runs, since /// every change to the documents ends in a busy error until the script ends. Plug-in worker runs /// are still read then, so Cancel and their time budgets still end them ([`plugin_runs::poll`]). - pub(crate) fn poll_finished_work(&mut self) { + /// Returns whether plug-in event delivery needs a repaint. + pub(crate) fn poll_finished_work(&mut self) -> bool { if self.session.script_running() { plugin_runs::poll(self); - return; + return false; } background::poll(self); opening::poll(self); @@ -372,22 +373,22 @@ impl VectorcraftApp { trace_runs::poll(self); placing::poll(self); retype_runs::poll(self); - let _ = self.deliver_plugin_events(); + self.deliver_plugin_events() } /// Hands the plug-ins that react to events the changes of this frame /// ([`vectorcraft_engine::Session::deliver_plugin_events`]). The last warning or error a handler - /// wrote, or the last handler failure, shows in the status bar after the plug-in's name. → Whether - /// the status bar shows one. + /// wrote, or the last handler failure, shows in the status bar after the plug-in's name. + /// Returns whether the status bar changed or runnable handlers remain queued. fn deliver_plugin_events(&mut self) -> bool { - self.session.deliver_plugin_events(); + let pending = self.session.deliver_plugin_events(); let shown = self .session .take_plugin_event_notices() .into_iter() .rev() .find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn)); - let Some(n) = shown else { return false }; + let Some(n) = shown else { return pending }; let name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); self.status(format!("{name}: {}", n.text)); true @@ -480,6 +481,9 @@ impl VectorcraftApp { /// [`Self::tick`]'s work. fn tick_frame(&mut self, ctx: &egui::Context) { self.ticked_pass = Some(ctx.cumulative_pass_nr()); + if ctx.current_pass_index() == 0 { + self.session.begin_plugin_event_frame(); + } let lang = self.ui_language(); i18n::set_current(lang); // The engine gives new type the Japanese defaults while the UI is in Japanese. @@ -531,14 +535,13 @@ impl VectorcraftApp { let script_was_running = self.session.script_running(); // Once a frame: work that finishes during a frame's first pass is applied in the next frame, not in a second // pass of this one. - if ctx.current_pass_index() == 0 { - self.poll_finished_work(); + if ctx.current_pass_index() == 0 && self.poll_finished_work() { + ctx.request_repaint(); } crate::script_runs::poll(self); - if script_was_running && !self.session.script_running() { - // The work that waited for the script, and the plug-in events its changes give, are - // taken in the frame it ended in: no repaint is asked for once it has ended. - self.poll_finished_work(); + // Apply the work that waited for the script in the frame it ended in. + if script_was_running && !self.session.script_running() && self.poll_finished_work() { + ctx.request_repaint(); } // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); diff --git a/docs/mcp.md b/docs/mcp.md index 1c39001b62..487a70a68f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15204,8 +15204,12 @@ switches documents or undoes is never called; `plugin.install` refuses a manifes `refusedCommands` and ids no command has as `unknownCommands`; `plugin.install` also lists the `unknownCommands`. A plug-in at API level 2 whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given the events of the kinds its `events` list names, from `selection.changed`, `document.opened`, `document.saved` and `layer.changed`, -through `vc_event` once the change has finished; -its handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). A live-effect plug-in is an effect with +through `vc_event` once the change has finished. Headless tool gestures deliver events after their actions finish. +An open drag, including one temporarily set aside by a command, holds events until it ends. Documents created or +opened in a batch are compared with their state when added, and background plug-in loads record the event baseline +when they install, or after the drag ends if one is open. Each UI frame calls at most four event handlers across +background delivery and all UI passes; runnable recipients still queued request another frame, even without notices. +The handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). A live-effect plug-in is an effect with id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50b9678301..df93e7c2c3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2838,7 +2838,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. -- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two checks are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. The desktop app checks after background work and at the end of each UI pass; `vectorcraft-cli` and headless MCP check after each top-level command. Each UI frame runs at most four handlers across background delivery and all UI passes, and requests another frame while runnable handlers remain queued, even without notices. An open drag holds events until it ends. A plug-in loaded during a drag records its baseline after commit or cancel, before the next edit, without recording temporary previews. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. From 1a991e47872ff1d415d0a2dc4fd399cc7a922f82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:38:41 -0800 Subject: [PATCH 12/60] Scripts: pathItems reads names such as -1 and 1.5 as pageItems does A key that is the text of a number but not an array index, such as -1 or 1.5, reaches the indexer as a number, so pathItems[-1] gave undefined for a path named -1. pathItems now takes main's pageItems lookup: an array index is a position, and any other number is looked up as that name. index() still takes a number as a position. The progress-doc line for Document.pathItems states the name lookup and the locked-artboard rule of removeAll(). --- crates/engine/src/script/dom/paths.rs | 44 +++++++++++++++------ crates/engine/src/tests/script_dom_paths.rs | 17 ++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 50 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index fdd850e9a0..399cd80f4d 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -404,27 +404,44 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } -/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. +/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no path has it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - if let Data::String(_) = arg(a, 1) { - return match items_by_name(h, a) { + match arg(a, 1) { + Data::String(_) => match items_by_name(h, a) { Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined), r => r, - }; + }, + Data::Number(n) => match super::position(*n) { + Some(i) => Ok(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, + }, + }, + _ => Ok(Data::Undefined), } - 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)))) +} + +/// The path at position `i` of `pathItems`, or `undefined` past the end. +fn item_at(h: &super::Host, doc: Doc, i: usize) -> Data { + with_doc(h, doc, |_, st| 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())) }; + items_named(h, doc, name) +} + +/// The first path of `pathItems` named `name`, or `Not found`. +fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, 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())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -432,10 +449,13 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { fn items_index(h: &super::Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), - Data::Number(_) => match items_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let doc = items_doc(h, a)?; + match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)) { + Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())), + Some(d) => Ok(d), + } + } _ => Err(HostError::Type("give a name or an index".into())), } } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b842932244..54e84595bc 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -114,6 +114,23 @@ fn path_items_read_with_a_name_give_the_named_path() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); } +/// `pathItems` read with a name that is the text of a number but not an array index, such as `-1` +/// or `1.5`, gives the path of that name, and `undefined` when no path has it; `index` still takes +/// a number as a position, as in `pageItems`. +#[test] +fn path_items_read_with_a_number_name_that_is_not_an_index_give_the_named_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems, m = [];\ + vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p['1.5'] === undefined, '1.5' in p]);\ + try { p.index(-1); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, true, true, true, false]), json!(["Not found"])]); +} + /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ee49042298..09679496a1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1120,7 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - 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: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. From ebd59b794db04227ac3eb0dd35884ab8c754be99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:15:57 -0800 Subject: [PATCH 13/60] Plug-ins: drop layer events of a rolled-back batch and serve waiting recipients first A layer change seen when a command.batch step settled its interaction was queued before the batch finished, so a failed batch still reported it. The check now waits until the outermost command ends. Delivery under the frame budget now serves recipients in the order they were added to the event, so recipients re-added by a coalesced change no longer take the budget ahead of ones still waiting. The frame-budget tests use a session-local subscriber list instead of the shared plug-in registry. --- crates/engine/src/plugin_events.rs | 24 +++++-- crates/engine/src/tests/plugin_events.rs | 86 +++++++++++++++++++++--- 2 files changed, 95 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index e2e60f445f..93375f4924 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -125,15 +125,22 @@ pub struct PluginEvents { queued: u64, dispatching: bool, frame_handlers: usize, + interaction_ended: bool, failures: BTreeMap, notices: VecDeque, /// The installed plug-ins that react to events, as of a registry revision. subscribers: Option<(u64, Vec>)>, + #[cfg(test)] + pub(crate) test_subscribers: Option>>, } impl PluginEvents { /// The installed plug-ins that react to events (none in Safe Mode). fn subscribers(&mut self) -> Vec> { + #[cfg(test)] + if let Some(subs) = &self.test_subscribers { + return subs.clone(); + } if vectorcraft_plugins::safe_mode::active() { return Vec::new(); } @@ -425,11 +432,9 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } - for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event)) { - let r = recipient(plugin); - if !p.is_for(&r) { - continue; - } + let recipients = p.to.clone(); + for (r, _) in recipients { + let Some(plugin) = subs.iter().find(|s| recipient(s) == r && s.manifest().reacts_to(p.event)) else { continue }; if self.plugin_events.failures_of(plugin).disabled { p.to.retain(|(to, _)| *to != r); continue; @@ -549,6 +554,9 @@ impl Session { /// them once a frame ([`Session::plugin_event_frames`]) or a script is running. pub(crate) fn plugin_events_after_command(&mut self) { self.plugin_events_see_new_documents(); + if std::mem::take(&mut self.plugin_events.interaction_ended) { + self.plugin_events_interaction_ended(); + } if !self.plugin_event_frames && !self.script_in_run { self.deliver_plugin_events(); } @@ -568,7 +576,11 @@ impl Session { /// installed during its previews. Tool actions may still be finishing; handlers wait for them. pub(crate) fn plugin_events_interaction_ended(&mut self) { if !self.plugin_events.dispatching { - self.check_plugin_events(true); + if self.depth == 0 { + self.check_plugin_events(true); + } else { + self.plugin_events.interaction_ended = true; + } } } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 0ab0becd00..5f471b7925 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -36,6 +36,21 @@ fn install(s: &mut Session, id: &str, events: &str, more: &[&str], imports: &str run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); } +fn local_session() -> Session { + let mut s = Session::new(); + s.plugin_events.test_subscribers = Some(Vec::new()); + run(&mut s, "file.new", json!({"width": 400, "height": 200})); + s +} + +fn subscribe(s: &mut Session, id: &str, events: &str, handler: &str) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)).unwrap(); + let plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap(); + s.plugin_events.test_subscribers.as_mut().unwrap().push(std::sync::Arc::new(plugin)); + s.plugins_changed_for_events(); +} + /// The events plug-in `id`'s handler was given since the last call, as it logged them. fn given(s: &mut Session, id: &str) -> Vec { let notices = s.take_plugin_event_notices(); @@ -197,8 +212,8 @@ fn background_installs_during_a_drag_record_the_settled_baseline() { fn silent_handlers_report_when_another_frame_is_needed() { use vectorcraft_plugins::events::Event; let id = "test.events.silent_pending"; - let mut s = session(); - install(&mut s, id, r#"["document.saved"]"#, &[], "", "(i32.const 0)", &[]); + let mut s = local_session(); + subscribe(&mut s, id, r#"["document.saved"]"#, "(i32.const 0)"); s.plugin_event_frames = true; let doc = s.doc().unwrap().uid; for _ in 0..=crate::plugin_events::MAX_FRAME_HANDLERS { @@ -210,15 +225,14 @@ fn silent_handlers_report_when_another_frame_is_needed() { s.begin_plugin_event_frame(); assert!(!s.deliver_plugin_events(), "the next frame drains the remaining handler"); assert!(s.take_plugin_event_notices().is_empty()); - run(&mut s, "plugin.remove", json!({"id": id})); } #[test] fn deliveries_in_one_frame_share_the_handler_budget() { use vectorcraft_plugins::events::Event; let id = "test.events.shared_frame_budget"; - let mut s = session(); - install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let mut s = local_session(); + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); s.plugin_event_frames = true; let doc = s.doc().unwrap().uid; for _ in 0..(crate::plugin_events::MAX_FRAME_HANDLERS * 2) { @@ -232,17 +246,16 @@ fn deliveries_in_one_frame_share_the_handler_budget() { s.begin_plugin_event_frame(); assert!(!s.deliver_plugin_events()); assert_eq!(given(&mut s, id).len(), crate::plugin_events::MAX_FRAME_HANDLERS); - run(&mut s, "plugin.remove", json!({"id": id})); } #[test] fn frame_delivery_bounds_handlers_and_resumes_remaining_recipients() { use vectorcraft_plugins::events::Event; - let mut s = session(); + let mut s = local_session(); s.plugin_event_frames = true; let ids: Vec = (0..=crate::plugin_events::MAX_FRAME_HANDLERS).map(|i| format!("test.events.frame_budget_{i}")).collect(); for id in &ids { - install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); } let doc = s.doc().unwrap().uid; s.note_plugin_event(Event::DocumentSaved, doc); @@ -258,7 +271,62 @@ fn frame_delivery_bounds_handlers_and_resumes_remaining_recipients() { assert_eq!(delivered.len(), ids.len() * 2); for id in &ids { assert_eq!(delivered.iter().filter(|got| *got == id).count(), 2, "{id}"); - run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +#[test] +fn coalesced_changes_serve_waiting_recipients_before_readded_recipients() { + let mut s = local_session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + let ids: Vec = (0..9).map(|i| format!("test.events.fair_selection_{i}")).collect(); + for id in &ids { + subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT); + } + s.plugin_event_frames = true; + let mut delivered = Vec::new(); + for frame in 0..3 { + s.begin_plugin_event_frame(); + let selection = if frame % 2 == 0 { vec![r.0] } else { Vec::new() }; + run(&mut s, "select.set", json!({"ids": selection})); + assert!(s.deliver_plugin_events()); + let notices = s.take_plugin_event_notices(); + assert_eq!(notices.len(), crate::plugin_events::MAX_FRAME_HANDLERS); + delivered.extend(notices.into_iter().map(|n| n.plugin)); + } + for id in &ids { + assert!(delivered.contains(id), "{id} was not served while selection kept changing"); + } +} + +#[test] +fn a_failed_batch_drops_layer_changes_from_a_settled_interaction() { + let id = "test.events.rolled_back_layer"; + for frames in [false, true] { + let mut s = local_session(); + subscribe(&mut s, id, r#"["layer.changed","document.opened"]"#, tpl::LOG_EVENT); + s.plugin_event_frames = frames; + let before = s.doc().unwrap().doc.clone(); + let error = s + .execute( + "command.batch", + &json!({"commands": [ + {"command": "layer.new", "params": {"name": "Notes"}}, + {"command": "edit.newDocumentFromState", "params": {}}, + {"command": "no.such.command", "params": {}} + ]}), + ) + .unwrap_err(); + assert!(error.to_string().contains("batch step 2"), "{error}"); + assert_eq!(s.documents().len(), 1); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the batch's layer was rolled back"); + run(&mut s, "layer.new", json!({"name": "Committed"})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); } } From 95f08201f637298a6a78f4b6a9691f9559883ce3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:25:22 -0800 Subject: [PATCH 14/60] Plug-ins: keep a failed script's layer changes out of events and index recipients Event checks no longer compare documents while a script runs, so a script that throws after a command.batch gives no event for its discarded working copy. A batch that settles an open drag records the plug-in baselines before its own steps edit, so a plug-in loaded during the drag gets the batch's changes. Delivery looks recipients up in a map built once per delivery and drains served recipients once per event. --- crates/engine/src/cmd/fileio/batch.rs | 1 + crates/engine/src/plugin_events.rs | 35 +++++++++--- crates/engine/src/tests/plugin_events.rs | 73 ++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 316fae8573..51ed9b6cd4 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -19,6 +19,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // would otherwise run inside it and take its baseline as theirs (#1697). if s.active().is_some() && !s.previewing { super::super::edit::settle_interaction(s)?; + s.plugin_events_batch_settled(); } let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // The documents as they are now, whole: what a failed step brings back. Their art, history, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 93375f4924..16ea428c56 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -61,8 +61,15 @@ struct Seen { /// ([`Plugin::serial`]), so a module removed and installed again is another recipient. type Recipient = (String, String, u64); +#[cfg(test)] +std::thread_local! { + pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The recipient `p` is. fn recipient(p: &Plugin) -> Recipient { + #[cfg(test)] + RECIPIENT_IDENTITIES.with(|count| count.set(count.get() + 1)); (p.id().to_string(), p.hash().to_string(), p.serial()) } @@ -82,6 +89,7 @@ struct Pending { impl Pending { /// Whether this event is for `r`. + #[cfg(test)] fn is_for(&self, r: &Recipient) -> bool { self.to.iter().any(|(x, _)| x == r) } @@ -342,6 +350,9 @@ impl Session { /// installed now, so a module removed and installed again is not given it. Nothing is compared /// while an interaction is open, nor when no plug-in reacts to events. fn check_plugin_events(&mut self, interaction_ended: bool) { + if self.script_in_run { + return; + } let subs = self.plugin_events.subscribers(); if subs.is_empty() { self.plugin_events.seen.clear(); @@ -411,7 +422,7 @@ impl Session { { return false; } - let subs = self.plugin_events.subscribers(); + let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); self.plugin_events.dispatching = true; // The commands a handler calls run nested, never journaled; a panic in one leaves the depth // as it was found. @@ -432,23 +443,27 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } - let recipients = p.to.clone(); - for (r, _) in recipients { - let Some(plugin) = subs.iter().find(|s| recipient(s) == r && s.manifest().reacts_to(p.event)) else { continue }; + let mut served = 0; + for (i, (r, _)) in p.to.iter().enumerate() { + let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else { + served = i + 1; + continue; + }; if self.plugin_events.failures_of(plugin).disabled { - p.to.retain(|(to, _)| *to != r); + served = i + 1; continue; } if budget == 0 { break; } self.run_handler(plugin, &p); - p.to.retain(|(to, _)| *to != r); + served = i + 1; budget -= 1; if self.plugin_event_frames { self.plugin_events.frame_handlers += 1; } } + p.to.drain(..served); if !p.to.is_empty() { held.push_back(p); } @@ -465,7 +480,7 @@ impl Session { self.plugin_events.pending.iter().any(|p| { !p.by_script && (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)) - && subs.iter().any(|plugin| p.is_for(&recipient(plugin)) && !self.plugin_event_status(plugin).0) + && p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0)) }) } @@ -572,6 +587,12 @@ impl Session { } } + pub(crate) fn plugin_events_batch_settled(&mut self) { + if !self.plugin_events.dispatching && self.batch_stash.is_none() { + self.check_plugin_events(true); + } + } + /// Records the settled document state after an interaction ends, including subscribers /// installed during its previews. Tool actions may still be finishing; handlers wait for them. pub(crate) fn plugin_events_interaction_ended(&mut self) { diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 5f471b7925..3bdca8154c 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -299,6 +299,79 @@ fn coalesced_changes_serve_waiting_recipients_before_readded_recipients() { } } +#[test] +fn delivery_indexes_subscribers_and_preserves_pending_recipient_order() { + use vectorcraft_plugins::events::Event; + let mut s = local_session(); + let ids: Vec = (0..32).map(|i| format!("test.events.indexed_{i}")).collect(); + for id in &ids { + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); + } + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.plugin_events.test_subscribers.as_mut().unwrap().reverse(); + crate::plugin_events::RECIPIENT_IDENTITIES.with(|count| count.set(0)); + assert!(!s.deliver_plugin_events()); + let identities = crate::plugin_events::RECIPIENT_IDENTITIES.with(|count| count.get()); + let delivered: Vec<_> = s.take_plugin_event_notices().into_iter().map(|n| n.plugin).collect(); + assert_eq!(delivered, ids); + assert!(identities <= ids.len() * 8, "{identities} recipient identities for {} subscribers", ids.len()); +} + +#[test] +fn a_subscriber_loaded_during_a_drag_receives_the_batch_changes() { + let id = "test.events.batch_drag_baseline"; + for frames in [false, true] { + let mut s = local_session(); + s.plugin_event_frames = frames; + s.begin_interaction("Add layer").unwrap(); + s.preview("layer.new", &json!({"name": "Drag preview"})).unwrap(); + subscribe(&mut s, id, r#"["layer.changed"]"#, tpl::LOG_EVENT); + assert!(!s.deliver_plugin_events()); + assert!(given(&mut s, id).is_empty()); + run(&mut s, "command.batch", json!({"commands": [{"command": "layer.new", "params": {"name": "Batch layer"}}]})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty()); + } +} + +#[test] +fn script_batches_compare_layers_only_after_the_script_commits() { + let id = "test.events.script_batch_layers"; + for frames in [false, true] { + for kept in [false, true] { + let mut s = local_session(); + subscribe(&mut s, id, r#"["layer.changed"]"#, tpl::LOG_EVENT); + s.plugin_event_frames = frames; + let before = s.doc().unwrap().doc.layers.len(); + let ending = if kept { "" } else { "throw new Error('stop');" }; + let source = format!("vc.run('command.batch', {{commands: [{{command: 'layer.new', params: {{name: 'Script layer'}}}}]}}); {ending}"); + let result = s.execute("script.run", &json!({"source": source, "name": "batch.js"})); + assert_eq!(result.is_ok(), kept, "{result:?}"); + if !kept { + assert_eq!(s.doc().unwrap().doc.layers.len(), before, "the failed script's layer was rolled back"); + } + s.deliver_plugin_events(); + let got = given(&mut s, id); + if kept { + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + } else { + assert!(got.is_empty(), "the script's layer was rolled back: {got:?}"); + } + run(&mut s, "layer.new", json!({"name": "Committed"})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + } + } +} + #[test] fn a_failed_batch_drops_layer_changes_from_a_settled_interaction() { let id = "test.events.rolled_back_layer"; From 3bf15fe5e6170df84f4031beaf06a55b128cdfe6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:42:38 -0800 Subject: [PATCH 15/60] Packaging: the Windows signing test does not turn its expected warning into an annotation The stable optional-signing case in nightly-signing-tests.ps1 calls sign.ps1 with no signing variables set. On a runner, GITHUB_ACTIONS is set, so sign.ps1 printed "Windows signing secrets not set" as a ::warning:: workflow command, and every nightly-check run showed it as a warning annotation. The test now clears GITHUB_ACTIONS for that call and restores it after. It reads the line from the warning stream and fails when the warning is missing or when the call prints a workflow command. --- packaging/windows/nightly-signing-tests.ps1 | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 index 51a8e2ade9..60d2fa420f 100644 --- a/packaging/windows/nightly-signing-tests.ps1 +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -84,7 +84,14 @@ try { $file = Join-Path $root 'owned-sentinel.exe' [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash - & $sign -Files $file + # With GITHUB_ACTIONS set, sign.ps1 prints its unsigned-files warning as a workflow annotation. + # The test clears it for this call, reads the warning from the warning stream and restores it. + $actions = $env:GITHUB_ACTIONS + $env:GITHUB_ACTIONS = $null + try { $signOutput = @(& $sign -Files $file 3>&1) } finally { $env:GITHUB_ACTIONS = $actions } + $warnings = @($signOutput | Where-Object { $_ -is [Management.Automation.WarningRecord] }) + Assert-Policy ($warnings.Count -eq 1 -and $warnings[0].Message.Contains('Windows signing secrets not set')) 'optional stable policy did not warn about unsigned files' + Assert-Policy (-not ($signOutput | Where-Object { "$_".StartsWith('::') })) 'optional stable policy printed a workflow command' Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' } finally { From b558bf31441057abdbe36c624351b347d2536266 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:11:03 -0800 Subject: [PATCH 16/60] Plug-ins: keep the event baseline when a batch settles no interaction A command.batch checked the documents for plug-in events before its steps even when no drag or typing was open, so a selection that the batch put back as it was reached plug-ins as selection.changed. The check now runs only when the batch settles an interaction, or when the installed plug-ins differ from the last check's. Otherwise the batch only drops queued events for removed plug-ins and closed documents, and the snapshots of closed documents. Each handler is given its layer.changed reasons directly instead of looking them up among the event's recipients. --- crates/engine/src/cmd/fileio/batch.rs | 3 +- crates/engine/src/plugin_events.rs | 47 ++++++++++++++++++------ crates/engine/src/tests/plugin_events.rs | 40 ++++++++++++++++++++ 3 files changed, 77 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 51ed9b6cd4..263cbf57e1 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -18,8 +18,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // A drag or typing still in progress is a step of its own, as before Undo: the batch's steps // would otherwise run inside it and take its baseline as theirs (#1697). if s.active().is_some() && !s.previewing { + let open = s.holds_interaction() || s.docs.iter().any(|d| d.interaction.is_some()); super::super::edit::settle_interaction(s)?; - s.plugin_events_batch_settled(); + s.plugin_events_batch_settled(open); } let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // The documents as they are now, whole: what a failed step brings back. Their art, history, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 16ea428c56..89a23ae390 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -25,7 +25,7 @@ //! until the session ends, or until another module is installed under its id. //! - When no installed plug-in reacts to events, a check returns before comparing anything. -use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::hash::Hash; use std::sync::Arc; @@ -95,6 +95,7 @@ impl Pending { } /// The reasons of a `layer.changed` that `r` is given. + #[cfg(test)] fn reasons_for(&self, r: &Recipient) -> &[&'static str] { self.to.iter().find(|(x, _)| x == r).map_or(&[], |(_, reasons)| reasons.as_slice()) } @@ -444,7 +445,7 @@ impl Session { continue; } let mut served = 0; - for (i, (r, _)) in p.to.iter().enumerate() { + for (i, (r, reasons)) in p.to.iter().enumerate() { let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else { served = i + 1; continue; @@ -456,7 +457,7 @@ impl Session { if budget == 0 { break; } - self.run_handler(plugin, &p); + self.run_handler(plugin, &p, reasons); served = i + 1; budget -= 1; if self.plugin_event_frames { @@ -485,8 +486,9 @@ impl Session { } /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a - /// `selection.changed` only with `doc.read`. - fn event_json(&self, plugin: &Plugin, p: &Pending) -> Value { + /// `selection.changed` only with `doc.read`, and `reasons`, the reasons of a `layer.changed` + /// it was given. + fn event_json(&self, plugin: &Plugin, p: &Pending, reasons: &[&'static str]) -> Value { let mut v = json!({ "type": p.event.name(), "document": p.document }); let Some(st) = self.docs.iter().find(|d| d.uid == p.document) else { return v }; match p.event { @@ -502,17 +504,18 @@ impl Session { } Event::LayerChanged => { v["layer"] = json!(st.active_layer.map(|l| l.0)); - v["reasons"] = json!(p.reasons_for(&recipient(plugin))); + v["reasons"] = json!(reasons); } Event::DocumentOpened | Event::DocumentSaved => {} } v } - /// Calls `plugin`'s handler with event `p` and records what it wrote and whether it failed. - fn run_handler(&mut self, plugin: &Arc, p: &Pending) { + /// Calls `plugin`'s handler with event `p`, given `reasons`, and records what it wrote and + /// whether it failed. + fn run_handler(&mut self, plugin: &Arc, p: &Pending, reasons: &[&'static str]) { let event = p.event.name(); - let text = serde_json::to_vec(&self.event_json(plugin, p)).unwrap_or_default(); + let text = serde_json::to_vec(&self.event_json(plugin, p, reasons)).unwrap_or_default(); let m = plugin.manifest(); let may = m.permissions(); let (r, report) = if may.contains(&Permission::Commands) && !m.command_allowlist.is_empty() { @@ -587,10 +590,30 @@ impl Session { } } - pub(crate) fn plugin_events_batch_settled(&mut self) { - if !self.plugin_events.dispatching && self.batch_stash.is_none() { - self.check_plugin_events(true); + /// Before a batch's steps run: checks the documents when the batch settled an interaction + /// (`settled`), or when the installed plug-ins differ from the last check's, so that a plug-in + /// installed since then is given the batch's changes. Otherwise the last check stays the + /// baseline. + pub(crate) fn plugin_events_batch_settled(&mut self, settled: bool) { + if self.plugin_events.dispatching || self.batch_stash.is_some() || self.script_in_run { + return; } + if !settled { + let installed: Vec = self.plugin_events.subscribers().iter().map(|p| recipient(p)).collect(); + if installed == self.plugin_events.seen_by { + // Events for plug-ins removed, or for documents closed, since then still leave the + // queue first. + let set: HashSet<&Recipient> = installed.iter().collect(); + let docs = &self.docs; + self.plugin_events.pending.retain_mut(|p| { + p.to.retain(|(r, _)| set.contains(r)); + !p.to.is_empty() && (p.event.outlives_document() || docs.iter().any(|d| d.uid == p.document)) + }); + self.plugin_events.seen.retain(|s| docs.iter().any(|d| d.uid == s.uid)); + return; + } + } + self.check_plugin_events(true); } /// Records the settled document state after an interaction ends, including subscribers diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 3bdca8154c..7c83109c01 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -339,6 +339,46 @@ fn a_subscriber_loaded_during_a_drag_receives_the_batch_changes() { } } +/// A batch with no interaction to settle keeps the last check's state: a selection it puts back +/// as it was is not a change. +#[test] +fn a_batch_without_an_interaction_keeps_the_event_baseline() { + let id = "test.events.batch_no_interaction"; + let mut s = local_session(); + s.plugin_event_frames = true; + rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT); + s.deliver_plugin_events(); + given(&mut s, id); + run(&mut s, "select.all", json!({})); + run(&mut s, "command.batch", json!({"commands": [{"command": "select.none", "params": {}}]})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the selection is as it was at the last delivery"); +} + +/// A plug-in installed since the last check, without this session hearing of it, is given the +/// changes of a batch that settles no interaction. +#[test] +fn a_batch_gives_its_changes_to_a_plugin_installed_since_the_last_check() { + let id = "test.events.batch_new_subscriber"; + let mut s = local_session(); + s.plugin_event_frames = true; + subscribe(&mut s, "test.events.batch_earlier", r#"["selection.changed"]"#, tpl::LOG_EVENT); + s.deliver_plugin_events(); + s.take_plugin_event_notices(); + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":["layer.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap(); + s.plugin_events.test_subscribers.as_mut().unwrap().push(std::sync::Arc::new(plugin)); + run(&mut s, "command.batch", json!({"commands": [{"command": "layer.new", "params": {"name": "Batch layer"}}]})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); +} + #[test] fn script_batches_compare_layers_only_after_the_script_commits() { let id = "test.events.script_batch_layers"; From 308befa8cfdbbddde8400cb3840f19a8a1fca811 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:32:36 -0800 Subject: [PATCH 17/60] CI: run only the test shards a pull request's changes reach The gate call sets select-tests and shard-members, so a pull request runs the test shards whose crates its changes reach (the crates that own or declare a read of a changed file, and every crate that depends on them) and always runs shard 6, the checks. Pushes to main, the nightly run and the full-ci label run all six shards. xtask's test ci_names_the_crates_of_every_shard_for_test_selection fails when the shard-members lines in ci.yml differ from GROUPS in xtask/src/shards.rs. --- .github/workflows/ci.yml | 13 +++++++++++++ xtask/src/shards.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0954b5c35c..4acf23c676 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,6 +47,19 @@ jobs: test-shards: 6 shard-command: cargo xtask ci shard warm-command: cargo xtask ci warm + # A pull request runs only the test shards whose crates its changes reach: the crates that + # own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every + # crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the + # shards left out and why; pushes to main, the nightly run and the `full-ci` label run all + # six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does. + select-tests: true + shard-members: | + vectorcraft-ui-egui + vectorcraft-ui-egui + vectorcraft-engine + vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask + (rest) + (always) # The dependency cache also keeps the compiled workspace crates and test executables, so a # pull request's shards rebuild only the crates its changes reach. Each main run's `cache # warm` leg saves a rolling entry of its own, every leg restores the newest one, and diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 2a4ae4d927..261a27191e 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -70,7 +70,8 @@ pub static UI_EGUI: Split = Split { ], }; -/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length. +/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its +/// `shard-members` names each shard's crates. pub const GROUPS: &[Group] = &[ Group::Part(&UI_EGUI, 1), Group::Part(&UI_EGUI, 2), @@ -586,4 +587,29 @@ geom v0.1.0 (/w/geom)| ["lib: features absent in shard 4, [default,synth] with the whole workspace"] ); } + + /// The lines of the `shard-members: |` block in `workflow`, trimmed. + fn shard_members(workflow: &str) -> Vec<&str> { + let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |"); + let Some(key) = lines.next() else { return Vec::new() }; + let indent = |l: &str| l.len() - l.trim_start().len(); + lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect() + } + + #[test] + fn ci_names_the_crates_of_every_shard_for_test_selection() { + // The shared gate runs only the shards that test a crate a pull request reaches, by these lines. + let expected: Vec = GROUPS + .iter() + .map(|g| match g { + Group::Crates(crates) => crates.join(" "), + Group::Part(split, _) => split.crates.join(" "), + Group::Rest => "(rest)".to_owned(), + Group::Checks => "(always)".to_owned(), + }) + .collect(); + assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml"); + assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]); + assert!(shard_members("test-shards: 6\n").is_empty()); + } } From a9467c2b7e9129c9fe60af972b4961e7285f6d51 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:49:45 -0800 Subject: [PATCH 18/60] CI: the plug-in grant call-site audit runs in the checks shard The audit that lists the shipped code allowed to make a plug-in grant token or record a grant read the sources of every crate from a vectorcraft-plugins integration test. That test needed `reads-every-member` in the crate's metadata, so test selection picked shard 5 for every Rust change. The audit is now `cargo xtask grant-sites`, a step of `cargo xtask ci` that runs in shard 6 on every event. It keeps the same list, the same walk and the same filters, and leaves its own file out. vectorcraft-plugins no longer sets `reads-every-member`, and the old test is removed. --- crates/plugins/Cargo.toml | 4 - crates/plugins/src/permissions.rs | 2 +- crates/plugins/tests/grant_sites.rs | 92 ----------------- docs/target-app-parity.md | 2 +- xtask/src/grant_sites.rs | 148 ++++++++++++++++++++++++++++ xtask/src/main.rs | 6 +- 6 files changed, 155 insertions(+), 99 deletions(-) delete mode 100644 crates/plugins/tests/grant_sites.rs create mode 100644 xtask/src/grant_sites.rs diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index aecb0bd533..621f5e79bc 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -44,7 +44,3 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] } [features] # `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only). test-steady = [] - -# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate. -[package.metadata.craft] -reads-every-member = true diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index a78aeec09b..fc12ea177c 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -301,7 +301,7 @@ impl Grant { /// A [`Grant`] that [`crate::registry::grant`] records. The engine makes one where it records what /// a person approved and where it loads the grants kept in its plug-in folder; tests that set up a -/// grant use the same constructors. `tests/grant_sites.rs` fails when other shipped code makes one. +/// grant use the same constructors. `cargo xtask grant-sites` fails when other shipped code makes one. /// Native code linked into the app can still call these constructors, so the token does not /// protect against such code. #[derive(Debug)] diff --git a/crates/plugins/tests/grant_sites.rs b/crates/plugins/tests/grant_sites.rs deleted file mode 100644 index 7e96ef397d..0000000000 --- a/crates/plugins/tests/grant_sites.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! The shipped code that records a plug-in grant: only the engine's install approval and its load -//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`, -//! `registry::install_checked` or `registry::install_for_load`. A new call site fails this test until -//! it is added to the list. It checks the source, not what native code can do at run time. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; - -/// `(text, file, how many times)` for every place shipped code may name it. -const EXPECTED: &[(&str, &str, usize)] = &[ - ("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1), - ("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2), - ("registry::grant", "crates/engine/src/store.rs", 1), - ("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1), - ("registry::install_for_load", "crates/engine/src/store.rs", 2), -]; - -/// The names the audit counts. -const NAMES: [&str; 5] = [ - "GrantToken::after_engine_approval", - "GrantToken::from_engine_grants_file", - "registry::grant", - "registry::install_checked", - "registry::install_for_load", -]; - -/// Every `.rs` file under `dir`, without test files and folders. -fn sources(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { return }; - for entry in entries.flatten() { - let path = entry.path(); - let name = entry.file_name().to_string_lossy().to_string(); - if path.is_dir() { - if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") { - sources(&path, out); - } - } else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") { - out.push(path); - } - } -} - -/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {` -/// on. -fn shipped(text: &str) -> Vec<&str> { - let lines: Vec<&str> = text.lines().collect(); - let opens_test_module = |i: usize| { - lines[i] == "#[cfg(test)]" - && lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{')) - }; - let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len()); - lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect() -} - -/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`). -fn count(line: &str, name: &str) -> usize { - line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count() -} - -#[test] -fn grant_token_call_sites_are_limited() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); - let mut files = Vec::new(); - for top in ["crates", "apps", "xtask"] { - sources(&root.join(top), &mut files); - } - assert!(files.len() > 100, "found only {} source files under {}", files.len(), root.display()); - let mut found: BTreeMap<(&str, String), usize> = BTreeMap::new(); - for file in &files { - let text = std::fs::read_to_string(file).unwrap(); - let rel = file.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"); - for line in shipped(&text) { - for name in NAMES { - let n = count(line, name); - if n > 0 { - *found.entry((name, rel.clone())).or_default() += n; - } - } - } - } - let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect(); - assert_eq!(found, expected, "shipped code that makes a grant token or records a grant"); -} - -/// The audit's own filters: a test module and comments are left out, a longer name isn't counted. -#[test] -fn the_audit_skips_test_code_and_comments() { - let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n"; - let lines = shipped(text); - assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::(), 1, "{lines:?}"); -} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4df379b998..c5afd04db2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2852,7 +2852,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. -- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `xtask/src/grant_sites.rs` (`cargo xtask grant-sites`), `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in's manifest from a custom section (G17):** a module that carries its manifest in a `vc_manifest` custom section, with `"abi": 1`, is inspected, installed and loaded at startup without being instantiated, so none of its code runs (its start function, data segments, `vc_abi_version` and `vc_manifest`); the host checks its imports against the manifest's permissions, its `memory`, `vc_alloc` and `vc_run` exports by type, and its initial memory and tables against the limits its runs have. A repeated section, one over 64 KiB, or one that is not a valid manifest or gives another `abi` is refused. Such a module whose start function traps installs and fails at each run. Modules without the section load as before. The example plug-in carries the section. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. diff --git a/xtask/src/grant_sites.rs b/xtask/src/grant_sites.rs new file mode 100644 index 0000000000..0e8f0708c4 --- /dev/null +++ b/xtask/src/grant_sites.rs @@ -0,0 +1,148 @@ +//! `cargo xtask grant-sites`: the shipped code that records a plug-in grant. Only the engine's +//! install approval and its load of the plug-in folder's grants file make a `GrantToken` and call +//! `registry::grant`, `registry::install_checked` or `registry::install_for_load`. A new call site +//! fails this check until it is added to the list. It checks the source, not what native code can +//! do at run time. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// `(text, file, how many times)` for every place shipped code may name it. +const EXPECTED: &[(&str, &str, usize)] = &[ + ("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1), + ("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2), + ("registry::grant", "crates/engine/src/store.rs", 1), + ("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1), + ("registry::install_for_load", "crates/engine/src/store.rs", 2), +]; + +/// This file lists the names it counts. +const SELF: &str = "xtask/src/grant_sites.rs"; + +/// The names the audit counts. +const NAMES: [&str; 5] = [ + "GrantToken::after_engine_approval", + "GrantToken::from_engine_grants_file", + "registry::grant", + "registry::install_checked", + "registry::install_for_load", +]; + +pub fn run(root: &Path) -> Result<(), String> { + let mut files = Vec::new(); + for top in ["crates", "apps", "xtask"] { + sources(&root.join(top), &mut files); + } + if files.len() <= 100 { + return Err(format!("grant-sites: found only {} source files under {}", files.len(), root.display())); + } + let found = scan(root, &files)?; + let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect(); + if found == expected { + println!("grant-sites: only the listed shipped code makes a grant token or records a grant"); + return Ok(()); + } + let list = + |m: &BTreeMap<(&str, String), usize>| m.iter().map(|((name, file), n)| format!("{file}: {name} x{n}")).collect::>().join("\n "); + Err(format!( + "shipped code that makes a grant token or records a grant differs from EXPECTED in xtask/src/grant_sites.rs\nfound:\n {}\nexpected:\n {}", + list(&found), + list(&expected) + )) +} + +/// How many times each name occurs in the shipped lines of each of `files`, keyed by the file's +/// path relative to `root`. This file is left out. +fn scan(root: &Path, files: &[PathBuf]) -> Result, String> { + let mut found = BTreeMap::new(); + for file in files { + let rel = file.strip_prefix(root).unwrap_or(file).to_string_lossy().replace('\\', "/"); + if rel == SELF { + continue; + } + let text = std::fs::read_to_string(file).map_err(|e| format!("grant-sites: {}: {e}", file.display()))?; + for line in shipped(&text) { + for name in NAMES { + let n = count(line, name); + if n > 0 { + *found.entry((name, rel.clone())).or_default() += n; + } + } + } + } + Ok(found) +} + +/// Every `.rs` file under `dir`, without test files and folders. +fn sources(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().to_string(); + if path.is_dir() { + if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") { + sources(&path, out); + } + } else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") { + out.push(path); + } + } +} + +/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {` +/// on. +fn shipped(text: &str) -> Vec<&str> { + let lines: Vec<&str> = text.lines().collect(); + let opens_test_module = |i: usize| { + lines[i] == "#[cfg(test)]" + && lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{')) + }; + let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len()); + lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect() +} + +/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`). +fn count(line: &str, name: &str) -> usize { + line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The audit's own filters: a test module and comments are left out, a longer name isn't counted. + #[test] + fn the_audit_skips_test_code_and_comments() { + let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n"; + let lines = shipped(text); + assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::(), 1, "{lines:?}"); + } + + /// The walk leaves out test files and folders and this file; a shipped call site is counted. + #[test] + fn the_audit_counts_shipped_files_only() { + let dir = std::env::temp_dir().join(format!("vc-grant-sites-{}", std::process::id())); + let file = |p: &str| { + let path = dir.join(p); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, "fn f() { registry::grant(t); }\n").unwrap(); + }; + for p in [ + "crates/x/src/lib.rs", + "crates/x/src/tests.rs", + "crates/x/src/a_tests.rs", + "crates/x/tests/it.rs", + "crates/x/benches/b.rs", + "xtask/src/grant_sites.rs", + ] { + file(p); + } + let mut files = Vec::new(); + for top in ["crates", "apps", "xtask"] { + sources(&dir.join(top), &mut files); + } + let found = scan(&dir, &files); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(found.unwrap(), BTreeMap::from([(("registry::grant", "crates/x/src/lib.rs".to_owned()), 1)])); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 08a55df09a..c66da19b12 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -9,6 +9,7 @@ mod brands; mod bundle; mod cache_units; mod cursors; +mod grant_sites; mod ico; mod layers; mod pdf_deps; @@ -32,6 +33,7 @@ commands: assets check that every icon/image/font/asset is attributed in ASSETS.md brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) + grant-sites check that only the listed shipped code makes a plug-in grant token or records a grant i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift @@ -39,7 +41,7 @@ commands: layers enforce the crate dependency layering (plan/architecture.md §3) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker test the workspace tests (cargo nextest when installed, else cargo test), then the doctests - ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, grant-sites, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps ci warm build what every shard builds, without running it (fills the gate's cache); with @@ -74,6 +76,7 @@ fn main() -> ExitCode { Some("assets") => assets::run(&root()), Some("brands") => brands::run(&root()), Some("cursors") => cursors::run(&root()), + Some("grant-sites") => grant_sites::run(&root()), Some("i18n-report") => cmd_i18n_report(), Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")), Some("layers") => cmd_layers(), @@ -514,6 +517,7 @@ fn ci_steps() -> Vec { ("pdf-deps", Box::new(|| pdf_deps::run(&root()))), ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), + ("grant-sites", Box::new(|| grant_sites::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), ("i18n-report", Box::new(cmd_ci_i18n_report)), ("ui-commands", Box::new(|| ui_commands::run(&root(), true))), From 316a4b6bfae1ce9baeb622321921861d5400ac44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:54:19 -0800 Subject: [PATCH 19/60] Scripts: file.new takes Overprint Preview and reads the profile's linked files A script's addDocument with previewMode OverprintPreview failed: file.new turned the view on with view.overprintPreview, which scripts may not run. A script's file.new now asks for the view, and the run turns Overprint Preview on when it ends; a run that fails does not turn it on. The images a New Document profile's symbols, patterns and brushes link to were read under the script's file gate, after the profile's own file was read outside it, so images beside the profile showed only their preview. They are now read the way the profile's file is, under the automation roots in force. --- crates/engine/src/cmd/colormgmt.rs | 7 +++ crates/engine/src/cmd/newdoc.rs | 16 +++++-- crates/engine/src/lib.rs | 3 ++ crates/engine/src/script/mod.rs | 10 +++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/script_dom.rs | 63 ++++++++++++++++++++++++++ docs/mcp.md | 4 +- 7 files changed, 98 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 1ed09da2ee..2a87e7e53c 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -1521,6 +1521,13 @@ fn store_view(s: &mut Session, v: proof::ProofView) { } } +/// Turn Overprint Preview on, as `view.overprintPreview` with `on` true does. +pub(crate) fn turn_on_overprint_preview(s: &mut Session) { + let mut v = proof::view(); + v.overprint = true; + store_view(s, v); +} + fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option)) -> Result { let on = on_param(p, "on", cmd)?; let mut v = proof::view(); diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 6c71a75b96..8f799c840a 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -904,9 +904,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { super::newart::reset(s); } // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both - // are views of the whole app, so Default leaves them as they are. + // are views of the whole app, so Default leaves them as they are. A script's run turns it on + // when the run ends, and not at all when the run fails. if settings.preview_mode == PreviewMode::Overprint { - s.execute("view.overprintPreview", &json!({ "on": true }))?; + if s.script_in_run { + s.overprint_after_run = true; + } else { + s.execute("view.overprintPreview", &json!({ "on": true }))?; + } } remember(s, &settings); let mut out = json!({ "index": i, "previewMode": settings.preview_mode.id() }); @@ -1058,8 +1063,11 @@ impl Session { // them, so the new document's assigned profiles draw and are saved with it. let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?; // Linked images in its symbols, patterns and brushes are read from their files, as placing - // a document reads them. - super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false); + // a document reads them. They are part of the profile, so a script's gate does not apply to + // them either; the automation roots in force still do. + crate::file_access::app_folder_read(|| { + super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false); + }); warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc)); Ok(Some(ReadProfile { doc, file, warnings })) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fb2115190c..ac54345cd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -383,6 +383,9 @@ pub struct Session { pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// A script's `file.new` asked for Overprint Preview, which is turned on when the run ends and + /// is not turned on when the run fails. + pub(crate) overprint_after_run: bool, /// The desktop app supplies each window by (document uid, runtime window identity) while a /// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center, /// and screen mode. This list is empty without windows (headless). diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index f386b4dc68..f6d5869fd3 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -493,11 +493,13 @@ struct World { /// The choices outside the documents that a script's commands can change: the preferences, the /// global edit options, the Select Similar Objects attribute, the recent URLs, the chosen gradient stop, freeform point and appearance -/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state. +/// item, the Eyedropper's sample, the envelope defaults, the Caps Lock state and whether Overprint +/// Preview turns on when the run ends. #[derive(Clone)] struct Choices { prefs: crate::Prefs, caps_lock: bool, + overprint_after_run: bool, eyedropper_sample: Option>, global_edit_options: cmd::globaledit::Options, select_similar: &'static str, @@ -513,6 +515,7 @@ impl Choices { Self { prefs: s.prefs.clone(), caps_lock: s.caps_lock, + overprint_after_run: s.overprint_after_run, eyedropper_sample: s.eyedropper_sample.clone(), global_edit_options: s.global_edit_options.clone(), select_similar: s.select_similar, @@ -527,6 +530,7 @@ impl Choices { fn put(self, s: &mut Session) { s.prefs = self.prefs; s.caps_lock = self.caps_lock; + s.overprint_after_run = self.overprint_after_run; s.eyedropper_sample = self.eyedropper_sample; s.global_edit_options = self.global_edit_options; s.select_similar = self.select_similar; @@ -541,6 +545,7 @@ impl Choices { use std::mem::swap; swap(&mut self.prefs, &mut s.prefs); swap(&mut self.caps_lock, &mut s.caps_lock); + swap(&mut self.overprint_after_run, &mut s.overprint_after_run); swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample); swap(&mut self.global_edit_options, &mut s.global_edit_options); swap(&mut self.select_similar, &mut s.select_similar); @@ -2630,6 +2635,9 @@ impl Session { self.script_stop.clear(); self.reset_tool(); cmd::compositefonts::sync(self); + if std::mem::take(&mut self.overprint_after_run) { + cmd::colormgmt::turn_on_overprint_preview(self); + } let host = &job.host; let mut report = json!({ "ok": true, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 8a9eea3b4a..9dd542709d 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -192,6 +192,7 @@ impl Session { script_high_water: Default::default(), script_style_trail: Default::default(), script_in_run: false, + overprint_after_run: false, window_views: vec![], script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 14878904fb..5c9773d852 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1559,6 +1559,69 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +/// A run's `addDocument` with Overprint Preview turns the view on when the run ends; a run that +/// fails leaves it off. +#[test] +fn add_document_with_overprint_preview_turns_it_on_when_the_run_ends() { + if !super::in_own_process("tests::script_dom::add_document_with_overprint_preview_turns_it_on_when_the_run_ends") { + return; + } + let mut s = Session::new(); + let overprint = |s: &mut Session| s.execute("view.proofSetup", &json!({})).unwrap()["overprintPreview"].clone(); + s.execute("view.overprintPreview", &json!({"on": false})).unwrap(); + let add = "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.OverprintPreview; app.documents.addDocument('Print', p);"; + let e = failure(&mut s, &format!("{add} throw new Error('stopped here');")); + assert!(e.contains("stopped here"), "{e}"); + assert_eq!(overprint(&mut s), false); + assert!(s.documents().is_empty()); + assert_eq!(log(&mut s, &format!("{add} vc.log(app.documents.length);")), vec![json!(1)]); + assert_eq!(overprint(&mut s), true); + assert_eq!(s.documents().len(), 1); + s.execute("view.overprintPreview", &json!({"on": false})).unwrap(); +} + +/// A run's `addDocument` reads the images the profile links to beside its file, as the person's +/// File › New does. +#[test] +fn add_document_reads_the_images_the_profile_links_to() { + let dir = std::env::temp_dir().join(format!("vc-script-newdoc-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let img = craft_image_codecs::Image::from_raw( + 600, + 300, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [200u8, 30, 30, 255].repeat(600 * 300), + ) + .unwrap(); + let mut bytes = vec![]; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) + .map(|b| bytes.extend_from_slice(&b)) + .unwrap(); + let pic = dir.join("logo.png"); + std::fs::write(&pic, &bytes).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": true})).unwrap(); + s.execute("symbol.new", &json!({"name": "Logo"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + let read = |s: &Session| { + let images = &s.doc().unwrap().doc.images; + !images.is_empty() && images.values().all(|b| !b.is_proxy()) + }; + s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert!(read(&s), "the person's File › New reads the linked image"); + // No document open when the run begins links to the image, so the run's gate alone does not + // let it be read. + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + log(&mut s, "app.documents.addDocument('Print');"); + assert!(read(&s), "a script's addDocument reads it too"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn setting_selected_keeps_how_the_other_objects_are_selected() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 3b647e4c7b..2ad125d7eb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2985,10 +2985,12 @@ through `$`: `transparencyGrid` also take `null` and can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A `presetSettings` that is omitted, `undefined` or `null` gives the preset's settings unchanged; any other value - that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder, and the files its symbols, patterns and brushes link to, as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it that cannot be used, for example) goes to the Script Console as a line `addDocument: `. A `previewMode` of + `DocumentPreviewMode.OverprintPreview` turns Overprint Preview on when the run ends; a run that fails does not turn + it on. A `previewMode` of `DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, From 32543571f3d61fc1c4c26e9da6bbd58b154a37e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:41:27 -0800 Subject: [PATCH 20/60] Scripts: close with SaveOptions.SAVECHANGES saves a native file whose last save named a range A native save keeps every artboard in its main file and reads `range` only for the separate files of `separateArtboards`. The close check treated a native document last saved with `range` and without `separateArtboards` as a save of some artboards, and refused to close it although the save writes every artboard. --- crates/engine/src/script/dom/save_open.rs | 13 +++++++------ crates/engine/src/tests/script_save_open.rs | 12 ++++++++---- docs/mcp.md | 2 +- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 510364d249..fe11e6233b 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -1010,12 +1010,13 @@ const SAVES_SOME_ARTBOARDS: &str = "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; /// Whether the file that saving `st` with its remembered options writes would omit artboards. A -/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` -/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its -/// `range` names only the separate files. An EPS file embeds the whole document in its main file, -/// so its `artboardRange` never omits an artboard from what reopens. +/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file holds every +/// artboard, and its `range` names only the separate files of `separateArtboards`. A `.ai` file +/// other than a legacy version 7 one with `separateArtboards` holds every artboard too. An EPS +/// file embeds the whole document in its main file, so its `artboardRange` never omits an artboard +/// from what reopens. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { - if st.format == "eps" { + if matches!(st.format, "eps" | "vectorcraft" | "template") { return false; } let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); @@ -1027,7 +1028,7 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool { return true; } let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options); - if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy { + if matches!(st.format, "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy { return false; } let count = st.doc.artboards.len(); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index e8bd8675cb..ffcc1d320d 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -1167,9 +1167,9 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { let _ = std::fs::remove_dir_all(base); } -/// A `.ai` file saved without separate artboard files, and an SVG file that carries the native -/// document, keep every artboard whatever `range` names, so `close(SaveOptions.SAVECHANGES)` saves -/// them; a `range` the save refuses still refuses. +/// A native file and a `.ai` file saved without separate artboard files, and an SVG file that +/// carries the native document, keep every artboard whatever `range` names, so +/// `close(SaveOptions.SAVECHANGES)` saves them; a `range` the save refuses still refuses. #[test] fn closing_with_save_changes_saves_files_that_keep_every_artboard() { let base = folder("closekeepall"); @@ -1177,7 +1177,11 @@ fn closing_with_save_changes_saves_files_that_keep_every_artboard() { let mut s = session(&base); data_folder(&mut s, &base) }; - for (name, options) in [("whole.ai", json!({"range": "2"})), ("native.svg", json!({"preserveEditing": true, "range": "1"}))] { + for (name, options) in [ + ("whole.vectorcraft", json!({"range": "2"})), + ("whole.ai", json!({"range": "2"})), + ("native.svg", json!({"preserveEditing": true, "range": "1"})), + ] { let mut s = session(&base); data_folder(&mut s, &base); let file = dir.join(name); diff --git a/docs/mcp.md b/docs/mcp.md index 55886fae8f..ec90023736 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3193,7 +3193,7 @@ through `$`: and leaves the document open when the document has no file (a converted or recovered document included) or when the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with - `useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other + `useArtboards: false` omits artboards; a native file (its `range` names only the separate files of `separateArtboards`) and a `.ai` or `.ait` file other than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with From b852316921dad971b935ed9b3f9cbb221e2eba50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:12:19 -0800 Subject: [PATCH 21/60] Plug-ins: fix event delivery edge cases from review - A commit or cancel with no drag open no longer ends an interaction for plug-in events. - A host query that panics during a handler still puts the session back. - Handler calls after a replayed command are checked as calls from outside. - A rolled-back batch puts back the events its opens pushed out of the 32-event queue. - Installing a plug-in again, the same module included, turns its events back on; plugin.info's eventsOff follows the same rule. - A document added before the first check records its baseline. - Handler failures show in the status bar from their English templates, translated when shown, and event handler time counts toward the frame time. - Tests check that the handler ran in the tested pass, and the script-run test no longer writes to other sessions' status bar. --- crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/src/cmd/plugin_call.rs | 8 +- crates/engine/src/plugin_events.rs | 153 ++++++++++++++++++++--- crates/engine/src/session/edit.rs | 9 +- crates/engine/src/tests/plugin_events.rs | 47 +++++++ crates/ui-egui/src/app.rs | 53 ++++++-- crates/ui-egui/src/caches.rs | 2 + crates/ui-egui/src/chrome/status_bar.rs | 14 +++ crates/ui-egui/src/chrome/tests.rs | 2 +- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/tests/plugins.rs | 6 + crates/ui-egui/src/tests/script_run.rs | 13 +- docs/mcp.md | 3 +- docs/plugins.md | 2 +- docs/target-app-parity.md | 2 +- 15 files changed, 279 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 340e4d4efc..e2ffb44d0c 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -2437,7 +2437,7 @@ pub fn specs() -> Vec { "Plug-in Info", [], None, - "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or another module is installed with its id), lastEventError? (with events: its handler's last failure, null)}", + "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or a module is installed with its id again, the same module included), lastEventError? (with events: its handler's last failure, null)}", always, info ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 97a66d3897..71669042f6 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -508,7 +508,8 @@ fn read_only(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) let pending_paint = s.pending_paint.clone(); let start = s.docs.clone(); let active = s.active; - let r = f(s); + // A panic in `f` still puts everything back before it carries on. + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(s))); let now = std::mem::replace(&mut s.docs, start); let mut changed = s.active != active || now.len() != s.docs.len(); for st in &mut s.docs { @@ -532,7 +533,10 @@ fn read_only(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) if changed { s.sync_front_profiles(); } - (r, changed) + match r { + Ok(r) => (r, changed), + Err(payload) => std::panic::resume_unwind(payload), + } } /// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 89a23ae390..7a60028afc 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -22,7 +22,7 @@ //! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]). //! - A handler that fails is reported once a streak; after //! [`vectorcraft_plugins::events::MAX_EVENT_FAILURES`] failures in a row the plug-in's events stop -//! until the session ends, or until another module is installed under its id. +//! until the session ends, or until a module is installed under its id again. //! - When no installed plug-in reacts to events, a check returns before comparing anything. use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; @@ -40,6 +40,10 @@ use crate::Session; /// Most events that wait for delivery. pub const MAX_PENDING: usize = 32; +/// Most events kept after the queue dropped them for room, until the next delivery, for a +/// rollback to put back. +const MAX_EVICTED: usize = 1024; + /// Most handlers called across all deliveries in one frontend frame. pub const MAX_FRAME_HANDLERS: usize = 4; @@ -82,6 +86,8 @@ struct Pending { to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, + /// The event this enqueue pushed out of the waiting queue. + displaced: Option, /// Queued by a command of the running script, whose run has not ended yet /// ([`Session::plugin_events_script_ended`]). by_script: bool, @@ -101,10 +107,11 @@ impl Pending { } } -/// One plug-in's failed handlers in a row, for the module with `hash`. +/// One plug-in's failed handlers in a row, for the installation `serial` of the module with `hash`. #[derive(Clone, Debug, Default)] struct Failures { hash: String, + serial: u64, count: u32, disabled: bool, last_error: Option, @@ -121,6 +128,28 @@ pub struct Notice { pub level: LogLevel, /// The text, in English for a failure. pub text: String, + /// For a failure, what failed, for the frontend to word in the interface language; `None` for + /// a line the handler wrote. + pub failure: Option, +} + +/// A failure a [`Notice`] reports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Failure { + /// A handler failed with `error`, the first time in a row. + Handler { error: String }, + /// The plug-in's events stopped after `count` failed handlers in a row. + EventsOff { count: u32 }, +} + +impl Failure { + /// The English message with `{event}`, `{error}` and `{n}` placeholders, `one` or `other` by + /// the count. + pub const HANDLER: &'static str = "its {event} handler failed: {error}"; + pub const EVENTS_OFF_ONE: &'static str = + "its events are off until it is installed again or VectorCraft starts again, after {n} failed handler in a row"; + pub const EVENTS_OFF_OTHER: &'static str = + "its events are off until it is installed again or VectorCraft starts again, after {n} failed handlers in a row"; } /// The session's plug-in event state. @@ -130,6 +159,9 @@ pub struct PluginEvents { /// The plug-ins that reacted to events when `seen` was taken. seen_by: Vec, pending: VecDeque, + /// The events dropped from `pending` since the last delivery, oldest first, which + /// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room. + evicted: VecDeque, /// How many events have been queued as their own entry. queued: u64, dispatching: bool, @@ -191,13 +223,22 @@ impl PluginEvents { } return; } + let mut displaced = None; if self.pending.len() >= MAX_PENDING && let Some(dropped) = self.pending.pop_front() { + displaced = Some(dropped.seq); log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); + // Kept until the next delivery, in case a rollback frees room for it again. + // When that store is full, an open goes first, since only opens are rolled back. + if self.evicted.len() >= MAX_EVICTED { + let at = self.evicted.iter().position(|p| p.event == Event::DocumentOpened).unwrap_or(0); + self.evicted.remove(at); + } + self.evicted.push_back(dropped); } let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); - self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, by_script: false }); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false }); self.queued += 1; } @@ -208,16 +249,24 @@ impl PluginEvents { self.notices.push_back(n); } - /// The failures of plug-in `p`, started again when another module was installed under its id. + /// The failures of plug-in `p`, started again when a module was installed under its id since + /// they were recorded, the same module again included. fn failures_of(&mut self, p: &Plugin) -> &mut Failures { let f = self.failures.entry(p.id().to_string()).or_default(); - if f.hash != p.hash() { - *f = Failures { hash: p.hash().to_string(), ..Failures::default() }; + if !f.is_of(p) { + *f = Failures { hash: p.hash().to_string(), serial: p.serial(), ..Failures::default() }; } f } } +impl Failures { + /// Whether these are the failures of `p` as it is installed now. + fn is_of(&self, p: &Plugin) -> bool { + self.hash == p.hash() && self.serial == p.serial() + } +} + /// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its /// contents (for comparing its options) and the ids of the rows directly in it, in order. type LayerRow = (Id, Option, vectorcraft_doc::Node, Vec); @@ -323,10 +372,12 @@ impl Session { /// files they wrote stay written, and so do the events of documents a frontend opened while the /// run was paused. The next delivery gives what is left in the order it was queued. pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { + let events = &mut self.plugin_events; if !kept { - self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + events.evicted.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); } - for p in &mut self.plugin_events.pending { + for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) { p.by_script = false; } } @@ -339,8 +390,20 @@ impl Session { /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The /// saves stay, since the files they wrote stay written. + /// Events displaced by those opens return in their original order, ahead of the events still + /// waiting, while there is room. pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { - self.plugin_events.pending.retain(|p| p.event != Event::DocumentOpened || p.seq < mark); + let events = &mut self.plugin_events; + let undone = |p: &Pending| p.event == Event::DocumentOpened && p.seq >= mark; + let displaced: Vec<_> = events.pending.iter().chain(&events.evicted).filter(|p| undone(p)).filter_map(|p| p.displaced).collect(); + events.pending.retain(|p| !undone(p)); + events.evicted.retain(|p| !undone(p)); + while events.pending.len() < MAX_PENDING + && let Some(at) = events.evicted.iter().rposition(|p| displaced.contains(&p.seq)) + && let Some(p) = events.evicted.remove(at) + { + events.pending.push_front(p); + } } /// Compares each open document with how the last check saw it and queues the events its changes @@ -359,6 +422,7 @@ impl Session { self.plugin_events.seen.clear(); self.plugin_events.seen_by.clear(); self.plugin_events.pending.clear(); + self.plugin_events.evicted.clear(); return; } let installed: Vec = subs.iter().map(|p| recipient(p)).collect(); @@ -425,6 +489,10 @@ impl Session { } let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); self.plugin_events.dispatching = true; + self.plugin_events.evicted.clear(); + // A handler's calls are checked as calls from outside, also when the command that ended + // played saved steps ([`Session::replay`] puts its flag back only after this delivery). + let replaying = self.set_replaying(false); // The commands a handler calls run nested, never journaled; a panic in one leaves the depth // as it was found. let depth = self.depth; @@ -477,6 +545,7 @@ impl Session { self.plugin_events.pending.push_front(p); } self.depth = depth; + self.set_replaying(replaying); self.plugin_events.dispatching = false; self.plugin_events.pending.iter().any(|p| { !p.by_script @@ -527,7 +596,7 @@ impl Session { }; let (id, name) = (plugin.id().to_string(), m.name.clone()); for line in report.lines { - self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text }); + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text, failure: None }); } let failures = self.plugin_events.failures_of(plugin); let e = match r { @@ -542,23 +611,31 @@ impl Session { let (count, first) = (failures.count, failures.count == 1); log::warn!("plug-in {id}: its {event} handler failed: {e}"); if first { - let text = format!("its {event} handler failed: {e}"); - self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text }); + let text = Failure::HANDLER.replace("{event}", event).replace("{error}", &e); + let failure = Some(Failure::Handler { error: e }); + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text, failure }); } if count >= MAX_EVENT_FAILURES { self.plugin_events.failures_of(plugin).disabled = true; - let text = format!("its events are off until VectorCraft starts again, after {count} failed handlers in a row"); - self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text }); + let text = if count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER }.replace("{n}", &count.to_string()); + let failure = Some(Failure::EventsOff { count }); + self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text, failure }); } } /// Takes each open document the last check didn't see, one opened or created since, as it is /// now, so the next check compares it with this state: a change made to it before the next /// delivery gives its event. Called when a document is added and after each top-level command. - /// Nothing is kept when no plug-in reacted to events at the last check, nor for a - /// document in an interaction. + /// When no check has seen a plug-in that reacts to events, the first check runs now for the + /// plug-ins installed. Nothing is kept when none is installed, nor for a document in an + /// interaction. pub(crate) fn plugin_events_see_new_documents(&mut self) { if self.plugin_events.seen_by.is_empty() { + // No check has run since plug-ins that react to events were installed: one now takes + // every open document as it is, for the plug-ins installed now. + if !self.plugin_events.subscribers().is_empty() { + self.check_plugin_events(false); + } return; } for st in &self.docs { @@ -636,7 +713,7 @@ impl Session { /// Whether this session stopped delivering events to plug-in `p` after its handlers failed, and /// the last failure's error. pub fn plugin_event_status(&self, p: &Plugin) -> (bool, Option) { - match self.plugin_events.failures.get(p.id()).filter(|f| f.hash == p.hash()) { + match self.plugin_events.failures.get(p.id()).filter(|f| f.is_of(p)) { Some(f) => (f.disabled, f.last_error.clone()), None => (false, None), } @@ -750,4 +827,46 @@ mod tests { assert_eq!(e.pending.len(), MAX_PENDING); assert_eq!(e.pending.front().map(|p| p.document), Some(5), "the oldest are dropped"); } + + #[test] + fn a_rollback_of_opens_brings_back_the_events_they_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let mark = s.plugin_events_mark(); + for uid in 0..(2 * MAX_PENDING) as u64 { + s.plugin_events.queue(Event::DocumentOpened, 100 + uid, vec![], vec![r.clone()]); + } + assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the save was pushed out"); + s.plugin_events.queue(Event::DocumentSaved, 999, vec![], vec![r]); + s.forget_plugin_opens_since(mark); + let left: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event.name(), p.document)).collect(); + assert_eq!( + left, + [ + (Event::DocumentSaved.name(), 1), + (Event::DocumentSaved.name(), 2), + (Event::DocumentSaved.name(), 3), + (Event::DocumentSaved.name(), 999) + ] + ); + } + + #[test] + fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() { + let mut s = Session::new(); + for uid in 0..=MAX_PENDING as u64 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![]); + } + assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0); + s.plugin_events.pending.pop_front(); + let waiting = s.plugin_events.pending.clone(); + let mark = s.plugin_events_mark(); + s.plugin_events.queue(Event::DocumentOpened, 100, vec![], vec![]); + s.forget_plugin_opens_since(mark); + assert_eq!(s.plugin_events.pending, waiting); + assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0); + } } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 5a7a1ee08d..891f77b789 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -659,11 +659,13 @@ impl Session { // The interaction is taken below, so its starting state is read first: the commit is what // the previews that came before it changed. let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten(); + // Plug-in events wait for an open interaction only: a commit with none open ends nothing. + let open = self.in_interaction() || self.holds_interaction(); let r = self.commit_interaction_unwatched(); if let Some(before) = before { self.reveal_since(&before); } - if r.is_ok() { + if r.is_ok() && open { self.plugin_events_interaction_ended(); } r @@ -762,6 +764,7 @@ impl Session { } pub fn cancel_interaction(&mut self) -> Result<()> { + let open = self.in_interaction() || self.holds_interaction(); self.put_back_interaction(); self.clear_deferred_overlay_cache(); self.decoded_images.empty(); @@ -798,7 +801,9 @@ impl Session { if !used_defaults_only { self.inherit_new_art(); } - self.plugin_events_interaction_ended(); + if open { + self.plugin_events_interaction_ended(); + } Ok(()) } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 7c83109c01..f7ac63e770 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -1029,5 +1029,52 @@ fn a_handler_that_keeps_failing_is_turned_off() { assert!(notices[1].contains("after 3 failed handlers in a row"), "{}", notices[1]); let info = run(&mut s, "plugin.info", json!({"id": id})); assert_eq!(info["eventsOff"], json!(true)); + // Installing the same module again turns its events back on. + install(&mut s, id, r#"["selection.changed"]"#, &[], "", "unreachable", &[]); + let info = run(&mut s, "plugin.info", json!({"id": id})); + assert_eq!(info["eventsOff"], json!(false), "a new installation starts with no failures"); run(&mut s, "plugin.remove", json!({"id": id})); } + +/// A commit or cancel with no interaction open ends nothing: it records no baseline, so a change +/// made and undone before the next delivery gives no event. +#[test] +fn a_commit_or_cancel_without_an_interaction_records_no_baseline() { + let id = "test.events.no_interaction"; + for commit in [true, false] { + let mut s = local_session(); + s.plugin_event_frames = true; + let a = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT); + s.deliver_plugin_events(); + let _ = given(&mut s, id); + run(&mut s, "select.set", json!({"ids": [a.0]})); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + run(&mut s, "select.none", json!({})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "commit: {commit}"); + } +} + +/// A document added before any check of a plug-in that reacts to events is compared with how it +/// was when it was added, so its first selection change gives an event. +#[test] +fn a_document_added_before_the_first_check_gives_its_first_change() { + let id = "test.events.first_document"; + let mut s = Session::new(); + s.plugin_event_frames = true; + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap(); + s.plugin_events.test_subscribers = Some(vec![std::sync::Arc::new(plugin)]); + run(&mut s, "file.new", json!({"width": 400, "height": 200})); + rect(&mut s, 10.0); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["selection.changed"]); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 729a87db09..0b03a8c955 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -61,6 +61,12 @@ fn now_secs() -> f64 { monotonic_ms() / 1000.0 } +#[cfg(test)] +std::thread_local! { + /// The notices [`VectorcraftApp::deliver_plugin_events`] took on this thread. + static TAKEN_EVENT_NOTICES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + impl VectorcraftApp { /// The app around `session`, reaching the platform through `services` (the clipboard, files /// and the like). It registers the app's icon sets, starts cataloguing the installed fonts at @@ -376,7 +382,19 @@ impl VectorcraftApp { trace_runs::poll(self); placing::poll(self); retype_runs::poll(self); - self.deliver_plugin_events() + // The handlers' time counts toward the frame-time sample, as the delivery after the UI + // pass does. + let t0 = monotonic_ms(); + let pending = self.deliver_plugin_events(); + self.perf.early_events_ms += monotonic_ms() - t0; + pending + } + + /// The plug-in event notices this thread's apps took, for tests that check a handler ran in a + /// pass ([`Self::deliver_plugin_events`] takes them from the session). + #[cfg(test)] + pub(crate) fn take_event_notices_taken() -> Vec { + TAKEN_EVENT_NOTICES.with(|taken| std::mem::take(&mut *taken.borrow_mut())) } /// Hands the plug-ins that react to events the changes of this frame @@ -385,15 +403,24 @@ impl VectorcraftApp { /// Returns whether the status bar changed or runnable handlers remain queued. fn deliver_plugin_events(&mut self) -> bool { let pending = self.session.deliver_plugin_events(); - let shown = self - .session - .take_plugin_event_notices() - .into_iter() - .rev() - .find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn)); - let Some(n) = shown else { return pending }; + let notices = self.session.take_plugin_event_notices(); + #[cfg(test)] + TAKEN_EVENT_NOTICES.with(|taken| taken.borrow_mut().extend(notices.iter().cloned())); + let shown = notices.into_iter().rev().find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn)); + let Some(mut n) = shown else { return pending }; let name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); - self.status(format!("{name}: {}", n.text)); + // The status is kept in English and translated when the status bar shows it, with the + // plug-in's name kept as it is; a line the handler wrote is kept whole. + let status = format!("{name}: {}", n.text); + self.status(status.clone()); + if n.failure.is_some() { + n.name = name; + self.ui.status_plugin_event = Some((status, n)); + self.ui.status_kept = None; + } else { + self.ui.status_plugin_event = None; + self.ui.status_kept = Some((String::new(), status, String::new())); + } true } @@ -490,6 +517,7 @@ impl VectorcraftApp { fn tick_frame(&mut self, ctx: &egui::Context) { self.ticked_pass = Some(ctx.cumulative_pass_nr()); if ctx.current_pass_index() == 0 { + self.perf.early_events_ms = 0.0; self.session.begin_plugin_event_frame(); } let lang = self.ui_language(); @@ -681,6 +709,9 @@ impl VectorcraftApp { /// input to the automation roots and turns a panic into an error message. pub fn ui(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); + if ctx.current_pass_index() == 0 && self.ticked_pass != Some(ctx.cumulative_pass_nr()) { + self.perf.early_events_ms = 0.0; + } self.adopt_context(&ctx); let confined = self.automation_scope(&ctx); if let Err(msg) = file_access::confine(confined.as_ref(), || { @@ -698,6 +729,8 @@ impl VectorcraftApp { } if !ctx.will_discard() { self.perf.frame_ms += monotonic_ms() - t0; + } else { + self.perf.early_events_ms += monotonic_ms() - t0; } }) }) { @@ -793,7 +826,7 @@ impl VectorcraftApp { // A pass egui will discard and rerun is not a presented frame: it must not become the // frame-time sample, and it must not issue a capture of what it drew. if !ctx.will_discard() { - self.perf.frame_ms = monotonic_ms() - t0; + self.perf.frame_ms = monotonic_ms() - t0 + std::mem::take(&mut self.perf.early_events_ms); self.issue_captures(&ctx); // A hidden window's pass shows nothing, so the step waits for a pass the user sees. if step_held && !self.viewport_hidden(&ctx) { diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 06c564f4c8..58b2e6c803 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -409,4 +409,6 @@ pub struct Perf { pub frame_ms: f64, pub render_ms: f64, pub fps: f64, + /// Time plug-in event handlers took before the frame's UI pass, added to its `frame_ms`. + pub early_events_ms: f64, } diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index b7446defb4..e4a9e91d82 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -771,6 +771,20 @@ fn date_time_now() -> (String, u64) { /// it are translated. pub(crate) fn status_message(app: &VectorcraftApp) -> String { let status = app.ui.status.as_str(); + if let Some((original, notice)) = &app.ui.status_plugin_event + && original == status + { + use vectorcraft_engine::plugin_events::Failure; + let text = match ¬ice.failure { + Some(Failure::Handler { error }) => crate::i18n::fmt(&crate::i18n::msg(Failure::HANDLER), &[("event", notice.event), ("error", error)]), + Some(Failure::EventsOff { count }) => { + let template = if *count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER }; + crate::i18n::fmt(&crate::i18n::msg(template), &[("n", &count.to_string())]) + } + None => notice.text.clone(), + }; + return format!("{}: {text}", notice.name); + } let is = |before: &str, kept: &str, after: &str| status.strip_prefix(before).and_then(|rest| rest.strip_suffix(after)) == Some(kept); if let Some((before, kept, after)) = app.session.script_authored_failure() && is(&before, kept, &after) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 67cc29b63f..440f0f412a 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -597,7 +597,7 @@ fn the_status_bar_stands_still_while_its_readouts_change() { ] { let (x_value, y_value) = { let mut app = bar.app(); - app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps }; + app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps, ..Default::default() }; app.hover_doc = Some(vectorcraft_geom::Point::new(x, y)); (app.session.general_unit().readout(x), app.session.general_unit().readout(y)) }; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index eeef403f06..990d245bc3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -747,6 +747,9 @@ pub struct UiState { /// as they are ([`crate::plugin_runs::show_notice`]). Not saved. #[serde(skip)] pub status_kept: Option<(String, String, String)>, + /// The status and structured plug-in event failure translated when shown. Not saved. + #[serde(skip)] + pub status_plugin_event: Option<(String, vectorcraft_engine::plugin_events::Notice)>, pub palette_open: bool, pub palette_query: String, /// Set when the palette's shortcut, its command or the search icon opens or closes the palette, @@ -1530,6 +1533,7 @@ impl Default for UiState { status_notes: None, startup_notes: Vec::new(), status_kept: None, + status_plugin_event: None, palette_open: false, palette_query: String::new(), palette_toggled: false, diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index d6d9a48508..2b977059e8 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -1083,7 +1083,10 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { // The window lays itself out in the first two passes. pass(&mut app, false); pass(&mut app, false); + let _ = VectorcraftApp::take_event_notices_taken(); pass(&mut app, true); + let ran = VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id && n.event == "selection.changed").count(); + assert_eq!(ran, 1, "the handler ran in the pass that made the change"); app.session.deliver_plugin_events(); let left: Vec = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); assert!(left.is_empty(), "delivered in the pass that made the change, not later: {left:?}"); @@ -1114,10 +1117,13 @@ fn a_selection_a_window_key_changes_is_delivered_in_that_pass() { super::synthetic::key_frame(&mut app, &ctx, vec![]); app.session.deliver_plugin_events(); let _ = app.session.take_plugin_event_notices(); + let _ = VectorcraftApp::take_event_notices_taken(); let before = app.session.doc().unwrap().selection.objects.clone(); let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; super::synthetic::key_frame(&mut app, &ctx, vec![esc]); assert_ne!(app.session.doc().unwrap().selection.objects, before, "Escape left isolation and restored the selection"); + let ran = VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id && n.event == "selection.changed").count(); + assert_eq!(ran, 1, "the handler ran in the pass of the key"); app.session.deliver_plugin_events(); let left: Vec = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); assert!(left.is_empty(), "delivered in the pass of the key, not later: {left:?}"); diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 997d1c5456..8352dc26e4 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -343,11 +343,13 @@ fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { let _remove = Remove(id); let grant = json!(["progress", "events"]); let manifest = format!(r#"{{"id":"{id}","name":"Run Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); - // The handler writes the event it is given as a warning, which the status bar shows. - let warn = "(drop (call $vc_log (i32.const 1) (local.get $ep) (local.get $el))) (i32.const 0)"; - let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, warn)).unwrap(); + // The handler writes the event as an information line, which the status bar does not show, so + // the plug-in leaves the status bar of other tests' sessions alone; this thread's app keeps + // what it took ([`VectorcraftApp::take_event_notices_taken`]). + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); app.poll_finished_work(); + let _ = crate::VectorcraftApp::take_event_notices_taken(); let source = format!("{DRAW} vc.run('select.all', {{}});"); menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); let ctx = egui::Context::default(); @@ -359,8 +361,9 @@ fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { out.textures_delta.clear(); } assert!(!app.session.script_running(), "the script did not end"); - assert!(app.ui.status.starts_with("Run Events: "), "{}", app.ui.status); - assert!(app.ui.status.contains("selection.changed"), "{}", app.ui.status); + let ran: Vec = crate::VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); + assert_eq!(ran.len(), 1, "{ran:?}"); + assert!(ran[0].contains("selection.changed"), "{ran:?}"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 93fdc02aad..8fc3bff795 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15258,7 +15258,8 @@ An open drag, including one temporarily set aside by a command, holds events unt opened in a batch are compared with their state when added, and background plug-in loads record the event baseline when they install, or after the drag ends if one is open. Each UI frame calls at most four event handlers across background delivery and all UI passes; runnable recipients still queued request another frame, even without notices. -The handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). A live-effect plug-in is an effect with +The handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). +Both reset when a module is installed under the plug-in's id again, including the same module. A live-effect plug-in is an effect with id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them diff --git a/docs/plugins.md b/docs/plugins.md index cbcdc68d8c..81f877afe0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -899,7 +899,7 @@ or the document's contents. These limits are VectorCraft's own values. A handler that returns anything but `0`, traps or runs out of budget leaves the change it was told of as it is. Every failure goes to the log, and the first failure in a row also shows in the status bar; after 3 failures in a row, the plug-in gets no more events until VectorCraft - starts again or another module is installed with its id. A warning or error line a handler writes with `vc_log` + starts again or a module is installed with its id again, the same module included. A warning or error line a handler writes with `vc_log` shows in the status bar after the plug-in's name. `plugin.info` gives `eventsOff` and `lastEventError`. - In Safe Mode no handler runs. When no installed plug-in names an event, VectorCraft does not compare anything. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ad1689b555..1122b7ed94 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2843,7 +2843,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. -- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two checks are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. The desktop app checks after background work and at the end of each UI pass; `vectorcraft-cli` and headless MCP check after each top-level command. Each UI frame runs at most four handlers across background delivery and all UI passes, and requests another frame while runnable handlers remain queued, even without notices. An open drag holds events until it ends. A plug-in loaded during a drag records its baseline after commit or cancel, before the next edit, without recording temporary previews. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two checks are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. At most 32 events wait for delivery; past that the oldest waiting event is dropped. The desktop app checks after background work and at the end of each UI pass; `vectorcraft-cli` and headless MCP check after each top-level command. Each UI frame runs at most four handlers across background delivery and all UI passes, and requests another frame while runnable handlers remain queued, even without notices. An open drag holds events until it ends. A plug-in loaded during a drag records its baseline after commit or cancel, before the next edit, without recording temporary previews. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session or until the plug-in is installed again, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. From fadba64cb53e6448f9302cb7e88911ebe9749ffa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:03:30 -0800 Subject: [PATCH 22/60] CI: adding the full-ci label starts a full run The workflow now listens for the labeled pull request event, so adding the full-ci label runs all six shards. Any other label is skipped and gets a concurrency group of its own, so it does not cancel a running check. --- .github/workflows/ci.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2757e10bdb..d7f5b4e77b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,19 +9,23 @@ on: branches: [main] schedule: - cron: "37 3 * * *" + # `labeled` so adding the `full-ci` label starts a run of all six shards. pull_request: + types: [opened, synchronize, reopened, labeled] workflow_dispatch: permissions: contents: read -# A newer push to a PR branch cancels its older run; every push to main runs to the end. +# A newer push to a PR branch cancels its older run; every push to main runs to the end. Adding +# any label other than `full-ci` gets a group of its own, so it never cancels a real run. concurrency: - group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + group: ci-${{ github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: gate: + if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: From 0bdbb241520d83839cbfb97fe3961d835b29a314 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:46:07 -0800 Subject: [PATCH 23/60] CI: run vectorcraft-engine's integration tests on shard 4 In each of the last 20 successful pull request runs the slowest shard was a ui-egui part or shard 3 (8 of the 20), which built and ran every vectorcraft-engine test, while shard 4 finished in about half the time. Shard 4 already builds the engine library for the app crates, so it now runs the engine's 936 integration tests (`--test '*'`), and shard 3 keeps the 9,471 library tests and the doctests. `Group::Targets` gives a shard a list of crates per test-target selection, and each list is its own cargo command, with its feature check and its `ci warm` build. A crate either runs every target on one shard, or its library and binary tests on one shard and its integration tests on another. shard-members in ci.yml is unchanged: shard 4 runs whenever the engine is selected, because the app crates on its line depend on it, and a test checks that dependency. --- xtask/src/main.rs | 114 ++++++++++--------- xtask/src/shards.rs | 266 +++++++++++++++++++++++++++++++++++++------- 2 files changed, 285 insertions(+), 95 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 1c9af7db00..3ada901300 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -271,23 +271,21 @@ fn has_nextest() -> bool { /// The workspace's unit and integration tests, without examples (clippy still checks those). /// nextest runs each test in its own process, in parallel across all test binaries. fn cmd_test() -> Result<(), String> { - test_packages(&["--workspace".to_owned()], "--workspace", None) + test_packages(&["--workspace".to_owned()], "--workspace", shards::Targets::All, None) } -/// The test targets that [`test_packages`] runs and `ci warm` builds. -const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; - -/// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`; -/// with `part`, only that part's share of their tests (xtask/src/shards.rs), which needs nextest. -/// A part runs its counted share, then its pinned tests, each with nextest's default thread count. -/// Every run finishes before the first error is returned. -fn test_packages(select: &[String], shown: &str, part: Option) -> Result<(), String> { +/// [`cmd_test`] for the `targets` of the packages `select` picks (`--workspace` or `-p` ids), +/// shown as `shown`; with `part`, only that part's share of their tests (xtask/src/shards.rs), +/// which needs nextest. A part runs its counted share, then its pinned tests, each with +/// nextest's default thread count. Every run finishes before the first error is returned. +fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option) -> Result<(), String> { + let (listed, targets) = (targets.shown(), targets.args()); if let Some(part) = part { if !has_nextest() { return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest")); } let mut c = cargo(); - c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(TARGETS); + c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(targets); let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?; if !out.status.success() { return Err(format!("cargo nextest list {shown}: exited with {}", out.status)); @@ -301,9 +299,9 @@ fn test_packages(select: &[String], shown: &str, part: Option) -> } let command = |args: Vec| { let mut c = cargo(); - c.args(["nextest", "run"]).args(select).args(TARGETS).args(&args); + c.args(["nextest", "run"]).args(select).args(targets).args(&args); let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::>().join(" "); - (c, format!("cargo nextest run {shown} --lib --bins --tests {quoted}")) + (c, format!("cargo nextest run {shown} {listed} {quoted}")) }; let mut result = Ok(()); for args in part.runs() { @@ -314,12 +312,12 @@ fn test_packages(select: &[String], shown: &str, part: Option) -> } let mut c = cargo(); if has_nextest() { - c.args(["nextest", "run"]).args(select).args(TARGETS); - run(c, &format!("cargo nextest run {shown} --lib --bins --tests")) + c.args(["nextest", "run"]).args(select).args(targets); + run(c, &format!("cargo nextest run {shown} {listed}")) } else { eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)"); - c.arg("test").args(select).args(TARGETS); - run(c, &format!("cargo test {shown} --lib --bins --tests")) + c.arg("test").args(select).args(targets); + run(c, &format!("cargo test {shown} {listed}")) } } @@ -375,22 +373,33 @@ fn cmd_ci_shard() -> Result<(), String> { let checked = shards::run()?; let mut steps: Vec = Vec::new(); match &checked[shard - 1] { - shards::Shard::Tests(crates, part) => { - let names = shards::names(crates); + shards::Shard::Tests(runs, part) => { let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default(); - eprintln!("ci shard {shard}/{count}: the tests of {names}{share}"); - let select = shards::select(crates); - let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); + eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(runs)); + let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); let part = *part; - let (s, w) = (select.clone(), shown.clone()); - steps.push(("test", Box::new(move || test_packages(&s, &w, part)))); + let tests: Vec<(Vec, String, shards::Targets)> = + runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect(); + // Each run finishes before the first error is returned. + steps.push(( + "test", + Box::new(move || { + let mut result = Ok(()); + for (s, w, t) in &tests { + result = result.and(test_packages(s, w, *t, part)); + } + result + }), + )); // The doctests and the i18n report run once, on a split's first part. let first = part.is_none_or(|p| p.is_first()); if first { - let c = crates.clone(); + let c = shards::unit_crates(runs); steps.push(("doctests", Box::new(move || doctest_packages(&c)))); } - if first && crates.iter().any(|m| m.name == "vectorcraft-ui-egui") { + let all = runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")); + if let Some(r) = all.filter(|_| first) { + let (select, shown) = (shards::select(&r.crates), shown(&r.crates)); steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown)))); } } @@ -402,13 +411,11 @@ fn cmd_ci_shard() -> Result<(), String> { run_steps(&steps) } -/// `cargo xtask ci warm`: for each test shard, builds its crates' library, binary and integration -/// tests without running them, then builds what the checks shard builds, so one dependency-cache -/// entry holds the dependencies of every shard with the features that shard builds them with (cargo -/// resolves features over the packages each command selects). The test builds select the same -/// targets as the test shards ([`TARGETS`]), so the cache also holds the test executables the -/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that -/// only an integration test uses. +/// `cargo xtask ci warm`: for each run of each test shard, builds the test targets it runs without +/// running them, then builds what the checks shard builds, so one dependency-cache entry holds the +/// dependencies of every shard with the features that shard builds them with (cargo resolves +/// features over the packages each command selects). The test builds select the same crates and +/// targets as the test shards' runs, so the cache also holds the test executables the shards run. /// /// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` /// (xtask/src/cache_units.rs), xtask's own build included. @@ -418,17 +425,19 @@ fn cmd_ci_warm() -> Result<(), String> { let mut steps: Vec = Vec::new(); for shard in checked { // A split's later parts build the same tests as its first. - if let shards::Shard::Tests(crates, part) = shard { + if let shards::Shard::Tests(runs, part) = shard { if part.is_some_and(|p| !p.is_first()) { continue; } - steps.push(( - "build tests", - Box::new(move || { - let (c, what) = warm_tests(&crates); - cache_units::run(c, &what) - }), - )); + for r in runs { + steps.push(( + "build tests", + Box::new(move || { + let (c, what) = warm_tests(&r); + cache_units::run(c, &what) + }), + )); + } } } steps.push(( @@ -457,11 +466,11 @@ fn cmd_ci_warm() -> Result<(), String> { run_steps(&steps) } -/// The command `ci warm` builds one test shard's tests with, and its description. -fn warm_tests(crates: &[shards::Member]) -> (Command, String) { +/// The command `ci warm` builds the tests of one run of a test shard with, and its description. +fn warm_tests(r: &shards::Run) -> (Command, String) { let mut c = cargo(); - c.arg("test").args(shards::select(crates)).args(TARGETS).arg("--no-run"); - (c, format!("cargo test {} --no-run ({})", TARGETS.join(" "), shards::names(crates))) + c.arg("test").args(shards::select(&r.crates)).args(r.targets.args()).arg("--no-run"); + (c, format!("cargo test {} --no-run ({})", r.targets.shown(), shards::names(&r.crates))) } /// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed @@ -613,13 +622,14 @@ mod tests { #[test] fn warm_builds_the_test_targets_the_shards_run() { - let crates = [shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }]; - let (c, what) = warm_tests(&crates); - let args: Vec = c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); - assert_eq!(args, ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); - for target in TARGETS { - assert!(args.iter().any(|a| a == target), "ci warm does not build {target}"); - } - assert_eq!(what, "cargo test --lib --bins --tests --no-run (a)"); + let a = shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }; + let args = |r: &shards::Run| warm_tests(r).0.get_args().map(|a| a.to_string_lossy().into_owned()).collect::>(); + let all = shards::Run::all(vec![a.clone()]); + assert_eq!(args(&all), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); + assert_eq!(warm_tests(&all).1, "cargo test --lib --bins --tests --no-run (a)"); + let units = shards::Run { targets: shards::Targets::Units, crates: vec![a.clone()] }; + assert_eq!(args(&units), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--no-run"]); + let integration = shards::Run { targets: shards::Targets::Integration, crates: vec![a] }; + assert_eq!(args(&integration), ["test", "-p", "path+file:///w/a#0.1.0", "--test", "*", "--no-run"]); } } diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 261a27191e..072e55f280 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -17,6 +17,11 @@ //! with the pinned tests filtered out, so each of them runs once). The doctests and the i18n //! report run on part 1. A part runs its counted share and then its pinned tests, each with //! nextest's default thread count, and runs both even when the first fails. +//! +//! A [`Group::Targets`] shard can run a crate's library and binary tests ([`Targets::Units`]) while +//! another shard runs its integration tests ([`Targets::Integration`]), so a shard that already +//! builds that crate's library takes those tests without building the library's test harness. Each +//! list of a shard is its own cargo command, and its doctests run with its library tests. use std::collections::{BTreeMap, BTreeSet}; @@ -25,16 +30,49 @@ use serde_json::Value; /// What one shard runs. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Group { - /// The tests of these workspace crates (package names). - Crates(&'static [&'static str]), /// Part `k` (1-based) of a split's tests. Parts 1 to n of a split are consecutive shards. Part(&'static Split, usize), + /// The given test targets of each list of workspace crates (package names). A crate whose + /// [`Targets::Units`] run on one shard has its [`Targets::Integration`] run on another. + Targets(&'static [(Targets, &'static [&'static str])]), /// The tests of every workspace member no other group names. Rest, /// The `cargo xtask ci` steps that are not tests. Checks, } +/// The test targets a shard builds and runs for a crate. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Targets { + /// The library, binary and integration tests. + All, + /// The library and binary tests. + Units, + /// The integration tests (`tests/`). + Integration, +} + +impl Targets { + /// The target selection `cargo test` and `cargo nextest run` take. + pub fn args(self) -> &'static [&'static str] { + match self { + Targets::All => &["--lib", "--bins", "--tests"], + Targets::Units => &["--lib", "--bins"], + // `--tests` would also take the library's and binaries' test harnesses (every target with `test = true`). + Targets::Integration => &["--test", "*"], + } + } + + /// [`Targets::args`] as a shell would take them, for messages. + pub fn shown(self) -> &'static str { + match self { + Targets::All => "--lib --bins --tests", + Targets::Units => "--lib --bins", + Targets::Integration => "--test '*'", + } + } +} + /// Crates whose tests run on several shards, one [`Group::Part`] each. #[derive(Debug, PartialEq, Eq)] pub struct Split { @@ -71,12 +109,16 @@ pub static UI_EGUI: Split = Split { }; /// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its -/// `shard-members` names each shard's crates. +/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on +/// shard 4, which already builds the engine library for the app crates. pub const GROUPS: &[Group] = &[ Group::Part(&UI_EGUI, 1), Group::Part(&UI_EGUI, 2), - Group::Crates(&["vectorcraft-engine"]), - Group::Crates(&["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), + Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]), + Group::Targets(&[ + (Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), + (Targets::Integration, &["vectorcraft-engine"]), + ]), Group::Rest, Group::Checks, ]; @@ -98,10 +140,29 @@ pub struct Member { /// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Shard { - Tests(Vec, Option), + Tests(Vec, Option), Checks, } +/// One test run of a shard: the given targets of these crates. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Run { + pub targets: Targets, + pub crates: Vec, +} + +impl Run { + /// A run of every test target of `crates`. + pub fn all(crates: Vec) -> Run { + Run { targets: Targets::All, crates } + } +} + +/// The crates of `runs` whose library is tested there, which run their doctests on that shard. +pub fn unit_crates(runs: &[Run]) -> Vec { + runs.iter().filter(|r| r.targets != Targets::Integration).flat_map(|r| r.crates.iter().cloned()).collect() +} + /// Part `index` (1-based) of `split`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Part { @@ -192,14 +253,15 @@ pub fn with_doctests(crates: &[Member]) -> Vec { } /// Each group of `groups` with its crates: a named crate must be a workspace member and named -/// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's -/// parts 1 to n must be consecutive shards, with at least two parts, and no test pinned twice. +/// once, or with its [`Targets::Units`] on one shard and its [`Targets::Integration`] on another; +/// there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's parts 1 +/// to n must be consecutive shards, with at least two parts, and no test pinned twice. pub fn assign(groups: &[Group], members: &[Member]) -> Result, String> { const WHERE: &str = "xtask/src/shards.rs › GROUPS"; - let mut named: BTreeMap<&str, usize> = BTreeMap::new(); + let mut named: BTreeMap<&str, Vec<(usize, Targets)>> = BTreeMap::new(); for (i, g) in groups.iter().enumerate() { - let names = match g { - Group::Crates(names) => *names, + let lists: Vec<(Targets, &[&str])> = match g { + Group::Targets(lists) => lists.to_vec(), Group::Part(split, k) => { let n = split.parts(); if n < 2 { @@ -222,22 +284,39 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result, String return Err(format!("`{name}` is pinned to two parts of shard {}'s split ({WHERE})", i + 1)); } } - split.crates + vec![(Targets::All, split.crates)] } Group::Rest | Group::Checks => continue, }; - if names.is_empty() { + if lists.iter().all(|(_, names)| names.is_empty()) { return Err(format!("shard {} names no crates ({WHERE})", i + 1)); } - for name in names { - if !members.iter().any(|m| m.name == *name) { - return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); - } - if let Some(first) = named.insert(name, i) { - return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)); + for (targets, names) in lists { + for name in names { + if !members.iter().any(|m| m.name == *name) { + return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); + } + let entries = named.entry(name).or_default(); + // The one allowed second entry: the other half of a crate split into units and integration tests. + let halves = + |a: Targets, b: Targets| matches!((a, b), (Targets::Units, Targets::Integration) | (Targets::Integration, Targets::Units)); + match entries.as_slice() { + [] => {} + [(first, t)] if halves(*t, targets) && *first != i => {} + [(first, _), ..] => return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)), + } + entries.push((i, targets)); } } } + for (name, entries) in &named { + if let [(i, t)] = entries.as_slice() + && *t != Targets::All + { + let other = if *t == Targets::Units { "integration" } else { "library and binary" }; + return Err(format!("shard {} runs part of `{name}`'s tests, and no shard runs its {other} tests ({WHERE})", i + 1)); + } + } let rests = groups.iter().filter(|g| **g == Group::Rest).count(); if rests != 1 { return Err(format!("{rests} shards take the remaining crates, not 1 ({WHERE})")); @@ -247,14 +326,23 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result, String .iter() .enumerate() .map(|(i, g)| match g { - Group::Crates(names) => Ok(Shard::Tests(pick(&|m| names.contains(&m.name.as_str())), None)), - Group::Part(split, index) => Ok(Shard::Tests(pick(&|m| split.crates.contains(&m.name.as_str())), Some(Part { split, index: *index }))), + Group::Targets(lists) => Ok(Shard::Tests( + lists + .iter() + .filter(|(_, names)| !names.is_empty()) + .map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) }) + .collect(), + None, + )), + Group::Part(split, index) => { + Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index }))) + } Group::Rest => { let rest = pick(&|m| !named.contains_key(m.name.as_str())); if rest.is_empty() { return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1)); } - Ok(Shard::Tests(rest, None)) + Ok(Shard::Tests(vec![Run::all(rest)], None)) } Group::Checks => Ok(Shard::Checks), }) @@ -325,6 +413,17 @@ pub fn names(crates: &[Member]) -> String { crates.iter().map(|m| m.name.as_str()).collect::>().join(", ") } +/// The crates of `runs` for messages, each run's targets after its crates unless it runs all of them. +pub fn describe(runs: &[Run]) -> String { + runs.iter() + .map(|r| match r.targets { + Targets::All => names(&r.crates), + t => format!("{} ({})", names(&r.crates), t.shown()), + }) + .collect::>() + .join(", ") +} + /// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`]. pub fn check() -> Result, String> { let members = members(&crate::metadata()?)?; @@ -332,9 +431,12 @@ pub fn check() -> Result, String> { let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members); let mut differences = Vec::new(); for (i, shard) in shards.iter().enumerate() { - if let Shard::Tests(crates, _) = shard { - let alone = tree_features(&tree(&select(crates))?, &members); - differences.extend(feature_differences(i + 1, crates, &workspace, &alone)); + // Each run is its own cargo command, so cargo resolves features over that run's crates. + if let Shard::Tests(runs, _) = shard { + for r in runs { + let alone = tree_features(&tree(&select(&r.crates))?, &members); + differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone)); + } } } if !differences.is_empty() { @@ -354,9 +456,9 @@ pub fn run() -> Result, String> { let shards = check()?; for (i, shard) in shards.iter().enumerate() { match shard { - Shard::Tests(crates, part) => { + Shard::Tests(runs, part) => { let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default(); - println!("shard {}/{}: tests of {} crate(s): {}{share}", i + 1, shards.len(), crates.len(), names(crates)) + println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs)) } Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()), } @@ -392,17 +494,18 @@ mod tests { fn crates(shard: &Shard) -> Vec<&str> { match shard { - Shard::Tests(c, _) => c.iter().map(|m| m.name.as_str()).collect(), + Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(), Shard::Checks => Vec::new(), } } - /// The crates of each shard that runs a crate's tests from the start: a part after the first + /// Each crate a shard tests from the start, with the targets it runs: a part after the first /// runs a share of the same tests, so it is counted with part 1. - fn owners(shard: &Shard) -> Vec<&str> { + fn owners(shard: &Shard) -> Vec<(&str, Targets)> { match shard { Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(), - _ => crates(shard), + Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(), + Shard::Checks => Vec::new(), } } @@ -451,12 +554,12 @@ mod tests { let ws = [m("a"), m("b")]; let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); assert_eq!(shards.iter().map(crates).collect::>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]); - assert_eq!(shards[1], Shard::Tests(vec![m("a")], Some(Part { split: &SPLIT, index: 2 }))); + assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 }))); let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err(); assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}"); let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err(); assert!(missing.contains("shard 1 is part 2"), "{missing}"); - let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err(); + let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), ALL_A, Group::Rest], &ws).unwrap_err(); assert!(twice.contains("`a` is in shard 1 and shard 3"), "{twice}"); const ONE: Split = Split { crates: &["a"], pinned: &[&[]] }; assert!(assign(&[Group::Part(&ONE, 1), Group::Rest], &ws).unwrap_err().contains("not 2 or more")); @@ -519,26 +622,61 @@ mod tests { #[test] fn the_rest_shard_takes_every_crate_no_group_names() { let ws = [m("a"), m("b"), m("c"), m("d")]; - let shards = assign(&[Group::Crates(&["c"]), Group::Rest, Group::Checks], &ws).unwrap(); + let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap(); assert_eq!(shards.iter().map(crates).collect::>(), [vec!["c"], vec!["a", "b", "d"], vec![]]); assert_eq!(shards[2], Shard::Checks); } + /// Every test target of `a`. + const ALL_A: Group = Group::Targets(&[(Targets::All, &["a"])]); + const UNITS: (Targets, &[&str]) = (Targets::Units, &["a"]); + const INTEGRATION: (Targets, &[&str]) = (Targets::Integration, &["a"]); + + #[test] + fn a_crate_s_units_and_integration_tests_run_on_two_shards() { + let ws = [m("a"), m("b"), m("c")]; + let shards = + assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap(); + assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None)); + assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None)); + assert_eq!(crates(&shards[2]), ["c"]); + assert_eq!( + unit_crates(match &shards[1] { + Shard::Tests(r, _) => r, + Shard::Checks => panic!("shard 2 is a test shard"), + }), + [m("b")] + ); + let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err(); + assert!(half.contains("no shard runs its integration tests"), "{half}"); + let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(other_half.contains("no shard runs its library and binary tests"), "{other_half}"); + let with_all = assign(&[ALL_A, Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(with_all.contains("`a` is in shard 1 and shard 2"), "{with_all}"); + let same_shard = assign(&[Group::Targets(&[UNITS, INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(same_shard.contains("`a` is in shard 1 and shard 1"), "{same_shard}"); + let units_twice = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err(); + assert!(units_twice.contains("`a` is in shard 1 and shard 2"), "{units_twice}"); + let third = + assign(&[Group::Targets(&[UNITS]), Group::Targets(&[INTEGRATION]), Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(third.contains("`a` is in shard 1 and shard 3"), "{third}"); + } + #[test] fn a_crate_named_twice_or_unknown_fails() { let ws = [m("a"), m("b")]; - let twice = assign(&[Group::Crates(&["a"]), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err(); + let twice = assign(&[ALL_A, ALL_A, Group::Rest], &ws).unwrap_err(); assert!(twice.contains("`a` is in shard 1 and shard 2"), "{twice}"); - let unknown = assign(&[Group::Crates(&["z"]), Group::Rest], &ws).unwrap_err(); + let unknown = assign(&[Group::Targets(&[(Targets::All, &["z"])]), Group::Rest], &ws).unwrap_err(); assert!(unknown.contains("`z`, which is not a workspace member"), "{unknown}"); } #[test] fn empty_groups_and_a_missing_or_second_rest_fail() { let ws = [m("a"), m("b")]; - assert!(assign(&[Group::Crates(&[]), Group::Rest], &ws).unwrap_err().contains("names no crates")); - assert!(assign(&[Group::Crates(&["a", "b"]), Group::Rest], &ws).unwrap_err().contains("there are none")); - assert!(assign(&[Group::Crates(&["a"])], &ws).unwrap_err().contains("0 shards take the remaining crates")); + assert!(assign(&[Group::Targets(&[(Targets::All, &[])]), Group::Rest], &ws).unwrap_err().contains("names no crates")); + assert!(assign(&[Group::Targets(&[(Targets::All, &["a", "b"])]), Group::Rest], &ws).unwrap_err().contains("there are none")); + assert!(assign(&[ALL_A], &ws).unwrap_err().contains("0 shards take the remaining crates")); assert!(assign(&[Group::Rest, Group::Rest], &ws).unwrap_err().contains("2 shards take the remaining crates")); } @@ -546,11 +684,22 @@ mod tests { fn every_workspace_member_is_tested_on_exactly_one_shard() { let ws = members(&crate::metadata().unwrap()).unwrap(); let shards = assign(GROUPS, &ws).unwrap(); - let mut tested: Vec<&str> = shards.iter().flat_map(owners).collect(); - tested.sort_unstable(); + let mut tested: BTreeMap<&str, Vec> = BTreeMap::new(); + for (name, targets) in shards.iter().flat_map(owners) { + tested.entry(name).or_default().push(targets); + } + for targets in tested.values_mut() { + targets.sort_unstable(); + } let mut all: Vec<&str> = ws.iter().map(|m| m.name.as_str()).collect(); all.sort_unstable(); - assert_eq!(tested, all); + assert_eq!(tested.keys().copied().collect::>(), all); + for (name, targets) in &tested { + assert!( + *targets == [Targets::All] || *targets == [Targets::Units, Targets::Integration], + "`{name}` runs {targets:?}, not each test target once" + ); + } assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1); } @@ -602,13 +751,44 @@ geom v0.1.0 (/w/geom)| let expected: Vec = GROUPS .iter() .map(|g| match g { - Group::Crates(crates) => crates.join(" "), Group::Part(split, _) => split.crates.join(" "), + // The selection names each crate on one line only, so a shard that runs a crate's + // integration tests leaves it off its line and relies on a crate there that + // depends on it (checked below). + Group::Targets(lists) => { + lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::>().join(" ") + } Group::Rest => "(rest)".to_owned(), Group::Checks => "(always)".to_owned(), }) .collect(); assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml"); + let meta = crate::metadata().unwrap(); + let deps: BTreeMap<&str, Vec<&str>> = meta["packages"] + .as_array() + .unwrap() + .iter() + .map(|p| (p["name"].as_str().unwrap(), p["dependencies"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect())) + .collect(); + let reaches = |from: &str, to: &str| { + let (mut seen, mut stack) = (BTreeSet::new(), vec![from]); + while let Some(c) = stack.pop() { + if c == to { + return true; + } + if seen.insert(c) { + stack.extend(deps.get(c).into_iter().flatten().copied()); + } + } + false + }; + for g in GROUPS { + let Group::Targets(lists) = g else { continue }; + let named: Vec<&str> = lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect(); + for crate_ in lists.iter().filter(|(t, _)| *t == Targets::Integration).flat_map(|(_, c)| c.iter().copied()) { + assert!(named.iter().any(|n| reaches(n, crate_)), "no crate on the shard of `{crate_}`'s integration tests depends on it"); + } + } assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]); assert!(shard_members("test-shards: 6\n").is_empty()); } From 3e6a21b93b3c5f71e8f72fec44fd82e4cb3965cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:01:48 -0800 Subject: [PATCH 24/60] xtask: test-lint leaves out census loops that run each entry through a computation A loop over a whole table whose body passes the entry to a call together with other state (a command run, a file written, a render, a parse of other input) checks behavior for each entry, so the census rule no longer reports it. A lookup, a call on the entry alone, literal arguments and calls in a failure message still count as a census. The census count from test-lint --all drops from 42 to 37: the cutting add-on dialog table, the quick pen toolbar clicks, the white spot ink overprint output, the plug-in proposal loads and the unit parse property test are no longer reported. --- xtask/src/test_lint.rs | 144 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 142 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..b1fc00dc12 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -45,7 +45,9 @@ //! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of //! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`, //! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or -//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. A loop that +//! passes the entry to a call together with other state (a command run, a file written, a +//! render) is a table of behavior cases and is not reported; //! * `mirror`: `assert_eq!(f(a), f(b) …)`, where the expected side derives its value from a //! second call of the same function (same path) with arithmetic, so a fault in `f` moves both //! sides; builders and conversions (`new`, `from`, `to_string` …) are left out; @@ -1447,7 +1449,10 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let Some(close) = matching(m, open) else { continue }; let pattern = String::from_utf8_lossy(&m[at + 3..kw]); let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&'); - if whole_table(&norm(&m[kw + 2..open])) && weak_in(open, close, var) { + if whole_table(&norm(&m[kw + 2..open])) + && weak_in(open, close, var) + && !feeds_entry(&unmessaged, &pattern, open + 1 - v.t.open, close - v.t.open) + { return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; } } @@ -1460,6 +1465,113 @@ fn census(v: &View, helpers: &HashSet) -> Vec { vec![] } +/// Calls that read or look up a value rather than compute one, so passing the entry to one of them +/// together with other state does not make the loop a behavior table. +const LOOKUPS: &[&str] = &[ + "contains", + "contains_key", + "starts_with", + "ends_with", + "get", + "get_mut", + "iter", + "into_iter", + "any", + "find", + "position", + "binary_search", + "eq", + "ne", + "find_map", +]; + +/// The lowercase names a `for` or `let` pattern binds. +fn pattern_names(pattern: &str) -> impl Iterator + '_ { + pattern + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) + .map(str::to_owned) +} + +/// Whether the body `b[from..to]` of a loop whose pattern is `pattern` feeds the entry into a +/// computation with other inputs: a call (not one of [`LOOKUPS`], nor a macro) whose receiver and +/// arguments include a value read from the entry and another value that is not a literal, such as +/// `app.run("…", json!({"id": id}))`, `export(&doc, &Options { level, .. })` or `check(SCHEMA, ¶ms)` +/// with `params` bound from the entry inside the loop. Such a loop runs, renders or writes something +/// for each entry, so it is a table of behavior cases. A call that takes the entry alone (`menu(c)`, +/// `Kind::from_id(k.id())`) is still a lookup. +fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { + let mut derived: Vec = pattern_names(pattern).collect(); + let reads = |s: &[u8], names: &[String]| { + let s = String::from_utf8_lossy(s); + names.iter().any(|n| reads_ident(&s, n)) + }; + // Names bound inside the loop from the entry count as the entry. + for at in words(b, b"let", from, to) { + let Some(eq) = + (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + else { + continue; + }; + let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); + if reads(&b[eq + 1..end], &derived) { + let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + derived.extend(names); + } + } + let literal = |s: &[u8]| { + let s = norm(s); + let s = s.trim_start_matches(['&', '*']); + // String, byte and raw literals keep their prefix after masking (`r"…"`, `b'…'`, `br#"…"#`). + let s = match s.find(['"', '\'']) { + Some(q) if q <= 3 && s[..q].bytes().all(|c| matches!(c, b'b' | b'c' | b'r' | b'#')) => &s[q..], + _ => s, + }; + // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. + s.is_empty() + || s.starts_with(['"', '\'', '-', '|']) + || s.starts_with("move|") + || s.starts_with(|c: char| c.is_ascii_digit()) + || matches!(s, "true" | "false" | "None") + }; + (from..to).filter(|&i| b[i] == b'(' && i > from && is_ident(b[i - 1])).any(|open| { + let mut start = open; + while start > from && is_ident(b[start - 1]) { + start -= 1; + } + let name = String::from_utf8_lossy(&b[start..open]); + if LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() { + return false; + } + let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; + let args = split_args(b, open + 1, close); + let mut inputs = args.clone(); + if start > from && b[start - 1] == b'.' { + // The receiver: the chain of names, calls and indexing before the dot. + let mut r = start - 1; + while r > from { + match b[r - 1] { + c if is_ident(c) || c == b'.' => r -= 1, + // A chain rustfmt splits over lines continues with a `.` after the line break. + c if c.is_ascii_whitespace() && b[r..start].iter().find(|c| !c.is_ascii_whitespace()) == Some(&b'.') => r -= 1, + b')' | b']' => match (from..r - 1).rev().find(|&o| matching(b, o) == Some(r - 1)) { + Some(o) => r = o, + None => break, + }, + _ => break, + } + } + inputs.push((r, start - 1)); + } + let fed = inputs.iter().any(|&(f, t)| reads(&b[f..t], &derived)); + // A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only + // another argument (`u.parse(&text)`) makes it a computation. + let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs }; + let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(&b[f..t], &derived)); + fed && other + }) +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -3783,6 +3895,34 @@ mod tests { assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip"); } + #[test] + fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let run = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app.session.execute(CMD, &json!({\"way\": k})).is_ok());\n }\n}\n"; + assert_eq!(census(run), [], "a command run for each entry"); + let split = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app\n .run(k)\n .is_ok());\n }\n}\n"; + assert_eq!(census(split), [], "a chain split over lines keeps its receiver"); + let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n"; + assert_eq!(census(rendered), [], "a file written for each entry"); + let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(check_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; + assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema"); + let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n"; + assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census"); + let alone = "#[test]\nfn t() {\n for c in COMMANDS {\n let m = menu(c);\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(alone), [(2, "census")], "a call on the entry alone is a lookup"); + let constant = + "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c, 2, \"x\", r\"y\", b'z', br#\"w\"#).is_some());\n }\n}\n"; + assert_eq!(census(constant), [(2, "census")], "literal arguments are not other inputs"); + let message = "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some(), \"{}\", app.describe(c));\n }\n}\n"; + assert_eq!(census(message), [(2, "census")], "a call in a failure message runs only after a failure"); + let closure = "#[test]\nfn t() {\n let tree = tree();\n for p in PLACES {\n let m = tree.iter().find(|t| t == p).map(|(_, items)| items.len());\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(closure), [(2, "census")], "a closure passed along a lookup is not another input"); + let registry = "#[test]\nfn t() {\n let registry = registry();\n for k in Kind::ALL {\n assert_eq!(registry.lookup(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip"); + let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n"; + assert_eq!(census(parsed), [], "parsing other input with each entry computes a result"); + } + #[test] fn census_loops_over_whole_tables_are_reported() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); From e0b51eb78235703e1c2940f2d2e5cdf6a88b516c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:33:34 -0800 Subject: [PATCH 25/60] xtask: census exemption does not count a call that an || can skip A call to the right of an || at its own nesting level may never run, so `menu(c).is_some() || app.run(c).is_ok()` is still reported as a census. The right side of &&, an || inside an earlier group or a sibling element, and the pipes of a zero-argument, move or async closure do not skip the call. --- xtask/src/test_lint.rs | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index b1fc00dc12..a9fd4b1be4 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1543,6 +1543,43 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { if LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() { return false; } + // A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`); the + // right side of `&&` has to run for an assertion to pass. + let stmt = (from..start).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(from, |i| i + 1); + // Only an `||` at the call's own nesting level or an enclosing one counts, not one inside + // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; + // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. + // Sibling elements and assignments also end the expression that can skip the call. + let mut depth = 0usize; + let mut after_or = false; + for i in (stmt + 1..start).rev() { + match b[i] { + b')' | b']' => depth += 1, + b'(' | b'[' => depth = depth.saturating_sub(1), + _ => {} + } + if depth == 0 + && (b[i] == b',' || (b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))) + { + break; + } + if depth == 0 && b[i] == b'|' && b[i - 1] == b'|' { + let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); + let prefix = &b[stmt..end]; + let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); + let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); + if !moved + && !asynchronous + && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + { + after_or = true; + break; + } + } + } + if after_or { + return false; + } let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; let args = split_args(b, open + 1, close); let mut inputs = args.clone(); @@ -3921,6 +3958,20 @@ mod tests { assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip"); let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n"; assert_eq!(census(parsed), [], "parsing other input with each entry computes a result"); + let skipped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() || app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(skipped), [(2, "census")], "a call after || may never run"); + let joined = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(joined), [], "a call after && runs whenever the assertion passes"); + let grouped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!((menu(c).is_some() || other(c).is_some()) && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(grouped), [], "an || inside an earlier group does not skip the call"); + let deferred = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(deferred), [], "a zero-argument closure feeds the entry into a computation"); + let moved = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = move || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(moved), [], "a move closure feeds the entry into a computation"); + let deferred_async = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = async || app.run(c);\n assert!(block_on(run()).is_ok());\n }\n}\n"; + assert_eq!(census(deferred_async), [], "an async closure feeds the entry into a computation"); + let sibling = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let result = (flag || other, app.run(c));\n assert!(result.1.is_ok());\n }\n}\n"; + assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } #[test] From 77e37176e2eb6bf844adf5e8da2e52cb31276e80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:40:34 -0800 Subject: [PATCH 26/60] xtask: test-lint no longer reports helper, diagnostic and fixed-size false alarms no-assertion: - A call in a top-level test reaches the helper its own file defines. A non-asserting helper of the same name in another file of the crate no longer hides it (several_handles.rs `near` beside affinity_features.rs). Names the file also calls with a path, and definitions below the file's top level, keep the crate's verdict. - An `#[ignore = "reason"]` test that prints is a diagnostic and needs no assertion. - An asserting function passed by name as a value (`keeping_color_settings(the_body)`) counts as the test's check, also through a helper that passes it, unless a local binding or parameter shadows the name. all-unguarded: - A parenthesized range of literals or constants, `(0..3).all(...)`. - A receiver whose source an earlier `assert_eq!` compares with a non-empty literal: a local collected from the receiver, or a call on the same local the receiver was made from, when nothing changes the source in between. - A call to a function of the file that lists a constant table and filters it only on parameters that are not references. On the whole tree, `cargo xtask test-lint --all` reports 96 no-assertion hits instead of 157 and 375 all-unguarded hits instead of 419. --- xtask/src/test_lint.rs | 528 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 505 insertions(+), 23 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..a7d06b4602 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -16,8 +16,12 @@ //! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, //! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later //! code may shrink or replace them; and fields the file declares only as arrays of a positive -//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change -//! anywhere in the test counts as a change to the hit; +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. Also +//! left out: a parenthesized range of literals or constants (`(0..3).all(…)`); a receiver whose +//! source an earlier equality assertion compares with a non-empty literal (a local bound from the +//! receiver, or a call on the same local as the receiver's binding); and a call to a function of +//! the file that lists a constant table and filters it only on parameters that are not +//! references. A change anywhere in the test counts as a change to the hit; //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that @@ -26,7 +30,9 @@ //! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no //! output, with a status check in any condition or compared operand of a standard assertion; //! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, -//! and no `#[should_panic]`; +//! and no `#[should_panic]`. An asserting helper passed by name as a value +//! (`keeping_settings(the_body)`) counts, and so does an `#[ignore = "…"]` test that prints. A +//! top-level test's call reaches the helper of its own file when the file defines one of that name; //! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value //! from the code under test. Left out: a return after an assertion in its block, one whose //! statement or line has a comment or a printed note saying why, and guards on files, fonts, @@ -1134,35 +1140,92 @@ fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { type Def = (String, bool, Vec); /// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test -/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. Each file of `files` +/// also gets an entry under its path ([`helpers_for`]): a call in a top-level test reaches the function of +/// that name the file defines only when all its definitions are at the file's top level and +/// the file does not call that name with a path. Other names keep the crate's verdict. pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { let mut defs: HashMap> = HashMap::new(); + // Each file's path, its definitions, and the names its own definitions decide. + let mut by_file: Vec<(&str, Vec, HashSet)> = vec![]; for (path, src) in files { let m = mask(src); let regions = test_regions(path, &m, &tests_in(&m)); - let crate_defs = defs.entry(crate_of(path)).or_default(); - for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { - if in_regions(®ions, at) { - crate_defs.extend(definition(&m, at)); - } - } + let depths = brace_depths(&m); + let mut nested = HashSet::new(); + let own: Vec = words(&m, b"fn", 0, m.len()) + .into_iter() + .chain(words(&m, b"macro_rules", 0, m.len())) + .filter(|&at| in_regions(®ions, at)) + .filter_map(|at| { + let def = definition(&m, at)?; + if depths[at] != 0 { + nested.insert(def.0.clone()); + } + Some(def) + }) + .collect(); + // A call with a path (`other::near(…)`) may reach another module's function, and calls + // keep only the last name, so a name the file also calls with a path keeps the crate's + // verdict. A definition below the file's top level also keeps the crate's verdict. + let names = own.iter().map(|d| d.0.clone()).filter(|n| !nested.contains(n) && !called_with_path(&m, n)).collect(); + defs.entry(crate_of(path)).or_default().extend(own.iter().cloned()); + by_file.push((path, own, names)); } let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); - defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() + let mut out: HashMap> = defs + .iter() + .map(|(krate, own)| (krate.clone(), checking(HashSet::new(), own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))) + .collect(); + for (path, own, names) in by_file { + if names.is_empty() { + continue; + } + let base = out.get(&crate_of(path)).map(|set| set.difference(&names).cloned().collect()).unwrap_or_default(); + out.insert(path.to_owned(), checking(base, own.iter().filter(|d| names.contains(&d.0)))); + } + out +} + +/// Whether the masked file names `name` (a function, or `name!` for a macro) after a `::` path. +fn called_with_path(m: &[u8], name: &str) -> bool { + let name = name.trim_end_matches('!'); + words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::")) +} + +/// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's +/// own entry of [`asserting_helpers`] if present; otherwise, its crate's. +fn helpers_for<'a>(ctx: &'a Ctx, path: &str, top_level: bool) -> Option<&'a HashSet> { + if top_level { ctx.helpers.get(path).or_else(|| ctx.helpers.get(&crate_of(path))) } else { ctx.helpers.get(&crate_of(path)) } +} + +/// The brace depth before each byte of masked text. +fn brace_depths(m: &[u8]) -> Vec { + let mut depth = 0usize; + m.iter() + .map(|&c| { + let before = depth; + match c { + b'{' => depth += 1, + b'}' => depth = depth.saturating_sub(1), + _ => {} + } + before + }) + .collect() } /// The crate whose test helpers every crate can call. const TESTKIT: &str = "crates/testkit"; -/// The names among `defs` that check something, directly or through another of `defs`. Calls do -/// not say which of several functions with one name they reach, so a name counts only when every -/// definition with that name checks. -fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { +/// `known` and the names among `defs` that check something, directly or through another of +/// `defs` or a name of `known`. Calls do not say which of several functions with one name they +/// reach, so a name counts only when every definition with that name checks. +fn checking<'a>(mut known: HashSet, defs: impl Iterator + Clone) -> HashSet { let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); for d in defs { by_name.entry(d.0.as_str()).or_default().push(d); } - let mut known: HashSet = HashSet::new(); loop { let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); let more: Vec = by_name @@ -1199,7 +1262,12 @@ fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { fn definition(m: &[u8], at: usize) -> Option { let (name, is_macro, open, close) = item_at(m, at)?; let name = String::from_utf8_lossy(name).into_owned(); - let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + let called = calls(m, open, close) + .into_iter() + .filter(|(_, method)| !method) + .map(|(n, _)| n) + .chain(passed_names(m, open, close).into_iter().filter(|name| !shadows_helper(m, at, open, close, name.as_bytes()))) + .collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1210,6 +1278,8 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// The brace depth before each byte of [`File::m`] ([`brace_depths`]). + depths: Vec, /// [`File::m`] with the functions and macros declared inside each test blanked: declaring /// one does not run its body ([`executed`]). exec: Vec, @@ -1252,10 +1322,11 @@ impl File<'_> { /// Every hit in one file, exemptions applied. pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); + let depths = brace_depths(&m); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); let exec = executed(&m, &tests); - let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; + let file = File { path, src: src.as_bytes(), m, depths, exec, lines: Lines::new(src), tests, regions }; let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); hits.extend(ignore_hits(&file)); hits.extend(sleep_hits(&file)); @@ -1309,19 +1380,106 @@ struct View<'a> { delegates: bool, checks: bool, should_panic: bool, + /// An ignored test with a reason that prints what it measures ([`ignored_with_reason`], + /// [`prints`]): a diagnostic run by hand, which has nothing to assert. + diagnostic: bool, +} + +/// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple +/// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings +/// and parameters that shadow helper names. +fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { + passed_names(m, t.open, t.close).into_iter().any(|name| { + name != t.name && !COMMON.contains(&name.as_str()) && helpers.contains(&name) && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes()) + }) +} + +/// Whether a local binding or parameter between `at` and `close` shadows the helper `name`. +fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8]) -> bool { + let_binds(&m[open + 1..close], name) || binds_parameter(&m[at..close], name) +} + +/// The bare identifiers passed as arguments or tuple elements in the body between `open` and `close`. +fn passed_names(m: &[u8], open: usize, close: usize) -> Vec { + let mut names = Vec::new(); + let mut at = open + 1; + while at < close { + if !is_ident(m[at]) || (at > 0 && (is_ident(m[at - 1]) || m[at - 1] == b'.')) { + at += 1; + continue; + } + let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); + let before = m[..at].trim_ascii_end().last().copied(); + let after = m.get(skip_ws(m, end)).copied(); + if matches!(before, Some(b'(' | b',')) && matches!(after, Some(b')' | b',')) { + names.push(String::from_utf8_lossy(&m[at..end]).into_owned()); + } + at = end; + } + names +} + +/// Whether a function or closure in `body` takes a parameter that binds `name`. +fn binds_parameter(body: &[u8], name: &[u8]) -> bool { + let binds = |from, to| { + split_args(body, from, to).into_iter().any(|(start, end)| { + let pattern = &body[start..end]; + let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); + !words(pattern, name, 0, end).is_empty() + }) + }; + if words(body, b"fn", 0, body.len()).into_iter().any(|at| { + let Some(open) = body[at + 2..].iter().position(|&c| c == b'(').map(|p| at + 2 + p) else { return false }; + matching(body, open).is_some_and(|close| binds(open + 1, close)) + }) { + return true; + } + let mut at = 0; + while at < body.len() { + let head = body[..at].trim_ascii_end(); + let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); + if body[at] == b'|' && opens { + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + if binds(at + 1, close) { + return true; + } + at = close; + } + at += 1; + } + false +} + +/// Whether the attributes in `file.m[from..to]` include `#[ignore = "…"]` with a non-blank reason. +fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool { + let m = &file.m; + words(m, b"ignore", from, to).into_iter().any(|at| { + let j = skip_ws(m, at + "ignore".len()); + m[..at].ends_with(b"#[") + && m.get(j) == Some(&b'=') + && ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + }) +} + +/// Whether the masked text prints: `println!`, `eprintln!`, `print!` or `eprint!`. +fn prints(m: &[u8], from: usize, to: usize) -> bool { + macro_calls(m, from, to).iter().any(|c| matches!(c.name.as_str(), "println" | "eprintln" | "print" | "eprint")) } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { let m = &file.exec; let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); let none = HashSet::new(); - let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); + let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); let delegates = calls(m, t.open, t.close) .iter() - .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) + || passes_helper(m, t, helpers); let checks = checks_itself(m, t.open, t.close); let should_panic = should_panic_attr(m, t.attr, t.fn_at); - let v = View { file, t, asserts, delegates, checks, should_panic }; + let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close); + let v = View { file, t, asserts, delegates, checks, should_panic, diagnostic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); hits.extend(early_returns(&v)); @@ -1811,7 +1969,167 @@ fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); let none_match = not_equal_conjunction(body); let (receiver, need) = receiver_need(&cond[..i], sizes); - !none_match && least_items(receiver, test_body, sizes) < need + // A parenthesized range of literals or constants: `(0..3).all(…)`. + let range = if receiver.starts_with('(') { expr_len(receiver, sizes, "") } else { 0 }; + let known = least_items(receiver, test_body, sizes).max(range); + !none_match && known < need && !(need == 1 && (pinned_source(receiver, test_body, sizes) || fixed_table_call(receiver, test_body, sizes))) + }) +} + +/// Whether an earlier equality assertion compares what `receiver` is made from with a non-empty +/// literal: a plain local whose binding reads `receiver` (`let got = r.items()….collect(); +/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`), or a call on the same plain local +/// as the call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(ids(&word), [a, b, c])`). +fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let init = |name: &str, at: usize| let_init(body, name, at).and_then(|(init, _)| init); + // For a receiver bound to `f(&x)`: `x`, and where the binding of `x` it reads ends. + let source = if plain_local(r) { + let_init(body, r, body.len()).and_then(|(init, bound)| { + let (text, _) = init?; + let s = single_local_arg(&text)?.to_owned(); + if binds(&body[bound..], s.as_bytes()) { + return None; + } + let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); + Some((s, at)) + }) + } else { + None + }; + macro_calls(body, 0, body.len()).into_iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) || a.args.len() < 2 { + return false; + } + let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1])); + [(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| { + if literal_len(literal, sizes) == 0 { + return false; + } + // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), and + // nothing changes the receiver's source from the binding on. + let read = !plain_local(r) + && plain_local(pinned) + && init(pinned, a.at) + .is_some_and(|(text, at)| keeping_base(&text, true) == r && !touched_after(body, root_local(r), statement_end(body, at), r)); + read || source.as_ref().is_some_and(|(s, at)| single_local_arg(pinned) == Some(s.as_str()) && !touched_after(body, s, *at, r)) + }) + }) +} + +/// The local a receiver path starts from: `r` of `r.items()`. +fn root_local(expr: &str) -> &str { + let end = expr.bytes().take_while(|&c| is_ident(c)).count(); + &expr[..end] +} + +/// Whether code after `from` uses `name` other than through a read-only use of `receiver`, a shared borrow +/// `&name`, or a getter named `len`, `is_empty` or ending in `_count`. Other uses, including +/// assertion arguments, may change what it holds. +fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { + if !plain_local(name) { + return true; + } + words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { + let rest = norm(&body[at..statement_end(body, at)]); + let head = body[..at].trim_ascii_end(); + let shared = head.ends_with(b"&") && !head.ends_with(b"&&"); + let getter = rest + .strip_prefix(name) + .and_then(|r| r.strip_prefix('.')) + .and_then(|r| r.split_once('(')) + .is_some_and(|(method, _)| plain_local(method) && (matches!(method, "len" | "is_empty") || method.ends_with("_count"))); + let read = rest.strip_prefix(receiver).is_some_and(|tail| { + tail.is_empty() + || tail.starts_with([')', ']', '}', ',']) + || [".iter()", ".len()", ".is_empty()", ".first()", ".last()", ".get(", ".contains("].iter().any(|method| tail.starts_with(method)) + }); + !(read || shared || getter) + }) +} + +/// The plain local of a call with one argument, `f(&x)` or `f(x)`. +fn single_local_arg(call: &str) -> Option<&str> { + let open = call.find('(')?; + let head = &call[..open]; + if head.is_empty() || !head.bytes().all(|c| is_ident(c) || c == b':') || matching(call.as_bytes(), open) != Some(call.len() - 1) { + return None; + } + let arg = &call[open + 1..call.len() - 1]; + let arg = arg.strip_prefix('&').unwrap_or(arg); + plain_local(arg).then_some(arg) +} + +/// Whether `receiver` calls a function of the file whose body lists a constant table +/// (`TABLE.iter()…`, `Kind::ALL.iter()…`) and filters it only on parameters that are not +/// references: which rows it gives depends on the table and plain values, not on the state the +/// test builds. +fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let Some(open) = r.find('(') else { return false }; + let name = &r[..open]; + if !plain_local(name) + || matching(r.as_bytes(), open) != Some(r.len() - 1) + || let_binds(test_body, name.as_bytes()) + || binds_parameter(test_body, name.as_bytes()) + { + return false; + } + let file = sizes.file; + words(file, name.as_bytes(), 0, file.len()).into_iter().any(|at| { + let head = file[..at].trim_ascii_end(); + if !head.ends_with(b"fn") || (head.len() > 2 && is_ident(head[head.len() - 3])) { + return false; + } + let Some((_, _, body_open, body_close)) = item_at(file, head.len() - 2) else { return false }; + let params_open = skip_ws(file, at + name.len()); + let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; + let signature = norm(&file[params_close + 1..body_open]); + let return_type = signature.strip_prefix("->").unwrap_or(""); + let refs: Vec = split_args(file, params_open + 1, params_close) + .into_iter() + .filter_map(|(f, t)| norm(&file[f..t]).split_once(':').filter(|(_, ty)| ty.starts_with('&')).map(|(n, _)| n.to_owned())) + .collect(); + let body = norm(&file[body_open + 1..body_close]); + let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); + let table = &body[..table_end]; + let screaming = table + .rsplit("::") + .next() + .is_some_and(|last| !last.is_empty() && last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')); + if !screaming || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + return false; + } + // The body is the chain alone, of steps that keep or filter rows; everything up to the end + // of the last `filter`, maps before it included, reads no reference parameter. + let mut at = table_end; + let mut decided = 0; + while at < body.len() { + let Some(rest) = body[at..].strip_prefix('.') else { return false }; + let method_len = rest.bytes().take_while(|&c| is_ident(c)).count(); + let method = &rest[..method_len]; + let mut open = at + 1 + method_len; + let mut target = None; + if method == "collect" && body[open..].starts_with("::<") { + let Some(close) = body[open..].find(">(") else { return false }; + target = Some(&body[open + 3..open + close]); + open += close + 1; + } + let Some(close) = (body.as_bytes().get(open) == Some(&b'(')).then(|| matching(body.as_bytes(), open)).flatten() else { return false }; + match method { + "iter" | "into_iter" | "map" | "copied" | "cloned" | "enumerate" | "rev" => {} + "collect" => { + if !known_collection(target.unwrap_or(if close + 1 == body.len() { return_type } else { "" })) { + return false; + } + } + "filter" => decided = close + 1, + _ => return false, + } + at = close + 1; + } + let decided = &body[..decided]; + refs.iter().all(|p| words(decided.as_bytes(), p.as_bytes(), 0, decided.len()).is_empty()) }) } @@ -1880,6 +2198,23 @@ fn least_items(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { .max(if binds(body, array_receiver(receiver).as_bytes()) { 0 } else { item_len(receiver, sizes) }) } +/// Whether a `let` pattern in masked `body` contains `name` as a whole word. +fn let_binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + !words(body, name, start, end).is_empty() + }) +} + /// Whether `body` has a `let` binding of `name`. fn binds(body: &[u8], name: &[u8]) -> bool { words(body, b"let", 0, body.len()).into_iter().any(|at| { @@ -2689,7 +3024,7 @@ fn strip_stream_configuration(body: &mut [u8]) { } fn no_assertion(v: &View) -> Option { - if v.checks || v.delegates || v.should_panic { + if v.checks || v.delegates || v.should_panic || v.diagnostic { return None; } Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) @@ -5128,6 +5463,153 @@ mod tests { assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ..Ctx::default() }), []); } + #[test] + fn a_files_own_helper_decides_over_one_of_the_same_name_in_another_file() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n"; + let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n"; + let caller = "#[test]\nfn v() {\n near(f());\n}\n"; + let files = [ + ("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), + ("crates/x/tests/it/other.rs".to_owned(), other.to_owned()), + ("crates/x/tests/it/caller.rs".to_owned(), caller.to_owned()), + ]; + let ctx = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &ctx), [], "the file's own near asserts"); + let qualified = own.replace(" near(f());", " other::near(f());"); + let files = [files[0].clone(), files[1].clone(), ("crates/x/tests/it/q.rs".to_owned(), qualified.clone())]; + let ctx_q = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/q.rs", &qualified, &ctx_q), + [(3, "no-assertion")], + "a call with a path may reach the other file's near" + ); + assert_eq!( + hits_in("crates/x/tests/it/caller.rs", caller, &ctx), + [(2, "no-assertion")], + "a file that defines none cannot tell which it reaches" + ); + let nested = "mod a {\n fn near(a: f64) { assert!(a < 1.0); }\n}\nuse other::*;\n#[test]\nfn t() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/nested.rs".to_owned(), nested.to_owned()), files[1].clone()]; + let ctx_nested = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/nested.rs", nested, &ctx_nested), + [(6, "no-assertion")], + "a helper inside an inline module does not decide for the file's top-level call" + ); + let inner = + "fn near(a: f64) { assert!(a < 1.0); }\nmod inner {\n use super::other::*;\n #[test]\n fn t() {\n near(f());\n }\n}\n"; + let files = [("crates/x/tests/it/inner.rs".to_owned(), inner.to_owned()), files[1].clone()]; + let ctx_inner = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/inner.rs", inner, &ctx_inner), + [(5, "no-assertion")], + "a test inside an inline module may import the other file's near" + ); + let local = "#[test]\nfn t() {\n fn near(a: f64) { assert!(a < 1.0); }\n assert!(f());\n}\n#[test]\nfn u() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/local.rs".to_owned(), local.to_owned()), files[1].clone()]; + let ctx_local = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/local.rs", local, &ctx_local), + [(7, "no-assertion")], + "a helper inside a test does not decide for another test's call" + ); + } + + #[test] + fn an_ignored_diagnostic_that_prints_needs_no_assertion() { + let diagnostic = "#[test]\n#[ignore = \"manual timing\"]\nfn t() {\n let n = f();\n eprintln!(\"{n:?}\");\n}\n"; + assert_eq!(hits(diagnostic), []); + assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing"); + assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints"); + } + + #[test] + fn a_test_body_passed_to_a_wrapper_counts_as_its_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + let wrapper = src.replace(" keeping(body);", " wrapper();") + "fn wrapper() {\n keeping(body);\n}\n"; + let wrapper_ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), wrapper.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &wrapper, &wrapper_ctx), []); + let shadowed_wrapper = wrapper.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + let shadowed_wrapper_ctx = + Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), shadowed_wrapper.clone())]), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/src/tests.rs", &shadowed_wrapper, &shadowed_wrapper_ctx), + [(8, "no-assertion")], + "a local binding in a wrapper shadows the asserting helper" + ); + let shadowed = src.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &shadowed, &ctx), [(8, "no-assertion")], "a local binding shadows the asserting helper"); + let destructured = src.replace(" keeping(body);", " let (body,) = (|| {},);\n keeping(body);"); + assert_eq!( + hits_in("crates/x/src/tests.rs", &destructured, &ctx), + [(8, "no-assertion")], + "a destructured binding shadows the asserting helper" + ); + let closure = src.replace(" keeping(body);", " keeping(|body| keeping(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); + let parameter = src.replace("fn t()", "fn t(body: fn())"); + assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); + let idle = src.replace("assert_eq!(f(), 1);", "f();"); + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); + } + + #[test] + fn all_over_a_literal_range_or_a_pinned_source_is_guarded() { + let range = "#[test]\nfn t() {\n assert!((0..3).all(|i| a[i] == b[i]));\n}\n"; + assert_eq!(hits(range), []); + assert_eq!(hits(&range.replace("(0..3)", "(0..n)")), [(3, "all-unguarded")], "a range whose end the test does not show"); + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(pinned), []); + assert_eq!(hits(&pinned.replace("vec![1, 2]", "vec![]")), [(5, "all-unguarded")], "pinned to an empty list"); + assert_eq!(hits(&pinned.replace("= r.items()", "= other.items()")), [(5, "all-unguarded")], "a list made from another receiver"); + let shadowed = "#[test]\nfn t() {\n let got = f();\n assert_eq!(got, vec![1]);\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(shadowed), [(6, "all-unguarded")], "the pinned binding is not the one made from the receiver"); + let cleared = pinned.replace(" assert!(r.items()", " r.clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "the receiver changed after the assertion"); + let cleared_items = pinned.replace(" assert!(r.items()", " r.items().clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared_items), [(6, "all-unguarded")], "the receiver's items changed after the assertion"); + let early = pinned.replace(" assert_eq!(got", " r.clear();\n assert_eq!(got"); + assert_eq!(hits(&early), [(6, "all-unguarded")], "the receiver changed between the binding and the assertion"); + let taken = pinned.replace(" assert!(r.items()", " assert!(r.take_items().is_some());\n assert!(r.items()"); + assert_eq!(hits(&taken), [(6, "all-unguarded")], "an assertion changes the receiver after the pinning assertion"); + let counted = pinned.replace(" assert!(r.items()", " assert_eq!(r.unhandled_rejection_count(), 2);\n assert!(r.items()"); + assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); + let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); + assert_eq!(hits(&chained), [(5, "all-unguarded")], "a list that is not empty without the receiver's items"); + let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(ids(&plain), [1, 2, 3]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; + assert_eq!(hits(word), []); + assert_eq!(hits(&word.replace("ids(&plain)", "ids(&other)")), [(6, "all-unguarded")], "a literal about another value"); + let emptied = word.replace(" let gaps = gaps(&plain);\n", " let mut gaps = gaps(&plain);\n gaps.clear();\n"); + assert_eq!(hits(&emptied), [(7, "all-unguarded")], "a receiver that may change after its binding"); + let rebound = word.replace(" assert_eq!(ids(&plain), [1, 2, 3]);\n", "").replace( + " let gaps = gaps(&plain);", + " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(ids(&plain), [1, 2, 3]);", + ); + assert_eq!(hits(&rebound), [(7, "all-unguarded")], "the assertion reads a later binding of the source"); + } + + #[test] + fn all_over_a_constant_table_filtered_on_plain_values_is_guarded() { + let src = "fn reasons(app: &App, wide: bool) -> Vec> {\n TABLE.iter().filter(|r| r.wide == wide).map(|r| app.reason(r)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, true).iter().all(|r| r.is_none()));\n}\n"; + assert_eq!(hits(src), []); + let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: bool| Vec::>::new();\n assert!"); + assert_eq!(hits(&shadowed), [(8, "all-unguarded")], "a local binding shadows the file's function"); + let state = src.replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); + assert_eq!(hits(&state), [(7, "all-unguarded")], "a filter on the state the test builds"); + let mapped = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map(|r| app.reason(r)).filter(|r| r.is_some())"); + assert_eq!(hits(&mapped), [(7, "all-unguarded")], "a filter on values mapped from that state"); + let map_while = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map_while(|r| app.reason(r))"); + assert_eq!(hits(&map_while), [(7, "all-unguarded")], "another step that drops rows"); + let optional = src + .replace("-> Vec>", "-> Option>>") + .replace(".map(|r| app.reason(r))", ".map(|r| Some(app.reason(r)))") + .replace(".all(|r| r.is_none())", ".all(|r| r.len() == 1)"); + assert_eq!(hits(&optional), [(7, "all-unguarded")], "collecting into an option can discard every row"); + } + #[test] fn a_changed_collection_loses_its_equality_guard() { let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!(xs, vec![1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; From 03bddf6a2afa7824ac73409a319996858689ba7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:01:53 -0800 Subject: [PATCH 27/60] xtask: fix test-lint false hits and misses in census, gates and source reads census: - an asserting helper after || no longer keeps a loop out of the census - a let that rebinds the entry name to another value shadows it until its block ends; a rebinding from the entry ends the shadow - a call in a let-bound closure that the loop never calls does not count - calls with a turbofish (app.run::(c)) are read as computations - -offset is another input; only a minus before a number is a literal - a block on the right of || can be skipped; a finished if before the call does not skip it - a round trip can read the entry as the receiver (k.parse()) - a field label in a pattern does not bind the label's name never-run and module routes: - base hits match the same test by name and line - a parent too large to read at the base is reported as an incomplete comparison instead of an absent declaration; its size is checked before git show reads it, and each base file is read once - a removed route counts as a change to its child, including routes in deleted or renamed-away parents - cfg string values are decoded (\x, \u{}, escapes); an escape that is not decoded leaves the predicate unknown - every line of a multiline cfg attribute counts as a change - a tests folder inside src is a module, not a Cargo target root - #[path] accepts raw strings, and its targets are found from the declaring file, inside inline modules too, and followed transitively - every route at every depth of inline modules is kept, each with its own parents' gates; a crate root also loaded by #[path] still runs as its own target; a build script is not a test route - mod name; matches only the file it loads by default reads-source: - only path-taking calls count (fs::, an alias of std::fs, or an imported read_to_string), not Read::read_to_string or reader methods - whitespace inside a path literal is kept - a literal substituted into format! is not taken as the file name mirror and exact-pixel hits run through the compared operands, so a change to the expected side on a later line counts. A rect width in arithmetic is not reported as a hard-coded width. --- xtask/src/test_lint.rs | 1194 +++++++++++++++++++++++++++++++++++----- 1 file changed, 1046 insertions(+), 148 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index cc24470436..1a7731430a 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -81,7 +81,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. -use std::cell::OnceCell; +use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -272,20 +272,143 @@ fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap, base: Option<&Gates>, changed: &BTreeMap>>) -> bool { + gate_changed(current, changed) || base.is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent))) +} + +/// Whether the `never-run` hit `hit` is new against the hits of the same source with the base's +/// module gates: no base hit is for the same test at the same line. +fn newly_off(base: &[Hit], hit: &Hit) -> bool { + !base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +} + +/// A file as `git show` gave it at the base. +#[derive(Debug, PartialEq)] +enum BaseSource { + /// The path does not exist at the base. + Absent, + /// The file exists but is larger than [`MAX_FILE`], so it is not analyzed. + TooLarge, + Text(String), +} + +fn base_source(shown: Option) -> BaseSource { + match shown { + None => BaseSource::Absent, + Some(s) if s.len() as u64 > MAX_FILE => BaseSource::TooLarge, + Some(s) => BaseSource::Text(s), + } +} + +/// For each file a `#[path = "…"]` declaration loads, the files that declare it. +fn path_edges(files: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + // Cargo compiles a build script but never runs it as a test target. + for parent in files.iter().filter(|p| p.ends_with(".rs") && !p.ends_with("/build.rs") && p.as_str() != "build.rs") { + let Some(src) = read(parent) else { continue }; + if !src.contains("path") { + continue; + } + let m = mask(&src); + for at in words(&m, b"mod", 0, m.len()) { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + continue; + } + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + let target = path_target(parent, &inline_mods(&m, at), &rel); + let parents = out.entry(target).or_default(); + if !parents.contains(parent) { + parents.push(parent.clone()); + } + } + } + } + out +} + +/// The union of two [`path_edges`] maps. +fn merge_edges(a: &HashMap>, b: HashMap>) -> HashMap> { + let mut out = a.clone(); + for (target, parents) in b { + let entry = out.entry(target).or_default(); + for p in parents { + if !entry.contains(&p) { + entry.push(p); + } + } + } + out +} + +/// `edges` without the declarations made in `files`. +fn edges_without(edges: &HashMap>, files: &[String]) -> HashMap> { + edges + .iter() + .map(|(t, ps)| (t.clone(), ps.iter().filter(|p| !files.contains(p)).cloned().collect::>())) + .filter(|(_, ps)| !ps.is_empty()) + .collect() +} + +/// The files loaded through `#[path]` declarations, followed transitively from the changed files +/// `present` and the module directories `module_dirs`, and the module directories of those files. +fn path_loaded(edges: &HashMap>, present: &[String], module_dirs: &[String]) -> (BTreeSet, Vec) { + let (mut files, mut dirs): (BTreeSet, Vec) = (present.iter().cloned().collect(), module_dirs.to_vec()); + loop { + let more: Vec = edges + .iter() + .filter(|(t, ps)| !files.contains(*t) && ps.iter().any(|p| files.contains(p) || dirs.iter().any(|d| p.starts_with(d.as_str())))) + .map(|(t, _)| t.clone()) + .collect(); + if more.is_empty() { + break; + } + for t in more { + dirs.push(module_directory(&t)); + files.insert(t); + } + } + (files.into_iter().filter(|f| !present.contains(f)).collect(), dirs.split_off(module_dirs.len())) +} + /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. fn read_small(root: &Path, path: &str) -> Option { let full = root.join(path); (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } +/// The directory holding the modules a file declares, with a trailing `/`: the file's own directory +/// for `mod.rs`, `lib.rs` and `main.rs`, else the file's path without `.rs`. +fn module_directory(path: &str) -> String { + let (dir, file) = path.rsplit_once('/').unwrap_or(("", path)); + if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", path.trim_end_matches(".rs")) } +} + +/// The paths in `git … -z` output, which separates them with NUL and leaves them unquoted. +fn nul_paths(out: &str) -> Vec { + out.split('\0').filter(|p| !p.is_empty()).map(str::to_owned).collect() +} + +/// The `git` arguments that list files deleted since `base`. Without rename detection, the old path +/// of a renamed file is listed too. +fn deleted_diff_args(base: &str) -> [&str; 6] { + ["diff", "--name-only", "-z", "--diff-filter=D", "--no-renames", base] +} + pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let opts = Options::parse(args)?; let repo = crate::repo_files(root)?; let ci_env = ci_env(root, &repo)?; let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); + // `#[path]` declarations load files outside the declaring module's directory. + let edges = path_edges(&files, &|p| read_small(root, p)); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + let module_cfgs = module_gates_with(&files, &|p| read_small(root, p), &edges).into_iter().map(|(p, g)| (p, g.preds)).collect(); let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); @@ -293,48 +416,111 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } let base = resolve_base(root, opts.base)?; let changed = changed_lines(root, &base)?; - let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + let mut changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + // A deleted parent can have given the only CI route to a module; its routes exist only at the base. + let deleted: Vec = nul_paths(&git(root, &deleted_diff_args(&base))?).into_iter().filter(|p| is_scanned(p)).collect(); + for d in &deleted { + changed.entry(d.clone()).or_insert(None); + } let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn // their tests off without a change to them. - let module_dirs: Vec = present - .iter() - .map(|p| { - let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); - if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } - }) - .collect(); - let below: Vec = - files.iter().filter(|p| !changed.contains_key(*p) && module_dirs.iter().any(|d| p.starts_with(d.as_str()))).cloned().collect(); + let module_dirs: Vec = present.iter().chain(&deleted).map(|p| module_directory(p)).collect(); + // Files read at the base, for the gates the parent declarations gave there. A parent too large + // to read at the base leaves the comparison incomplete, which is reported instead of counted. + let too_large = RefCell::new(BTreeSet::new()); + let shown: RefCell>> = RefCell::new(HashMap::new()); + let read_base_once = |p: &str| { + let spec = format!("{base}:{p}"); + let size = git(root, &["cat-file", "-s", &spec]).ok().and_then(|s| s.trim().parse::().ok()); + let s = match size { + None => None, + Some(n) if n > MAX_FILE => { + too_large.borrow_mut().insert(p.to_owned()); + None + } + Some(_) => match base_source(git(root, &["show", &spec]).ok()) { + BaseSource::Text(s) => Some(s), + BaseSource::TooLarge => { + too_large.borrow_mut().insert(p.to_owned()); + None + } + BaseSource::Absent => None, + }, + }; + shown.borrow_mut().insert(p.to_owned(), s.clone()); + s + }; + let read_base = |p: &str| { + let cached = shown.borrow().get(p).cloned(); + cached.unwrap_or_else(|| read_base_once(p)) + }; + // A `#[path]` route removed from a changed file exists only at the base. + let changed_files: Vec = changed.keys().cloned().collect(); + let base_edges = merge_edges(&edges_without(&edges, &changed_files), path_edges(&changed_files, &read_base)); + let all_edges = merge_edges(&edges, base_edges.clone()); + // A deleted parent's base routes lead to files as well. + let seeds: Vec = present.iter().chain(&deleted).cloned().collect(); + let by_path = path_loaded(&all_edges, &seeds, &module_dirs); + let loaded = |p: &String| module_dirs.iter().chain(&by_path.1).any(|d| p.starts_with(d.as_str())) || by_path.0.contains(p); + let below: Vec = files.iter().filter(|p| !changed.contains_key(*p) && loaded(p)).cloned().collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); - let gates = module_gates(&gated, &|p| read_small(root, p)); + let gates = module_gates_with(&gated, &|p| read_small(root, p), &edges); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; - // The gates the parent declarations gave at the base: a parent edit counts against a child's - // test only when the test ran in CI before it. - let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + // A parent edit counts against a child's test only when the test ran in CI at the base. + let base_gates = module_gates_with(&gated, &read_base, &base_edges); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); + let route_changed = |path: &str| routes_changed(gates.get(path), base_gates.get(path), &changed); + // A base file too large to read may have declared the module even when no route names it: any + // such file in a directory above the module leaves the comparison incomplete. + let incomplete = |path: &str| { + let large = too_large.borrow(); + gates.get(path).into_iter().chain(base_gates.get(path)).flat_map(|g| &g.sources).any(|(p, _)| large.contains(p)) + || large.iter().any(|p| path.starts_with(&format!("{}/", p.rsplit_once('/').map_or("", |(d, _)| d)))) + }; let (mut counted, mut older) = (vec![], 0usize); + let child_hits = |path: &str, src: &str, hits: Vec, counted: &mut Vec| -> usize { + let base_hits = lint_file(path, src, &base_ctx); + let (mut new, mut skipped) = (vec![], 0usize); + for hit in hits { + if !newly_off(&base_hits, &hit) { + skipped += 1; + } else if incomplete(path) { + eprintln!("test-lint: {path}:{}: a parent module is larger than {MAX_FILE} bytes at {base}; not compared", hit.line); + skipped += 1; + } else { + new.push(hit); + } + } + counted.extend(new); + skipped + }; for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = route_changed(&path); + let mut by_parent = vec![]; for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) - || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) - { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { counted.push(hit); + } else if hit.rule == Rule::NeverRun && parent_changed { + by_parent.push(hit); } else { older += 1; } } + if !by_parent.is_empty() { + older += child_hits(&path, &src, by_parent, &mut counted); + } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + for path in below.iter().filter(|p| route_changed(p)) { let Some(src) = read_small(root, path) else { continue }; - counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); + let off: Vec = lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + if !off.is_empty() { + child_hits(path, &src, off, &mut counted); + } } finish(&counted, older, present.len(), &base) } @@ -991,6 +1177,11 @@ const COMMON: &[&str] = &[ /// The names called in `m[from..to]`: functions (`name(`, also through a path), methods /// (`.name(`), including calls with turbofish arguments, and macros (`name!`). fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + calls_at(m, from, to).into_iter().map(|(name, method, _)| (name, method)).collect() +} + +/// [`calls`] with the offset where each name starts. +fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(String, bool, usize)> { let m = &m[..to]; let mut out = vec![]; let mut i = from; @@ -1007,7 +1198,7 @@ fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { let name = String::from_utf8_lossy(&m[i..end]).into_owned(); let method = i > 0 && m[i - 1] == b'.'; if !KEYWORDS.contains(&name.as_str()) { - out.push((if bang { format!("{name}!") } else { name }, method)); + out.push((if bang { format!("{name}!") } else { name }, method, i)); } } i = end; @@ -1434,7 +1625,12 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let weak_in = |from: usize, to: usize, var: &str| { let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); let body = &unmessaged[from - v.t.open..to - v.t.open]; - helpers_in(from, to).is_empty() + // A helper counts only where it runs whenever the assertions pass, not after an `||`. + let (f, t) = (from + 1 - v.t.open, to - v.t.open); + let helper_runs = calls_at(&unmessaged, f, t).into_iter().any(|(n, method, at)| { + !(n.ends_with('!') && is_assert_macro(&n)) && is_helper_call(&n, method, helpers) && runs_with_assertion(&unmessaged, f, t, at) + }); + !helper_runs && !rejects(body) && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) @@ -1485,10 +1681,21 @@ const LOOKUPS: &[&str] = &[ "find_map", ]; -/// The lowercase names a `for` or `let` pattern binds. +/// The lowercase names a `for` or `let` pattern binds. A field label (`Row { c: other }`) binds +/// the name after it. fn pattern_names(pattern: &str) -> impl Iterator + '_ { + let b = pattern.as_bytes(); pattern - .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .match_indices(|c: char| c.is_ascii_alphanumeric() || c == '_') + .filter(move |&(at, _)| at == 0 || !is_ident(b[at - 1])) + .map(move |(at, _)| (at, at + b[at..].iter().take_while(|&&c| is_ident(c)).count())) + .filter(move |&(at, end)| { + // Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`). + let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count(); + let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count(); + !in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':') + }) + .map(move |(at, end)| &pattern[at..end]) .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) .map(str::to_owned) } @@ -1502,9 +1709,11 @@ fn pattern_names(pattern: &str) -> impl Iterator + '_ { /// `Kind::from_id(k.id())`) is still a lookup. fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let mut derived: Vec = pattern_names(pattern).collect(); - let reads = |s: &[u8], names: &[String]| { - let s = String::from_utf8_lossy(s); - names.iter().any(|n| reads_ident(&s, n)) + // Where a `let` that does not read the entry rebinds one of its names: from the end of that + // statement to the end of its block, the name holds another value. + let mut shadows: Vec<(String, usize, usize)> = vec![]; + let live = |f: usize, t: usize, names: &[String], shadows: &[(String, usize, usize)]| { + names.iter().any(|n| words(b, n.as_bytes(), f, t).into_iter().any(|at| !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z))) }; // Names bound inside the loop from the entry count as the entry. for at in words(b, b"let", from, to) { @@ -1514,11 +1723,25 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { continue; }; let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); - if reads(&b[eq + 1..end], &derived) { - let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + if live(eq + 1, end, &derived, &shadows) { + // Rebinding from the entry suspends earlier shadows until this block ends. + let until = block_close(b, at).min(to); + let mut resumed = vec![]; + for s in shadows.iter_mut().filter(|s| names.contains(&s.0) && s.1 <= at && at < s.2) { + if until < s.2 { + resumed.push((s.0.clone(), until, s.2)); + } + s.2 = end; + } + shadows.extend(resumed); derived.extend(names); + } else { + let until = block_close(b, at).min(to); + shadows.extend(names.into_iter().filter(|n| derived.contains(n)).map(|n| (n, end, until))); } } + let reads = |f: usize, t: usize| live(f, t, &derived, &shadows); let literal = |s: &[u8]| { let s = norm(s); let s = s.trim_start_matches(['&', '*']); @@ -1528,56 +1751,21 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { _ => s, }; // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. + // A minus sign makes a literal only in front of a number (`-2`, not `-offset`). + let s = s.strip_prefix('-').unwrap_or(s); s.is_empty() - || s.starts_with(['"', '\'', '-', '|']) + || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || s.starts_with(|c: char| c.is_ascii_digit()) || matches!(s, "true" | "false" | "None") }; - (from..to).filter(|&i| b[i] == b'(' && i > from && is_ident(b[i - 1])).any(|open| { - let mut start = open; + (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { + let mut start = name_end; while start > from && is_ident(b[start - 1]) { start -= 1; } - let name = String::from_utf8_lossy(&b[start..open]); - if LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() { - return false; - } - // A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`); the - // right side of `&&` has to run for an assertion to pass. - let stmt = (from..start).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(from, |i| i + 1); - // Only an `||` at the call's own nesting level or an enclosing one counts, not one inside - // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; - // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. - // Sibling elements and assignments also end the expression that can skip the call. - let mut depth = 0usize; - let mut after_or = false; - for i in (stmt + 1..start).rev() { - match b[i] { - b')' | b']' => depth += 1, - b'(' | b'[' => depth = depth.saturating_sub(1), - _ => {} - } - if depth == 0 - && (b[i] == b',' || (b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))) - { - break; - } - if depth == 0 && b[i] == b'|' && b[i - 1] == b'|' { - let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); - let prefix = &b[stmt..end]; - let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); - let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); - if !moved - && !asynchronous - && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) - { - after_or = true; - break; - } - } - } - if after_or { + let name = String::from_utf8_lossy(&b[start..name_end]); + if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) { return false; } let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; @@ -1600,15 +1788,122 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { } inputs.push((r, start - 1)); } - let fed = inputs.iter().any(|&(f, t)| reads(&b[f..t], &derived)); + let fed = inputs.iter().any(|&(f, t)| reads(f, t)); // A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only // another argument (`u.parse(&text)`) makes it a computation. let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs }; - let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(&b[f..t], &derived)); + let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(f, t)); fed && other }) } +/// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the +/// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. +fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { + let before = open; + if before > from && is_ident(b[before - 1]) { + return Some(before); + } + if before == from || b[before - 1] != b'>' { + return None; + } + let mut depth = 0usize; + for i in (from..before).rev() { + match b[i] { + b'>' if i == 0 || b[i - 1] != b'-' => depth += 1, + b'<' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + let head = b[from..i].trim_ascii_end(); + let end = head.strip_suffix(b"::")?.trim_ascii_end().len(); + return (end > 0 && is_ident(b[from + end - 1])).then_some(from + end); + } + } + b';' | b'{' | b'}' => return None, + _ => {} + } + } + None +} + +/// Whether a call starting at `start` in the loop body `b[from..to]` runs whenever the loop's +/// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`, +/// also with a block as the right operand); the right side of `&&` has to run. A call inside a +/// zero-argument closure bound with `let` runs only when the loop calls that closure. +fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { + // The statement starts after a `;` or an unmatched brace, except for the `{` of a block that is + // the operand of `||` or `&&`. + let mut stmt = from; + let mut braces = 0usize; + for i in (from..start).rev() { + match b[i] { + // A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`) + // unless an operator joins the call's expression to it. + b'}' if braces == 0 && { + let after = b[i + 1..start].trim_ascii_start(); + !(after.starts_with(b"||") || after.starts_with(b"&&") || after.starts_with(b".") || after.starts_with(b"?")) + } => + { + stmt = i + 1; + break; + } + b'}' => braces += 1, + b'{' if braces > 0 => braces -= 1, + b'{' => { + let before = b[from..i].trim_ascii_end(); + if !(before.ends_with(b"||") || before.ends_with(b"&&")) { + stmt = i + 1; + break; + } + } + b';' if braces == 0 => { + stmt = i + 1; + break; + } + _ => {} + } + } + // Only an `||` at the call's own nesting level or an enclosing one counts, not one inside + // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; + // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. + // Sibling elements and assignments also end the expression that can skip the call. + let mut depth = 0usize; + let mut closure = None; + for i in (stmt + 1..start).rev() { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => depth = depth.saturating_sub(1), + _ => {} + } + if depth == 0 + && (b[i] == b',' || (b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))) + { + break; + } + if depth == 0 && b[i] == b'|' && b[i - 1] == b'|' { + let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); + let prefix = &b[stmt..end]; + let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); + let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); + if !moved + && !asynchronous + && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + { + return false; + } + closure = Some(stmt + prefix.len()); + } + } + // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. + let Some(end) = closure else { return true }; + let head = String::from_utf8_lossy(&b[stmt..end]); + let head = head.trim(); + let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true }; + let Some(name) = pattern_names(binding).last() else { return true }; + words(b, name.as_bytes(), end, to).into_iter().any(|at| b.get(skip_ws(b, at + name.len())) == Some(&b'(')) +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -1849,7 +2144,11 @@ fn round_trip_call(op: &str, var: &str) -> bool { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',']) - && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) + && matching(op.as_bytes(), open).is_some_and(|close| { + // The entry is read in the arguments (`Kind::from_id(k.id())`) or is the receiver (`k.parse()`). + let receiver = op[..at].strip_suffix('.').is_some_and(|r| reads_ident(r, var)); + only_unwraps(&op[close + 1..]) && (receiver || reads_ident(&op[open + 1..close], var)) + }) }) }) } @@ -3145,11 +3444,56 @@ fn reads_source_hits(file: &File) -> Vec { (&b"ends_with"[..], "keeps files ending in .rs"), (&b"read_to_string"[..], "reads a .rs file as text"), ]; + // A bare `read_to_string(…)` reads a path only where a `use` brings in `fs::read_to_string`. + let uses: Vec = + words(m, b"use", 0, m.len()).into_iter().map(|u| String::from_utf8_lossy(&m[u..statement_end(m, u)]).into_owned()).collect(); + let fs_imported = uses.iter().map(|u| norm(u.as_bytes())).any(|item| { + item.contains("fs::read_to_string") + || item.contains("fs::*") + || item.split_once("fs::{").is_some_and(|(_, list)| !words(list.as_bytes(), b"read_to_string", 0, list.len()).is_empty()) + }); + // Names `std::fs` is imported under (`use std::fs as filesystem;`). + let fs_aliases: Vec = uses + .iter() + .flat_map(|u| { + let b = u.as_bytes(); + words(b, b"as", 0, b.len()).into_iter().filter_map(move |at| { + let path = norm(&b[..at]); + let self_fs = path.ends_with("self") + && b[..at] + .iter() + .enumerate() + .rev() + .find(|&(i, &c)| c == b'{' && matching(b, i).is_some_and(|end| end > at)) + .is_some_and(|(open, _)| norm(&b[..open]).ends_with("fs::")); + let alias = b[at + 2..].trim_ascii_start(); + (path.ends_with("fs") || self_fs) + .then(|| String::from_utf8_lossy(&alias[..alias.iter().take_while(|&&c| is_ident(c)).count()]).into_owned()) + }) + }) + .filter(|a| !a.is_empty()) + .collect(); for (word, note) in words_and_notes { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { + if word == b"read_to_string" { + // `fs::read_to_string(path)` takes a path; `Read::read_to_string(&mut r, &mut buf)` and + // `reader.read_to_string(&mut buf)` take an output buffer. + let before = m[..at].trim_ascii_end(); + let path_call = match before.strip_suffix(b"::").map(<[u8]>::trim_ascii_end) { + Some(p) => ["fs"] + .into_iter() + .chain(fs_aliases.iter().map(String::as_str)) + .any(|q| p.ends_with(q.as_bytes()) && !p[..p.len() - q.len()].last().copied().is_some_and(is_ident)), + None => fs_imported && !before.ends_with(b".") && !before.ends_with(b"fn"), + }; + if !path_call { + continue; + } + } let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let arg = norm(&code[open + 1..close]); + // Whitespace inside a literal is part of the path (`"sample.r s"`). + let arg = norm_outside_literals(&code[open + 1..close], &m[open + 1..close]); // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); @@ -3157,7 +3501,9 @@ fn reads_source_hits(file: &File) -> Vec { b"ends_with" => literal == "\".rs\"", // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + // A literal inside `format!` is a value substituted into another path, so the file + // read is not known. + b"read_to_string" => path_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3171,6 +3517,47 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// `code` without the whitespace outside string literals; `m` is its masked text, where a literal's +/// quotes stay and its contents are blanked. +fn norm_outside_literals(code: &[u8], m: &[u8]) -> String { + let mut inside = false; + let kept: Vec = code + .iter() + .zip(m) + .filter_map(|(&c, &mc)| { + if mc == b'"' { + inside = !inside; + } + (inside || !c.is_ascii_whitespace()).then_some(c) + }) + .collect(); + String::from_utf8_lossy(&kept).into_owned() +} + +/// The literal that names the end of the path a (whitespace-free) argument reads: its last string +/// literal ([`last_literal`]), or, when that literal is a value substituted into a `format!`, the +/// format string itself (`format!("{}.json", "snapshot.rs")` reads a `.json` file). +fn path_literal(arg: &str) -> Option<&str> { + let close_q = arg.rfind('"')?; + let open_q = arg[..close_q].rfind('"')?; + for (f, _) in arg.match_indices("format!(") { + let open = f + "format!".len(); + let Some(close) = matching(arg.as_bytes(), open) else { continue }; + if !(open < open_q && close_q < close) { + continue; + } + let &(a, b) = split_args(arg.as_bytes(), open + 1, close).first()?; + if a <= open_q && close_q < b { + return Some(&arg[open_q..=close_q]); + } + // A format string that ends with a placeholder ends with the substituted value + // (`format!("{}/{}", root, "src/lib.rs")`). + let format_string = last_literal(&arg[a..b])?; + return Some(if format_string.ends_with("}\"") { &arg[open_q..=close_q] } else { format_string }); + } + Some(&arg[open_q..=close_q]) +} + /// The last string literal in a (whitespace-free) expression, quotes included. fn last_literal(arg: &str) -> Option<&str> { let close = arg.rfind('"')?; @@ -3246,8 +3633,12 @@ fn mirrors(v: &View) -> Vec { // compared as they are check that two inputs agree, which is a real check. let derived = ["+", "-", "*", "/"].iter().any(|op| !top_level_at(r, op).is_empty()); let last = name.rsplit("::").next().unwrap_or(name); - (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)) - .then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)).then(|| { + let mut h = v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name)); + // The span runs through the second operand, not the failure message. + h.last = h.last.max(v.file.lines.of(a.args[1].1)); + h + }) }) .collect() } @@ -3332,6 +3723,8 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), @@ -3339,6 +3732,59 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option` of the innermost `match` arm around `before` whose pattern binds `name`. +fn match_arm_binding(body: &[u8], name: &str, before: usize) -> Option { + let mut best = None; + for at in words(body, b"match", 0, before) { + let Some((open, close)) = let_body(body, at + 5) else { continue }; + if !(open < before && before < close) { + continue; + } + let (mut depth, mut start, mut i) = (0usize, open + 1, open + 1); + while i < close { + match body[i] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + b',' if depth == 0 => start = i + 1, + b'=' if depth == 0 && body.get(i + 1) == Some(&b'>') => { + let arrow = i; + let value = skip_ws(body, arrow + 2); + let end = if body.get(value) == Some(&b'{') { + matching(body, value).unwrap_or(close) + } else { + let mut d = 0usize; + (value..close) + .find(|&j| { + match body[j] { + b'(' | b'[' | b'{' => d += 1, + b')' | b']' | b'}' => d = d.saturating_sub(1), + _ => {} + } + d == 0 && body[j] == b',' + }) + .unwrap_or(close) + }; + let pattern = &body[start..arrow]; + let guard = words(pattern, b"if", 0, pattern.len()).first().copied().unwrap_or(pattern.len()); + // A field label (`Row { n: actual }`) is not a binding of `n`. + let binds = words(&pattern[..guard], name.as_bytes(), 0, guard).into_iter().any(|w| { + let next = skip_ws(pattern, w + name.len()); + pattern.get(next) != Some(&b':') || pattern.get(next + 1) == Some(&b':') + }); + if arrow < before && before <= end && binds { + best = best.max(Some(arrow)); + } + start = end + 1; + i = end; + } + _ => {} + } + i += 1; + } + } + best +} + /// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { let mut found = None; @@ -3494,20 +3940,62 @@ fn cfg_value(p: &str, t: &Target) -> Option { if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { return cfg_value(arg, t).map(|v| !v); } - // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. - let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + let (key, value) = p.split_once('=').map_or((p, None), |(k, v)| (k, Some(cfg_string(v)))); + // A value that cannot be decoded matches no known target, so the predicate is unknown. + let value = || value.clone().flatten(); match key { "test" => Some(true), "unix" => Some(t.family == "unix"), "windows" => Some(t.family == "windows"), - "target_os" => Some(t.os == value), - "target_family" => Some(t.family == value), - "target_arch" => Some(t.arch == value), - "target_pointer_width" => Some(value == "64"), + "target_os" => value().map(|v| t.os == v), + "target_family" => value().map(|v| t.family == v), + "target_arch" => value().map(|v| t.arch == v), + "target_pointer_width" => value().map(|v| v == "64"), _ => None, } } +/// The value of an ordinary or raw string literal in a (whitespace-free) `cfg` predicate: +/// `"linux"`, `"lin\x75x"`, `r"linux"`, `r#"linux"#`. Raw contents are kept as written; `None` for +/// an escape this does not decode. +fn cfg_string(lit: &str) -> Option { + if let Some(raw) = lit.strip_prefix('r') { + let hashes = raw.len() - raw.trim_start_matches('#').len(); + let inner = raw.get(hashes..raw.len().checked_sub(hashes)?)?; + return inner.strip_prefix('"')?.strip_suffix('"').map(str::to_owned); + } + let inner = lit.strip_prefix('"')?.strip_suffix('"')?; + let mut out = String::new(); + let mut chars = inner.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next()? { + 'n' => out.push('\n'), + 't' => out.push('\t'), + 'r' => out.push('\r'), + '0' => out.push('\0'), + c @ ('\\' | '"' | '\'') => out.push(c), + 'x' => { + let hex: String = chars.by_ref().take(2).collect(); + let v = u8::from_str_radix(&hex, 16).ok().filter(|v| *v <= 0x7f)?; + out.push(char::from(v)); + } + 'u' => { + let rest = chars.as_str().strip_prefix('{')?; + let close = rest.find('}')?; + let v = u32::from_str_radix(&rest[..close].replace('_', ""), 16).ok().and_then(char::from_u32)?; + out.push(v); + chars = rest[close + 1..].chars(); + } + _ => return None, + } + } + Some(out) +} + /// A `cfg` attribute found by [`cfg_attrs`]. struct CfgAttr { pred: String, @@ -3582,8 +4070,8 @@ fn pred_text(src: &[u8]) -> String { } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the -/// offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { @@ -3599,7 +4087,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - out.push((pred, at)); + out.push((pred, at, end)); } } out @@ -3610,7 +4098,9 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { /// `examples`). fn module_parent(path: &str) -> Option<(&str, Vec)> { let (dir, file) = path.rsplit_once('/')?; - let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); + // Cargo's target directories sit next to `src`; a `tests` folder inside `src` is a module. + let in_src = format!("/{dir}/").contains("/src/"); + let root_dir = !in_src && ["/tests", "/benches", "/examples"].iter().any(|d| format!("/{dir}").ends_with(d)); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } @@ -3628,6 +4118,16 @@ struct Loaded<'a> { chain: &'a [String], } +/// The file a `#[path = "rel"]` declaration in `parent` loads: relative to `parent`'s directory, or, +/// inside the inline modules `chain`, to their directory under `parent`'s module. +fn path_target(parent: &str, chain: &[String], rel: &str) -> String { + let mut base = if chain.is_empty() { parent.rsplit_once('/').map_or("", |(d, _)| d).to_owned() } else { module_directory(parent) }; + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + /// The `cfg` predicates under which `src`, the file `parent`, loads `want`: those on the /// `mod ;` declarations that load it (by name, or through a `#[path]` override) and on the /// items, inline modules and file around them, with the 1-based lines of those declarations and @@ -3647,19 +4147,21 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => { - // A `#[path]` outside inline modules is relative to the file's directory; inside them, - // to the inline modules' directory under the file's module. + Some(rel) => path_target(parent, want.chain, &rel) == want.path, + None => { + // The default file of `mod name;`: `name.rs` or `name/mod.rs` under the declaring + // module's directory and the inline modules around the declaration. let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { + if !mod_rs { base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); } for seg in want.chain { base = join_path(&base, seg); } - join_path(&base, &rel) == want.path + let name = String::from_utf8_lossy(&m[start..end]); + &m[start..end] == want.name.as_bytes() + && [format!("{name}.rs"), format!("{name}/mod.rs")].iter().any(|f| join_path(&base, f) == want.path) } - None => &m[start..end] == want.name.as_bytes(), }; if !loads { continue; @@ -3667,11 +4169,12 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); at_lines.push(lines.of(at)); - at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); + // Every line of a multiline attribute counts. + at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); - for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + for (p, a, end) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); - at_lines.push(lines.of(a)); + at_lines.extend(lines.of(a)..=lines.of(end)); } each.push(preds); } @@ -3688,11 +4191,16 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { words(m, b"path", from, to).into_iter().find_map(|at| { let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); let eq = skip_ws(m, at + 4); - let q = skip_ws(m, eq + 1); + // An ordinary or raw string: `"x.rs"`, `r"x.rs"`, `r#"x.rs"#`. + let open = skip_ws(m, eq + 1); + let raw = m.get(open) == Some(&b'r'); + let hashes = if raw { m[open + 1..].iter().take_while(|&&c| c == b'#').count() } else { 0 }; + let q = if raw { open + 1 + hashes } else { open }; if !attr || m.get(eq) != Some(&b'=') || m.get(q) != Some(&b'"') { return None; } - let close = find(m, b"\"", q + 1)?; + let closing: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let close = find(m, &closing, q + 1)?; Some(String::from_utf8_lossy(&src[q + 1..close]).into_owned()) }) } @@ -3731,6 +4239,7 @@ fn inline_mods(m: &[u8], at: usize) -> Vec { /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. +#[cfg(test)] fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() } @@ -3744,49 +4253,19 @@ struct Gates { } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that -/// may declare its module and, when none does, in the files above them through inline modules +/// may declare its module and in the files above them through inline modules /// (`mod platform { mod child; }` loads `platform/child.rs`). +#[cfg(test)] fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { + module_gates_with(paths, read, &HashMap::new()) +} + +/// [`module_gates`], also looking up each file in the files `edges` ([`path_edges`]) names as +/// declaring it through `#[path]`. +fn module_gates_with(paths: &[String], read: &dyn Fn(&str) -> Option, edges: &HashMap>) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } + let gates = file_gates(path, read, edges, 0); if !gates.preds.is_empty() { out.insert(path.clone(), gates); } @@ -3794,12 +4273,83 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> Hash out } +/// The [`Gates`] of one file: each route that loads it (a declaring file, at any depth of inline +/// modules) contributes that declaration's predicates and its parent's own gates. Several routes +/// join into one `any(all(…), …)`, so the tests are off only when every route leaves them out. +fn file_gates(at: &str, read: &dyn Fn(&str) -> Option, edges: &HashMap>, depth: usize) -> Gates { + let mut gates = Gates::default(); + if depth >= 16 { + return gates; + } + let declared_by = edges.get(at).cloned().unwrap_or_default(); + // A crate root that a `#[path]` declaration also loads still runs as its own target. + let root = module_parent(at).is_none(); + let (name, mut candidates) = match module_parent(at) { + Some((n, c)) => (n.to_owned(), c), + None if !declared_by.is_empty() => (at.rsplit_once('/').map_or(at, |(_, f)| f).trim_end_matches(".rs").to_owned(), vec![]), + None => return gates, + }; + for d in &declared_by { + if !candidates.contains(d) { + candidates.push(d.clone()); + } + } + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let mut module_dir = if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }; + let mut chain: Vec = vec![]; + let mut found = vec![]; + for _ in 0..4 { + let want = Loaded { path: at, name: &name, chain: &chain }; + found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + let Some(dir) = module_dir.take() else { break }; + let Some((up, seg)) = dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = Some(up); + } + for parent in declared_by { + let Some(src) = read(&parent) else { continue }; + let m = mask(&src); + let chains: BTreeSet> = words(&m, b"mod", 0, m.len()).into_iter().map(|at| inline_mods(&m, at)).collect(); + for chain in chains { + let want = Loaded { path: at, name: &name, chain: &chain }; + if let Some(route) = declared_cfgs(&src, &parent, &want) { + let entry = (parent.clone(), route); + if !found.contains(&entry) { + found.push(entry); + } + } + } + } + let mut routes: Vec> = vec![]; + for (parent, (preds, lines)) in found { + let up = file_gates(&parent, read, edges, depth + 1); + routes.push(preds.into_iter().chain(up.preds).collect()); + gates.sources.push((parent, lines)); + gates.sources.extend(up.sources); + } + if root && !routes.is_empty() { + routes.push(vec![]); + } + match routes.len() { + 0 => {} + 1 => gates.preds = routes.pop().unwrap_or_default(), + _ => gates.preds.push(format!("any({})", routes.iter().map(|p| format!("all({})", p.join(","))).collect::>().join(","))), + } + gates +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); // A change to an attribute that turns the test off counts as a change to the test. - let attr_lines: Vec = local.iter().map(|&(_, at)| v.file.lines.of(at)).collect(); - let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); + let attr_lines: Vec = local.iter().flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect(); + let mut preds: Vec = local.into_iter().map(|(p, _, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -3859,8 +4409,31 @@ fn names_rect(op: &str) -> bool { if b.get(after) == Some(&b'(') { after = matching(b, after).map_or(b.len(), |c| c + 1); } - let rest = &op[after..]; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + // The rect, or a part of it, has to be the whole operand: `rect.min.x`, not + // `rect.width() - other.width()`. + let mut rest = &op[after..]; + loop { + let coord = [".x", ".y"].iter().find(|c| rest.starts_with(**c) && !rest.as_bytes().get(2).copied().is_some_and(is_ident)); + match RECT_PARTS.iter().find(|p| rest.starts_with(**p) && !rest.as_bytes().get(p.len()).copied().is_some_and(is_ident)).or(coord) { + Some(p) => rest = &rest[p.len()..], + None => break, + } + } + // Before it, only the path or receiver chain it is read through (`resp.rect`). + let prefix = op[..i].trim_start_matches(['&', '*']); + let mut at = 0; + let mut operator = false; + while at < prefix.len() { + match prefix.as_bytes()[at] { + b'(' | b'[' | b'{' => at = matching(prefix.as_bytes(), at).map_or(prefix.len(), |close| close + 1), + b'+' | b'-' | b'*' | b'/' | b'%' | b'^' | b'|' | b',' | b'=' | b'<' | b'>' | b'!' => { + operator = true; + break; + } + _ => at += 1, + } + } + if rest.is_empty() && !operator { return true; } } @@ -3898,7 +4471,13 @@ fn exact_pixels(v: &View) -> Vec { return None; }; let pixel = (names_rect(&l) && only_numbers(&r)) || (names_rect(&r) && only_numbers(&l)); - pixel.then(|| v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) + // The span runs through the compared operands, not the failure message. + let operands = if a.name.ends_with("_eq") { a.args[1].1 } else { a.args[0].1 }; + pixel.then(|| { + let mut h = v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name)); + h.last = h.last.max(v.file.lines.of(operands)); + h + }) }) .collect() } @@ -3991,6 +4570,57 @@ mod tests { assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } + #[test] + fn census_follows_the_calls_that_run_for_each_entry() { + let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| census_in(&loop_of(body)); + assert_eq!(census("assert!(menu(c).is_some() || verify_fallback(c).is_ok());"), [(2, "census")], "a helper after || can be skipped"); + assert_eq!(census("assert!(menu(c).is_some() && verify_fallback(c).is_ok());"), [], "a helper after && runs"); + assert_eq!(census("assert!(menu(c).is_some()); { let c = fallback(); app.run(c); }"), [(2, "census")], "a shadowed entry name"); + assert_eq!(census("assert!(menu(c).is_some()); app.run(c);"), [], "the entry itself"); + assert_eq!(census("let _run = || app.run(c); assert!(menu(c).is_some());"), [(2, "census")], "a closure that is never called"); + assert_eq!(census("assert!(app.run::(c).is_ok());"), [], "a call with a turbofish"); + assert_eq!(census("assert!(menu::(c).is_some());"), [(2, "census")], "an entry-only call with a turbofish"); + assert_eq!(census("assert!(render(c, -offset).is_ok());"), [], "a negated variable is another input"); + assert_eq!(census("assert!(render(c, -2).is_ok());"), [(2, "census")], "a negative literal is not"); + assert_eq!( + census("let _ = menu(c).is_some() || { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a block on the right of || can be skipped" + ); + assert_eq!( + census("let _ = (menu(c).is_some() || other(c).is_some()) && { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [], + "an || in an earlier group does not skip the block" + ); + assert_eq!(census("assert!(menu(c).is_some()); if first || second {} app.run(c);"), [], "an || in a finished if does not skip the call"); + assert_eq!( + census("let entry = c; let c = fallback(); let c = entry; assert!(menu(c).is_some()); app.run(c);"), + [], + "a name rebound from the entry is the entry again" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; } assert!(menu(entry).is_some()); app.run(c);"), + [(2, "census")], + "an inner entry binding does not end the outer fallback binding" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; app.run(c); } assert!(menu(entry).is_some());"), + [], + "the inner entry binding is live inside its block" + ); + assert_eq!( + census("let Row { c: other } = fallback(); assert!(menu(c).is_some()); app.run(c);"), + [], + "a field label does not rebind the entry" + ); + let receiver = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(k.parse(), k);\n }\n}\n"; + assert_eq!(census_in(receiver), [(2, "census")], "a round trip with the entry as receiver"); + let fixed = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(registry.lookup(\"baseline\"), k);\n }\n}\n"; + assert_eq!(census_in(fixed), [], "a lookup of a fixed key"); + } + #[test] fn census_loops_over_whole_tables_are_reported() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -5750,4 +6380,272 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + fn never_run_test() -> &'static str { + "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n" + } + + #[test] + fn base_hits_match_the_same_test_not_only_its_name() { + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn smoke() {}\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn smoke() {}\n}\n"; + let now: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + assert_eq!(now.len(), 2); + // At the base only `a::smoke` was off. + let base = [now[0].clone()]; + assert!(!newly_off(&base, &now[0]), "a::smoke was off at the base"); + assert!(newly_off(&base, &now[1]), "b::smoke has the same name and ran at the base"); + } + + #[test] + fn an_oversized_base_file_is_not_an_absent_one() { + assert_eq!(base_source(None), BaseSource::Absent); + assert_eq!(base_source(Some("mod child;\n".into())), BaseSource::Text("mod child;\n".into())); + assert_eq!(base_source(Some("x".repeat(MAX_FILE as usize + 1))), BaseSource::TooLarge); + } + + #[test] + fn a_removed_route_counts_as_a_route_change() { + let lib = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(unix)]\n#[path = \"child.rs\"]\nmod other;\n"; + let base_files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib), ("crates/x/src/child.rs", "")].into_iter().collect(); + let base_read = |p: &str| base_files.get(p).map(|s| (*s).to_owned()); + let base = module_gates(&["crates/x/src/child.rs".to_owned()], &base_read); + let now_lib = "#[cfg(target_os = \"macos\")]\nmod child;\n"; + let now_files: HashMap<&str, &str> = [("crates/x/src/lib.rs", now_lib), ("crates/x/src/child.rs", "")].into_iter().collect(); + let now_read = |p: &str| now_files.get(p).map(|s| (*s).to_owned()); + let now = module_gates(&["crates/x/src/child.rs".to_owned()], &now_read); + let changed: BTreeMap>> = [("crates/x/src/lib.rs".to_owned(), Some(BTreeSet::new()))].into_iter().collect(); + assert!(!gate_changed(now.get("crates/x/src/child.rs"), &changed), "the surviving declaration did not change"); + assert!(routes_changed(now.get("crates/x/src/child.rs"), base.get("crates/x/src/child.rs"), &changed)); + let ctx_now = Ctx { module_cfgs: now.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let ctx_base = Ctx { module_cfgs: base.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let off = lint_file("crates/x/src/child.rs", never_run_test(), &ctx_now); + assert_eq!(off.iter().filter(|h| h.rule == Rule::NeverRun).count(), 1); + assert!(newly_off(&lint_file("crates/x/src/child.rs", never_run_test(), &ctx_base), &off[0]), "the Unix route ran it at the base"); + } + + #[test] + fn cfg_string_values_are_decoded() { + let t = &CI_TARGETS[0]; + assert_eq!(cfg_value("target_os=\"lin\\x75x\"", t), Some(true)); + assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", t), Some(true)); + assert_eq!(cfg_value("target_os=r\"linux\"", t), Some(true)); + assert_eq!(cfg_value("target_os=r#\"lin\\x75x\"#", t), Some(false), "raw contents are kept"); + assert_eq!(cfg_value("target_os=\"lin\\qux\"", t), None, "an escape this does not decode"); + assert_eq!(cfg_value("target_os=\"macos\"", t), Some(false)); + let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", escaped), []); + } + + #[test] + fn every_line_of_a_multiline_cfg_counts() { + let src = "#[cfg(\n target_os = \"macos\"\n)]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[2].into_iter().collect())), "a change to the predicate line"); + assert!(!touches(hit, Some(&[4].into_iter().collect())), "the line between the attribute and the test"); + let lib = "#[cfg(\n target_os = \"macos\"\n)]\nmod child;\n"; + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let lines = declared_cfgs(lib, "src/lib.rs", &child).map(|(_, l)| l).unwrap_or_default(); + assert!(lines.contains(&2), "the predicate line of the declaration's cfg: {lines:?}"); + } + + #[test] + fn a_tests_folder_inside_src_is_a_module() { + assert_eq!(module_parent("crates/x/src/tests/child.rs").map(|(n, _)| n), Some("child")); + assert!(module_parent("crates/x/tests/it.rs").is_none(), "an integration test root"); + assert!(module_parent("crates/x/examples/demo.rs").is_none()); + let files: HashMap<&str, &str> = + [("crates/x/src/tests/mod.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/tests/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + assert!(module_cfgs(&["crates/x/src/tests/child.rs".to_owned()], &read).contains_key("crates/x/src/tests/child.rs")); + } + + #[test] + fn raw_path_attributes_load_their_file() { + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let both = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(unix)]\n#[path = r\"child.rs\"]\nmod alias;\n"; + assert_eq!(declared_cfgs(both, "src/lib.rs", &child).map(|(p, _)| p), Some(vec!["any(all(target_os=\"macos\"),all(unix))".to_owned()])); + let hashed = "#[path = r#\"child.rs\"#]\nmod alias;\n"; + assert_eq!(declared_cfgs(hashed, "src/lib.rs", &child).map(|(p, _)| p), Some(vec![])); + } + + #[test] + fn path_declarations_outside_the_module_directory_are_followed() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod platform;\n"), + ("crates/x/src/platform.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod imp;\n"), + ("crates/x/src/shared.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let all: Vec = files.keys().map(|k| (*k).to_owned()).collect(); + let edges = path_edges(&all, &read); + assert_eq!(edges.get("crates/x/src/shared.rs"), Some(&vec!["crates/x/src/platform.rs".to_owned()])); + let gates = module_gates_with(&["crates/x/src/shared.rs".to_owned()], &read, &edges); + assert_eq!(gates.get("crates/x/src/shared.rs").map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + let sibling = Loaded { path: "crates/x/src/shared.rs", name: "shared", chain: &[] }; + let ordinary = "mod shared;\n#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod mac_shared;\n"; + assert_eq!( + declared_cfgs(ordinary, "crates/x/src/platform.rs", &sibling).map(|(p, _)| p), + Some(vec!["target_os=\"macos\"".to_owned()]), + "`mod shared;` in platform.rs loads platform/shared.rs, not the sibling" + ); + let target: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/smoke.rs\"]\nmod smoke;\n"), + ("crates/x/tests/smoke.rs", ""), + ] + .into_iter() + .collect(); + let read_target = |p: &str| target.get(p).map(|s| (*s).to_owned()); + let target_files: Vec = target.keys().map(|k| (*k).to_owned()).collect(); + let target_cfgs: HashMap> = + module_gates_with(&["crates/x/tests/smoke.rs".to_owned()], &read_target, &path_edges(&target_files, &read_target)) + .into_iter() + .map(|(p, g)| (p, g.preds)) + .collect(); + let target_ctx = Ctx { module_cfgs: target_cfgs, ..ctx() }; + assert_eq!(hits_in("crates/x/tests/smoke.rs", never_run_test(), &target_ctx), [], "Cargo still runs the integration test"); + let present = ["crates/x/src/platform.rs".to_owned()]; + let mut chained = edges.clone(); + chained.insert("crates/x/src/inner.rs".to_owned(), vec!["crates/x/src/shared.rs".to_owned()]); + let (loaded, dirs) = path_loaded(&chained, &present, &["crates/x/src/platform/".to_owned()]); + assert!(loaded.contains("crates/x/src/shared.rs") && loaded.contains("crates/x/src/inner.rs"), "followed transitively: {loaded:?}"); + assert!(dirs.contains(&"crates/x/src/shared/".to_owned())); + let base = merge_edges(&edges_without(&edges, &present), HashMap::new()); + assert!(base.is_empty(), "the changed file's routes come from its base text"); + for file in ["mod.rs", "lib.rs", "main.rs"] { + let path = format!("crates/x/src/shared/{file}"); + let mut with_children = HashMap::new(); + with_children.insert(path.clone(), vec![present[0].clone()]); + with_children.insert("crates/x/src/elsewhere.rs".to_owned(), vec!["crates/x/src/shared/child.rs".to_owned()]); + let (loaded, dirs) = path_loaded(&with_children, &present, &[]); + assert!(loaded.contains(&path)); + assert!(dirs.contains(&"crates/x/src/shared/".to_owned()), "the module directory of {file}"); + assert!(loaded.contains("crates/x/src/elsewhere.rs"), "path declarations in children of {file} are followed"); + } + } + + #[test] + fn inline_path_declarations_keep_their_module_chain() { + for parent in ["crates/x/src/lib.rs", "crates/x/src/mod.rs", "crates/x/src/platform.rs"] { + let source = "#[cfg(target_os = \"macos\")]\nmod outer { mod inner { #[path = \"../../../shared.rs\"] mod shared; } }\n"; + let target = if parent.ends_with("platform.rs") { "crates/x/src/shared.rs" } else { "crates/x/shared.rs" }; + let read = |p: &str| (p == parent).then(|| source.to_owned()); + let edges = path_edges(&[parent.to_owned()], &read); + assert_eq!(edges.get(target), Some(&vec![parent.to_owned()]), "the inline directory under {parent}"); + let gates = module_gates_with(&[target.to_owned()], &read, &edges); + let gate = gates.get(target).unwrap(); + assert_eq!(gate.preds, ["target_os=\"macos\""], "the inline declaration's gate in {parent}"); + assert!(gate.sources.iter().any(|(p, lines)| p == parent && lines.contains(&1) && lines.contains(&2))); + let gated = Ctx { module_cfgs: gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + assert_eq!(hits_in(target, never_run_test(), &gated), [(2, "never-run")]); + } + } + + #[test] + fn deleted_parent_query_includes_renamed_away_paths() { + assert_eq!(deleted_diff_args("base-revision"), ["diff", "--name-only", "-z", "--diff-filter=D", "--no-renames", "base-revision"]); + assert_eq!(nul_paths("crates/x/src/plateforme-é.rs\0crates/x/src/a b.rs\0"), ["crates/x/src/plateforme-é.rs", "crates/x/src/a b.rs"]); + let edges: HashMap> = + [("crates/x/src/shared.rs".to_owned(), vec!["crates/x/src/bin/check.rs".to_owned()])].into_iter().collect(); + let deleted = ["crates/x/src/bin/check.rs".to_owned()]; + assert!(path_loaded(&edges, &deleted, &[]).0.contains("crates/x/src/shared.rs"), "a deleted parent's base route"); + let build: HashMap<&str, &str> = + [("apps/a/build.rs", "#[path = \"src/channel.rs\"]\nmod channel;\n"), ("apps/a/src/main.rs", "mod channel;\n")].into_iter().collect(); + let read_build = |p: &str| build.get(p).map(|s| (*s).to_owned()); + let build_files: Vec = build.keys().map(|k| (*k).to_owned()).collect(); + assert!(path_edges(&build_files, &read_build).is_empty(), "a build script is not a test route"); + } + + #[test] + fn routes_at_every_depth_are_kept() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod platform;\n"), + ("crates/x/src/main.rs", "mod platform {\n mod child;\n}\n"), + ("crates/x/src/platform.rs", "mod child;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let both = Ctx { module_cfgs: module_cfgs(&["crates/x/src/platform/child.rs".to_owned()], &read), ..ctx() }; + assert_eq!(hits_in("crates/x/src/platform/child.rs", never_run_test(), &both), [], "the binary's inline module runs it"); + let mac_only: HashMap<&str, &str> = files.iter().filter(|(k, _)| **k != "crates/x/src/main.rs").map(|(k, v)| (*k, *v)).collect(); + let read = |p: &str| mac_only.get(p).map(|s| (*s).to_owned()); + let library = Ctx { module_cfgs: module_cfgs(&["crates/x/src/platform/child.rs".to_owned()], &read), ..ctx() }; + assert_eq!(hits_in("crates/x/src/platform/child.rs", never_run_test(), &library), [(2, "never-run")]); + } + + #[test] + fn multiline_mirror_and_pixel_hits_cover_their_operands() { + let mirror = "#[test]\nfn t() {\n assert_eq!(\n scale(p, 2.0),\n scale(p, 1.0) * 2.0,\n \"message\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", mirror, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::Mirror).unwrap(); + assert!(touches(hit, Some(&[5].into_iter().collect())), "a change to the expected operand"); + assert!(!touches(hit, Some(&[6].into_iter().collect())), "a change to the message"); + let pixel = + "use egui::Rect;\n#[test]\nfn t() {\n assert_eq!(\n button_rect.min.x,\n 120.0,\n \"message\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", pixel, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::ExactPixel).unwrap(); + assert!(touches(hit, Some(&[6].into_iter().collect())), "a change to the expected operand"); + assert!(!touches(hit, Some(&[7].into_iter().collect())), "a change to the message"); + } + + #[test] + fn a_rect_width_difference_is_not_a_hard_coded_width() { + let ui = |body: &str| format!("use egui::Rect;\n#[test]\nfn t() {{\n {body}\n}}\n"); + assert_eq!(only("exact-pixel", &ui("assert_eq!(left_rect.width() - right_rect.width(), 0.0);")), []); + assert_eq!(only("exact-pixel", &ui("assert_eq!(left_rect.width(), 120.0);")), [(4, "exact-pixel")]); + assert_eq!(only("exact-pixel", &ui("assert_eq!(left_rect.min.x, 12.0);")), [(4, "exact-pixel")]); + assert_eq!(only("exact-pixel", &ui("assert_eq!(panels[0].rect.width(), 120.0);")), [(4, "exact-pixel")], "a rect reached through indexing"); + assert_eq!( + only("exact-pixel", &ui("assert_eq!(panels[i - 1].rect.width(), 120.0);")), + [(4, "exact-pixel")], + "arithmetic inside the receiver's index" + ); + assert_eq!(only("exact-pixel", &ui("assert_eq!(2.0 * rect.width(), 120.0);")), [], "arithmetic on the rect width"); + assert_eq!(only("exact-pixel", &ui("assert_eq!(panels[i - 1].rect.width() - right_rect.width(), 0.0);")), []); + assert_eq!(only("exact-pixel", &ui("assert_eq!(response().rect.width(), 120.0);")), [(4, "exact-pixel")], "a rect returned by a call"); + } + + #[test] + fn a_match_binding_shadows_the_outer_fixture_in_its_arm() { + let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => {}\n }\n}\n"; + assert_eq!(only("fixture-only", arm), []); + let after = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) => consume(m),\n None => {}\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the match"); + let label = + "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Row { n: actual } => assert_eq!(n, 0),\n _ => {}\n }\n}\n"; + assert_eq!(only("fixture-only", label), [(2, "fixture-only")], "a field label binds another name"); + } + + #[test] + fn reads_source_needs_a_path_read_of_a_known_rust_file() { + let rs = |call: &str| only("reads-source", &format!("#[test]\nfn t() {{\n let s = {call};\n assert!(s.contains(\"x\"));\n}}\n")); + assert_eq!(rs("fs::read_to_string(format!(\"{}.json\", \"snapshot.rs\")).unwrap()"), [], "a format argument is not the path"); + assert_eq!(rs("fs::read_to_string(\"sample.r s\").unwrap()"), [], "whitespace inside a literal is kept"); + assert_eq!(rs("fs::read_to_string(\"test data/sample.rs\").unwrap()"), [(3, "reads-source")]); + assert_eq!(rs("Read::read_to_string(&mut r, &mut String::from(\"seed.rs\")).unwrap()"), [], "an output buffer"); + assert_eq!(rs("r.read_to_string(&mut String::from(\"seed.rs\")).unwrap()"), [], "a reader method"); + assert_eq!(rs("std::fs::read_to_string(\"src/lib.rs\").unwrap()"), [(3, "reads-source")]); + assert_eq!(rs("fs::read_to_string(format!(\"src/{name}.rs\")).unwrap()"), [(3, "reads-source")], "a format string with a Rust suffix"); + assert_eq!( + rs("fs::read_to_string(format!(\"{}/{}\", root, \"src/lib.rs\")).unwrap()"), + [(3, "reads-source")], + "a value substituted at the end" + ); + let alias = "use std::fs as filesystem;\n#[test]\nfn t() {\n let s = filesystem::read_to_string(\"src/lib.rs\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", alias), [(4, "reads-source")], "an alias of std::fs"); + let tree = alias.replace("use std::fs as filesystem;", "use std::{fs as filesystem, io};"); + assert_eq!(only("reads-source", &tree), [(4, "reads-source")], "an alias in an import tree"); + let self_alias = alias.replace("use std::fs as filesystem;", "use std::fs::{self as filesystem, File};"); + assert_eq!(only("reads-source", &self_alias), [(4, "reads-source")], "a self alias in a filesystem import tree"); + let later_alias = alias.replace("use std::fs as filesystem;", "use std::{io as input, fs::{File, self as filesystem}};"); + assert_eq!(only("reads-source", &later_alias), [(4, "reads-source")], "a self alias after other imported names and aliases"); + let imported = "use std::fs::read_to_string;\n#[test]\nfn t() {\n let s = read_to_string(\"src/lib.rs\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", imported), [(4, "reads-source")]); + let glob = imported.replace("use std::fs::read_to_string;", "use std::fs::*;"); + assert_eq!(only("reads-source", &glob), [(4, "reads-source")], "a glob import"); + } } From 28559ec558340323d05043fe7806ece9ecd585fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:52:27 -0800 Subject: [PATCH 28/60] xtask: test-lint reads cfg_attr path routes, numeric literals, turbofish reads and spaced cfg strings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - never-run follows `#[cfg_attr(, path = "…")]` routes: a routed file loads under its condition (after earlier routes fail), the default or plain `#[path]` file loads only when no route applies, and path_edges follows the routed file. Path strings are split outside literals and their escapes decoded. - The census literal check accepts one numeric literal or fixed arithmetic on literals (`1`, `-2`, `1 << 4`); `1 + offset`, `1..limit` and `1usize - offset` count as another input. - reads-source skips a turbofish after `fs::read_to_string` (`::<&str>`). - cfg predicates keep whitespace inside string values (`"li nux"` is not `linux`), and a comma inside a string value no longer splits `any(…)`/`all(…)`. --- xtask/src/test_lint.rs | 249 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 236 insertions(+), 13 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 1a7731430a..5b2d45eba8 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -319,7 +319,11 @@ fn path_edges(files: &[String], read: &dyn Fn(&str) -> Option) -> HashMa continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + // A `cfg_attr` route loads its file when its condition holds. + let rels = path_attr(&m, src.as_bytes(), item, at) + .into_iter() + .chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, rel)| rel)); + for rel in rels { let target = path_target(parent, &inline_mods(&m, at), &rel); let parents = out.entry(target).or_default(); if !parents.contains(parent) { @@ -1753,11 +1757,30 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. // A minus sign makes a literal only in front of a number (`-2`, not `-offset`). let s = s.strip_prefix('-').unwrap_or(s); - s.is_empty() - || s.starts_with(['"', '\'', '|']) - || s.starts_with("move|") - || s.starts_with(|c: char| c.is_ascii_digit()) - || matches!(s, "true" | "false" | "None") + let mut start = 0; + let mut operands = 0; + let mut numeric = true; + for (i, c) in s.char_indices().chain([(s.len(), '+')]) { + if !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { + continue; + } + let head = &s[start..i]; + if i < s.len() + && matches!(c, '+' | '-') + && head + .strip_suffix(['e', 'E']) + .is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.bytes().all(|c| c.is_ascii_digit() || matches!(c, b'_' | b'.'))) + { + continue; + } + if !head.is_empty() { + operands += 1; + numeric &= numeric_literal(head); + } + start = i + c.len_utf8(); + } + let numeric = numeric && operands > 0; + s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None") }; (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { let mut start = name_end; @@ -1797,6 +1820,61 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { }) } +/// Whether the whitespace-free `s` is one numeric literal (`1`, `0x1F`, `2.5f32`, `1_000`, `1e-3`), not +/// an expression that starts with one (`1+offset`, `1..limit`). +fn numeric_literal(s: &str) -> bool { + let b = s.as_bytes(); + let radix = match b.get(..2) { + Some(b"0x") => 16, + Some(b"0o") => 8, + Some(b"0b") => 2, + _ => 10, + }; + let mut i = if radix == 10 { 0 } else { 2 }; + let mut digits = 0; + while let Some(&c) = b.get(i) { + if (c as char).is_digit(radix) { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 || !b.first().is_some_and(u8::is_ascii_digit) { + return false; + } + if radix == 10 { + if b.get(i) == Some(&b'.') { + i += 1; + if i < b.len() && !b[i].is_ascii_digit() { + return false; + } + while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'_') { + i += 1; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + let mut digits = 0; + while let Some(&c) = b.get(i) { + if c.is_ascii_digit() { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 { + return false; + } + } + } + matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") +} + /// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the /// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { @@ -3490,7 +3568,11 @@ fn reads_source_hits(file: &File) -> Vec { continue; } } - let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + let mut open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + if word == b"read_to_string" { + // A turbofish may follow the filesystem read: `fs::read_to_string::<&str>(path)`. + open = skip_turbofish(m, open); + } let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; // Whitespace inside a literal is part of the path (`"sample.r s"`). let arg = norm_outside_literals(&code[open + 1..close], &m[open + 1..close]); @@ -3922,7 +4004,8 @@ fn cfg_value(p: &str, t: &Target) -> Option { if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) { let mut parts = vec![]; let mut start = 0; - for at in top_level_at(args, ",").into_iter().chain([args.len()]) { + // A comma inside a string value does not split the arguments (`target_os = "a,unix"`). + for at in top_level_at(&String::from_utf8_lossy(&mask(args)), ",").into_iter().chain([args.len()]) { if at > start { parts.push(cfg_value(&args[start..at], t)); } @@ -4063,10 +4146,12 @@ fn cfg_attr_preds(text: &str, outer: Option<&str>) -> Vec { out } -/// A `cfg` predicate's source text without whitespace or comments. Masking would also blank the -/// string literals `target_os = "macos"` needs, so only comments are blanked. +/// A `cfg` predicate's source text without comments or the whitespace between tokens. Masking would +/// also blank the string literals `target_os = "macos"` needs, so only comments are blanked, and +/// whitespace inside a string literal is kept. fn pred_text(src: &[u8]) -> String { - norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) + let text = String::from_utf8_lossy(src); + norm_outside_literals(&mask_parts(&text, true, false), &mask(&text)) } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the @@ -4146,8 +4231,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => path_target(parent, want.chain, &rel) == want.path, + // The condition under which a `cfg_attr` route decides the file, when one does. + // Rust takes the first `path` attribute that applies, so only the routes before a plain + // `#[path]` can take its place. + let mut routed = None; + let direct = words(&m, b"path", item, at).into_iter().find_map(|w| path_attr(&m, src.as_bytes(), w, w + 4).map(|rel| (w, rel))); + let routes = cfg_attr_paths(&m, src.as_bytes(), item, direct.as_ref().map_or(at, |(w, _)| *w)); + let fallback = match &direct { + Some((_, rel)) => path_target(parent, want.chain, rel) == want.path, None => { // The default file of `mod name;`: `name.rs` or `name/mod.rs` under the declaring // module's directory and the inline modules around the declaration. @@ -4163,6 +4254,37 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, && [format!("{name}.rs"), format!("{name}/mod.rs")].iter().any(|f| join_path(&base, f) == want.path) } }; + let loads = if routes.is_empty() { + fallback + } else { + // The fallback file loads only when no route's condition holds. + let mut conds: Vec = routes + .iter() + .enumerate() + .filter(|(_, (_, rel))| path_target(parent, want.chain, rel) == want.path) + .map(|(i, (c, _))| { + if i == 0 { + c.clone() + } else { + let earlier = routes[..i].iter().map(|(c, _)| format!("not({c})")).collect::>(); + format!("all({},{c})", earlier.join(",")) + } + }) + .collect(); + if fallback { + let all: Vec<&str> = routes.iter().map(|(c, _)| c.as_str()).collect(); + conds.push(match all.as_slice() { + [one] => format!("not({one})"), + _ => format!("not(any({}))", all.join(",")), + }); + } + routed = match conds.len() { + 0 => None, + 1 => conds.pop(), + _ => Some(format!("any({})", conds.join(","))), + }; + routed.is_some() + }; if !loads { continue; } @@ -4172,6 +4294,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, // Every line of a multiline attribute counts. at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); + if let Some(cond) = routed { + preds.push(cond); + // The lines of the `cfg_attr` attributes that route the file. + for w in words(&m, b"cfg_attr", item, at) { + let open = skip_ws(&m, w + 8); + at_lines.extend(lines.of(w)..=lines.of(matching(&m, open).unwrap_or(w))); + } + } for (p, a, end) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); at_lines.extend(lines.of(a)..=lines.of(end)); @@ -4205,6 +4335,45 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { }) } +/// The `path = "…"` values inside the `#[cfg_attr(, …)]` attributes in `m[from..to]`, each +/// with its condition (`#[cfg_attr(unix, path = "x.rs")]` gives `("unix", "x.rs")`). A nested +/// `cfg_attr` joins its condition to the enclosing ones with `all(…)`. +fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { + fn walk(text: &str, outer: Option<&str>, out: &mut Vec<(String, String)>) { + // Commas and brackets inside a string literal do not split the arguments (`"mac,impl.rs"`). + let cuts = top_level_at(&String::from_utf8_lossy(&mask(text)), ","); + let Some(&first) = cuts.first() else { return }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(v) = arg.strip_prefix("path=") { + // An ordinary or raw string, with its escapes decoded: `"x.rs"`, `r#"x.rs"#`, `"\x6dac.rs"`. + if let Some(rel) = cfg_string(v) { + out.push((cond.clone(), rel)); + } + } else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) { + walk(n, Some(&cond), out); + } + start = cut + 1; + } + } + let mut out = vec![]; + for at in words(m, b"cfg_attr", from, to) { + let before = m[..at].trim_ascii_end(); + if !before.strip_suffix(b"[").is_some_and(|h| h.trim_ascii_end().ends_with(b"#") && !h.trim_ascii_end().ends_with(b"#!")) { + continue; + } + let open = skip_ws(m, at + 8); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + walk(&pred_text(&src[open + 1..close]), None, &mut out); + } + out +} + /// `rel` joined to the directory `base`, with `.` and `..` resolved. fn join_path(base: &str, rel: &str) -> String { let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); @@ -4526,6 +4695,27 @@ mod tests { assert_eq!(census(derived), [(2, "census")]); let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n"; assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip"); + let fixed_arg = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1), Some(k));\n assert_eq!(Kind::from_id(k.id(), -2), Some(k));\n }\n}\n"; + assert_eq!(census(fixed_arg), [(2, "census")], "a numeric literal is not another input"); + let shifted = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1 << 4), Some(k));\n }\n}\n"; + assert_eq!(census(shifted), [(2, "census")], "fixed arithmetic is not another input"); + let offset = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1 + offset), Some(k));\n }\n}\n"; + assert_eq!(census(offset), [], "an expression that only starts with a digit is another input"); + let suffixed = + "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1usize - offset), Some(k));\n }\n}\n"; + assert_eq!(census(suffixed), [], "a suffixed number minus a variable is another input"); + let range = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1..limit), Some(k));\n }\n}\n"; + assert_eq!(census(range), [], "a range with a variable bound is another input"); + } + + #[test] + fn numeric_literals_are_one_token() { + for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] { + assert!(numeric_literal(s), "{s}"); + } + for s in ["1+offset", "1..limit", "1usize-offset", "1<<4"] { + assert!(!numeric_literal(s), "{s}"); + } } #[test] @@ -6329,6 +6519,10 @@ mod tests { fn reads_source_covers_read_to_string_of_rust_files() { let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", read), [(3, "reads-source")]); + let turbofish = "#[test]\nfn t() {\n let s = fs::read_to_string::<&str>(\"src/lib.rs\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", turbofish), [(3, "reads-source")], "a turbofish before the argument"); + let suffix = "#[test]\nfn t() {\n assert!(rendered.ends_with::<&str>(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", suffix), [], "a string suffix check"); let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", data), []); let comment = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"input.rs\" */ \"data.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; @@ -6432,8 +6626,11 @@ mod tests { assert_eq!(cfg_value("target_os=r#\"lin\\x75x\"#", t), Some(false), "raw contents are kept"); assert_eq!(cfg_value("target_os=\"lin\\qux\"", t), None, "an escape this does not decode"); assert_eq!(cfg_value("target_os=\"macos\"", t), Some(false)); + assert_eq!(cfg_value("any(target_os=\"foo,unix,bar\")", t), Some(false), "a comma inside a string value"); let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", escaped), []); + let spaced = "#[cfg(target_os = \"li nux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", spaced), [(3, "never-run")], "whitespace inside a string value is kept"); } #[test] @@ -6469,6 +6666,32 @@ mod tests { assert_eq!(declared_cfgs(hashed, "src/lib.rs", &child).map(|(p, _)| p), Some(vec![])); } + #[test] + fn cfg_attr_path_attributes_load_their_file() { + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let declared = |src: &str| declared_cfgs(src, "src/lib.rs", &child).map(|(p, _)| p); + let routed = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg_attr(unix, path = \"child.rs\")]\nmod alias;\n"; + assert_eq!(declared(routed), Some(vec!["any(all(target_os=\"macos\"),all(unix))".to_owned()])); + let away = "#[cfg_attr(target_os = \"macos\", path = \"mac_child.rs\")]\nmod child;\n"; + assert_eq!(declared(away), Some(vec!["not(target_os=\"macos\")".to_owned()]), "the default file loads only when the condition fails"); + let comma = Loaded { path: "src/mac,impl.rs", name: "imp", chain: &[] }; + let routed = "#[cfg_attr(target_os = \"macos\", path = \"mac,impl.rs\")]\nmod imp;\n"; + assert_eq!(declared_cfgs(routed, "src/lib.rs", &comma).map(|(p, _)| p), Some(vec!["target_os=\"macos\"".to_owned()]), "a comma in the path"); + let escaped = "#[cfg_attr(unix, path = \"\\x63hild.rs\")]\nmod alias;\n"; + assert_eq!(declared(escaped), Some(vec!["unix".to_owned()]), "an escape in the path is decoded"); + let ordered = "#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\n#[path = \"child.rs\"]\nmod alias;\n"; + assert_eq!(declared(ordered), Some(vec!["not(target_os=\"macos\")".to_owned()]), "an earlier route takes the place of a plain path"); + let routes = "#[cfg_attr(unix, path = \"unix.rs\")]\n#[cfg_attr(target_os = \"linux\", path = \"child.rs\")]\nmod alias;\n"; + assert_eq!(declared(routes), Some(vec!["all(not(unix),target_os=\"linux\")".to_owned()])); + let later = "#[path = \"child.rs\"]\n#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\nmod alias;\n"; + assert_eq!(declared(later), Some(vec![]), "a route after a plain path never applies"); + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\nmod imp;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let edges = path_edges(&["crates/x/src/lib.rs".to_owned()], &read); + assert_eq!(edges.get("crates/x/src/mac.rs"), Some(&vec!["crates/x/src/lib.rs".to_owned()])); + } + #[test] fn path_declarations_outside_the_module_directory_are_followed() { let files: HashMap<&str, &str> = [ From 7fcf87a1fa56cf16455b03e0802d9906285503e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:42:55 -0800 Subject: [PATCH 29/60] xtask: test-lint follows every module route and binding scope - never-run: a parent edit now counts for a child file when its module gates differ from the base, so deleting the last unconditional `mod` declaration fails the check; a deleted parent file counts too. - never-run: the base verdicts are computed once per file and matched by test name and line, so `a::smoke` already off does not hide `b::smoke`. - never-run: each load route joins its own declaration and ancestor gates, and the routes join with `any`; `#[cfg_attr(, path = "...")]` loads the other file only under its condition; every line of a multi-line `cfg` counts as a change. - no-assertion: a helper passed as an argument is shadowed only by a binding in scope at that argument, including `for` patterns and closure parameters; a tuple that is dropped or bound to `_` does not count, and a name in a `let` pattern is not a passed value. - census: `if { panic!(...) }` that rejects input is a check. - all-unguarded: a shared borrow passed to a call between the pinning assertion and `.all(...)` may change the items. - all-unguarded: `mut app: &App` parameters are read by their name, and a function with a pattern parameter is not fixed-table evidence. - reads-source: only the literal the path ends in names the file, so `root.join("fixtures.rs").join(name)` is not a Rust source read. - fixture-only: a `match` arm pattern shadows an outer binding inside that arm. - exact-pixel: a rect read passed to a call is the call's input. - Docs: list every report-only rule and the enclosing-gate exception. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 653 ++++++++++++++++++++++++++++++++++------- 2 files changed, 556 insertions(+), 99 deletions(-) diff --git a/docs/development.md b/docs/development.md index c833a400e8..359da987d2 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, and an environment variable that no CI leg sets. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, a loop or `.all(…)` over every entry of a table that checks only presence (`census`), a comparison of a function with a second call of itself (`mirror`), an assertion of a constant or literal the test or crate states (`constant-echo`), an assertion on only the input the test built (`fixture-only`), and a UI test that compares a rect with numbers written out (`exact-pixel`). The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, with one exception: a change to a `mod` declaration or a `cfg` attribute on it, or the removal of a `mod` declaration, fails `never-run` for a test in an unchanged file below it when the change takes that test out of every CI test build. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 677c84b16f..e31150df25 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -276,6 +276,29 @@ fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap, then: Option<&Gates>, changed: &BTreeMap>>) -> bool { + let preds = |g: Option<&Gates>| g.map(|g| g.preds.clone()).unwrap_or_default(); + gate_changed(now, changed) || preds(now) != preds(then) +} + +/// The `never-run` tests in `src` under the module gates of `ctx`, by test name and `fn` line, so two +/// tests with one name in different modules of the file stay apart. +fn never_run_at(path: &str, src: &str, ctx: &Ctx) -> NeverRunSet { + lint_file(path, src, ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() +} + +/// The tests in `src` that run in CI under the base's gates and that the current gates turn off. +/// The base verdicts are computed once for the file. +fn newly_off(path: &str, src: &str, ctx: &Ctx, base: &Ctx) -> Vec { + let before = never_run_at(path, src, base); + lint_file(path, src, ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && !before.contains(&(h.test.clone(), h.line))).collect() +} + +type NeverRunSet = HashSet<(String, usize)>; + /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. fn read_small(root: &Path, path: &str) -> Option { let full = root.join(path); @@ -303,8 +326,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn // their tests off without a change to them. - let module_dirs: Vec = present - .iter() + // A deleted file counts too: its `mod` declarations were routes to the files below it. + let module_dirs: Vec = changed + .keys() .map(|p| { let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } @@ -319,16 +343,19 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // The gates the parent declarations gave at the base: a parent edit counts against a child's // test only when the test ran in CI before it. let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + let base_gates = module_gates(&gated, &read_base); + let moved = |p: &str| gates_moved(gates.get(p), base_gates.get(p), &changed); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = moved(&path); + let mut base_off = None; for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) - || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) + || (hit.rule == Rule::NeverRun + && parent_changed + && !base_off.get_or_insert_with(|| never_run_at(&path, &src, &base_ctx)).contains(&(hit.test.clone(), hit.line))) { counted.push(hit); } else { @@ -336,9 +363,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + for path in below.iter().filter(|p| moved(p)) { let Some(src) = read_small(root, path) else { continue }; - counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); + counted.extend(newly_off(path, &src, &ctx, &base_ctx)); } finish(&counted, older, present.len(), &base) } @@ -1263,7 +1290,9 @@ fn definition(m: &[u8], at: usize) -> Option { .into_iter() .filter(|(_, method)| !method) .map(|(n, _)| n) - .chain(passed_names(m, open, close).into_iter().filter(|name| !shadows_helper(m, at, open, close, name.as_bytes()))) + .chain( + passed_names(m, open, close).into_iter().filter(|(name, pos)| !shadows_helper(m, at, open, close, name.as_bytes(), *pos)).map(|(n, _)| n), + ) .collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1386,18 +1415,100 @@ struct View<'a> { /// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings /// and parameters that shadow helper names. fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { - passed_names(m, t.open, t.close).into_iter().any(|name| { - name != t.name && !COMMON.contains(&name.as_str()) && helpers.contains(&name) && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes()) + passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| { + name != t.name + && !COMMON.contains(&name.as_str()) + && helpers.contains(&name) + && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos) }) } -/// Whether a local binding or parameter between `at` and `close` shadows the helper `name`. -fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8]) -> bool { - let_binds(&m[open + 1..close], name) || binds_parameter(&m[at..close], name) +/// Whether a parameter of the function at `at` (body `open..close`), or a local binding in scope at +/// `pos`, shadows the helper `name`. +fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8], pos: usize) -> bool { + binds_parameter(&m[at..=open], name) || bound_at(&m[open + 1..close], name, pos - (open + 1)) } -/// The bare identifiers passed as arguments or tuple elements in the body between `open` and `close`. -fn passed_names(m: &[u8], open: usize, close: usize) -> Vec { +/// Whether a binding of `name` in `body` is in scope at `pos`: a `let` from the end of its statement +/// to the end of its block (an `if let` or `while let` in its block only), a `for` pattern in the +/// loop body, or a closure parameter in the brackets that hold the closure. +fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { + let lets = words(body, b"let", 0, pos).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + if words(body, name, start, end).is_empty() { + return false; + } + let head = body[..at].trim_ascii_end(); + let conditional = + [&b"if"[..], b"while"].into_iter().any(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); + if conditional { + return let_body(body, start).is_some_and(|(open, close)| open < pos && pos < close); + } + statement_end(body, at) < pos && pos < block_close(body, at) + }); + let loops = words(body, b"for", 0, pos).into_iter().any(|at| { + let Some((open, close)) = let_body(body, at + 3) else { return false }; + let Some(&in_at) = words(body, b"in", at + 3, open).first() else { return false }; + open < pos && pos < close && !words(body, name, at + 3, in_at).is_empty() + }); + lets || loops || closure_binds(body, name, pos) +} + +/// Whether a closure before `pos` takes a parameter that binds `name`, and `pos` lies inside the +/// innermost brackets around the closure (`keeping(|body| keeping(body))`). +fn closure_binds(body: &[u8], name: &[u8], pos: usize) -> bool { + let mut at = 0; + while at < pos { + let head = body[..at].trim_ascii_end(); + let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); + if body[at] == b'|' && opens { + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + let binds = split_args(body, at + 1, close).into_iter().any(|(start, end)| { + let pattern = &body[start..end]; + let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); + !words(pattern, name, 0, end).is_empty() + }); + if binds && close < pos { + let group = enclosing_open(body, at).and_then(|o| matching(body, o)).unwrap_or(body.len()); + if pos < group { + return true; + } + } + at = close; + } + at += 1; + } + false +} + +/// The innermost unclosed `(`, `[` or `{` before `at`. +fn enclosing_open(m: &[u8], at: usize) -> Option { + let mut depth = 0usize; + for i in (0..at).rev() { + match m[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => return Some(i), + b'(' | b'[' | b'{' => depth -= 1, + _ => {} + } + } + None +} + +/// The bare identifiers, with their offsets, passed as arguments or as tuple or array elements in +/// the body between `open` and `close`. An element of a tuple or array counts only where its value +/// is kept: not in a statement of its own (`(body,);`) or a `let _` or `let _name` binding. +fn passed_names(m: &[u8], open: usize, close: usize) -> Vec<(String, usize)> { let mut names = Vec::new(); let mut at = open + 1; while at < close { @@ -1408,14 +1519,38 @@ fn passed_names(m: &[u8], open: usize, close: usize) -> Vec { let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); let before = m[..at].trim_ascii_end().last().copied(); let after = m.get(skip_ws(m, end)).copied(); - if matches!(before, Some(b'(' | b',')) && matches!(after, Some(b')' | b',')) { - names.push(String::from_utf8_lossy(&m[at..end]).into_owned()); + if matches!(before, Some(b'(' | b',')) && matches!(after, Some(b')' | b',')) && value_kept(m, open, at) { + names.push((String::from_utf8_lossy(&m[at..end]).into_owned(), at)); } at = end; } names } +/// Whether the element at `at` is a call's argument, or sits in a tuple or array whose statement +/// keeps it ([`passed_names`]). +fn value_kept(m: &[u8], open: usize, at: usize) -> bool { + let Some(group) = enclosing_open(m, at).filter(|&g| g > open) else { return false }; + // A name in a `let` or `for` pattern (`let (body,) = …`) binds a value rather than passing one. + let from = m[open + 1..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(open + 1, |p| open + 2 + p); + if words(m, b"let", from, at).last().is_some_and(|&l| !m[l..at].contains(&b'=')) + || words(m, b"for", from, at).last().is_some_and(|&f| words(m, b"in", f, at).is_empty()) + { + return false; + } + let head = m[..group].trim_ascii_end(); + if m[group] != b'{' && head.last().is_some_and(|&c| is_ident(c) || c == b'!' || c == b'>') { + return true; + } + let statement = m[..group].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let statement = m[statement..group + 1].trim_ascii_start(); + if matches!(statement.first(), Some(b'(' | b'[')) { + return false; + } + // `let _ = …` and `let _name = …` drop or ignore the value. + !statement.strip_prefix(b"let").filter(|r| r.first().is_some_and(u8::is_ascii_whitespace)).is_some_and(|r| r.trim_ascii_start().starts_with(b"_")) +} + /// Whether a function or closure in `body` takes a parameter that binds `name`. fn binds_parameter(body: &[u8], name: &[u8]) -> bool { let binds = |from, to| { @@ -1592,6 +1727,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let body = &unmessaged[from - v.t.open..to - v.t.open]; helpers_in(from, to).is_empty() && !rejects(body) + && !panic_rejects(body) && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) }; @@ -1704,6 +1840,41 @@ fn rejects(body: &[u8]) -> bool { contains(&tight, b".unwrap_err()") || contains(&tight, b".expect_err(") } +/// Whether `body` holds an `if { panic!(…) }` that checks more than presence: it works as +/// `assert!(!)`, so `if accepts(c.invalid) { panic!(…) }` checks a rejection, while +/// `if parse(c).is_err() { panic!(…) }` or `if let Err(_) = parse(c) { panic!(…) }` only enforces +/// success. +fn panic_rejects(body: &[u8]) -> bool { + words(body, b"panic", 0, body.len()).into_iter().any(|at| { + if body.get(skip_ws(body, at + 5)) != Some(&b'!') { + return false; + } + let Some(open) = enclosing_open(body, at).filter(|&o| body[o] == b'{') else { return false }; + let Some(&kw) = words(body, b"if", 0, open).last() else { return false }; + let raw = &body[kw + 2..open]; + if raw.iter().any(|c| matches!(c, b';' | b'{' | b'}')) { + return false; + } + let cond = norm(raw); + if let Some(pattern) = cond.strip_prefix("let") { + // `if let Ok(_) = …` and `if let Some(_) = …` panic on success. + return pattern.starts_with("Ok(") || pattern.starts_with("Some("); + } + let negated = if !top_level_at(&cond, "&&").is_empty() || !top_level_at(&cond, "||").is_empty() { + format!("!({cond})") + } else if let Some(rest) = cond.strip_prefix('!') { + rest.to_owned() + } else if let Some(rest) = cond.strip_suffix(".is_err()") { + format!("{rest}.is_ok()") + } else if let Some(rest) = cond.strip_suffix(".is_none()") { + format!("{rest}.is_some()") + } else { + format!("!{cond}") + }; + !weak_predicate(&negated) + }) +} + /// The `{` that opens a `for` loop's body: the first one outside brackets after `from`. fn loop_open(m: &[u8], from: usize, to: usize) -> Option { let mut i = from; @@ -2052,7 +2223,18 @@ fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { let rest = norm(&body[at..statement_end(body, at)]); let head = body[..at].trim_ascii_end(); - let shared = head.ends_with(b"&") && !head.ends_with(b"&&"); + // A shared borrow reads the value in an assertion or a named binding; passed to a call in a + // statement of its own (`reset(&r);`), it may change what an interior-mutable value holds. + let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let raw = body[statement..at].trim_ascii_start(); + let macro_name = &raw[..raw.iter().take_while(|&&c| is_ident(c)).count()]; + let assertion = raw.get(macro_name.len()) == Some(&b'!') + && PLAIN_ASSERTS.iter().any(|p| macro_name.strip_prefix(p.as_bytes()).is_some_and(|r| r.is_empty() || r.starts_with(b"_"))); + let named_let = raw.starts_with(b"let") + && raw.get(3).is_some_and(u8::is_ascii_whitespace) + && !matches!(raw[3..].trim_ascii_start(), [b'_', c, ..] if !is_ident(*c)); + let checked = assertion || named_let; + let shared = head.ends_with(b"&") && !head.ends_with(b"&&") && checked; let getter = rest .strip_prefix(name) .and_then(|r| r.strip_prefix('.')) @@ -2105,10 +2287,21 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; let signature = norm(&file[params_close + 1..body_open]); let return_type = signature.strip_prefix("->").unwrap_or(""); - let refs: Vec = split_args(file, params_open + 1, params_close) - .into_iter() - .filter_map(|(f, t)| norm(&file[f..t]).split_once(':').filter(|(_, ty)| ty.starts_with('&')).map(|(n, _)| n.to_owned())) - .collect(); + // The binding name of each reference parameter, `app` of `mut app: &App`; a parameter whose + // pattern is not a plain name leaves the function out. + let mut refs: Vec = vec![]; + for (f, t) in split_args(file, params_open + 1, params_close) { + let param = String::from_utf8_lossy(&file[f..t]); + let Some((pattern, ty)) = param.split_once(':') else { return false }; + let pattern = pattern.trim(); + let pattern = pattern.strip_prefix("mut").filter(|r| r.starts_with(char::is_whitespace)).map_or(pattern, str::trim_start); + if !plain_local(pattern) { + return false; + } + if norm(ty.as_bytes()).starts_with('&') { + refs.push(pattern.to_owned()); + } + } let body = norm(&file[body_open + 1..body_close]); let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); let table = &body[..table_end]; @@ -3343,9 +3536,10 @@ fn reads_source_hits(file: &File) -> Vec { let literal = raw.unwrap_or(&arg); let rs = match word { b"ends_with" => literal == "\".rs\"", - // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, - // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + // The literal at the end of the path names the file read: `root.join("src/lib.rs")`, + // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")` or + // `root.join("fixtures.rs").join(name)`. + b"read_to_string" => terminal_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3359,11 +3553,61 @@ fn reads_source_hits(file: &File) -> Vec { out } -/// The last string literal in a (whitespace-free) expression, quotes included. -fn last_literal(arg: &str) -> Option<&str> { - let close = arg.rfind('"')?; - let open = arg[..close].rfind('"')?; - Some(&arg[open..=close]) +/// The string literal a (whitespace-free) path expression ends in, quotes included: the expression +/// itself, the last argument of its last call (`root.join("src/lib.rs")`, `concat!(…, "/x.rs")`), +/// the template of `format!`, or the receiver of a call without arguments (`"x.rs".to_owned()`). +/// `None` when that part is not a literal (`root.join(name)`). +fn terminal_literal(arg: &str) -> Option<&str> { + let arg = arg.trim_start_matches('&').trim_end_matches(','); + let literal = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')).unwrap_or(arg); + let b = literal.as_bytes(); + if b.len() >= 2 && b[0] == b'"' && b[b.len() - 1] == b'"' { + // One literal only, not `"a"+"b"`: its first closing quote is the last byte. + let mut i = 1; + while i < b.len() - 1 && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + return (i == b.len() - 1).then_some(literal); + } + let b = arg.as_bytes(); + let (mut depth, mut in_str, mut i) = (0usize, false, 0usize); + let (mut last_open, mut commas) = (None, vec![]); + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + match c { + b'"' => in_str = true, + b'(' | b'[' | b'{' => { + if depth == 0 && c == b'(' { + last_open = Some(i); + commas.clear(); + } + depth += 1; + } + b')' | b']' | b'}' => depth = depth.checked_sub(1)?, + b',' if depth == 1 => commas.push(i), + _ => {} + } + } + i += 1; + } + let open = last_open.filter(|_| depth == 0 && b.last() == Some(&b')'))?; + let close = b.len() - 1; + let starts = std::iter::once(open + 1).chain(commas.iter().map(|c| c + 1)); + let ends = commas.iter().copied().chain([close]); + let pieces: Vec<&str> = starts.zip(ends).map(|(s, e)| &arg[s..e]).filter(|p| !p.is_empty()).collect(); + let head = &arg[..open]; + let Some(&last) = pieces.last() else { + let method = head.trim_end_matches(|c: char| c.is_ascii_alphanumeric() || c == '_'); + return method.strip_suffix('.').and_then(terminal_literal); + }; + terminal_literal(if head.ends_with("format!") { pieces[0] } else { last }) } // ---- Mirrors, echoes, never-run tests and exact pixels ---- @@ -3520,13 +3764,56 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), (None, _) => found.map(|(init, _)| init), } } +/// Where the pattern starts of the innermost `match` arm that holds `before` and binds `name`. +fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { + words(body, b"match", 0, before) + .into_iter() + .filter_map(|at| { + let (open, close) = let_body(body, at + 5)?; + if !(open < before && before < close) { + return None; + } + // Walk the arms at the top of the match body to the one `before` is in. + let (mut depth, mut start, mut pattern) = (0usize, open + 1, None); + let mut i = open + 1; + while i < before { + match body[i] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' => depth = depth.saturating_sub(1), + b'}' => { + depth = depth.saturating_sub(1); + // A block arm ends at its `}` when no `,` follows. + if depth == 0 && pattern.is_some() && !matches!(body.get(skip_ws(body, i + 1)), Some(b',' | b'.' | b'?')) { + (start, pattern) = (i + 1, None); + } + } + b'=' if depth == 0 && pattern.is_none() && body.get(i + 1) == Some(&b'>') => { + pattern = Some((start, i)); + i += 1; + } + b',' if depth == 0 && pattern.is_some() => (start, pattern) = (i + 1, None), + _ => {} + } + i += 1; + } + let (from, to) = pattern?; + let text = String::from_utf8_lossy(&body[from..to]); + // The guard reads names; only the pattern binds them. + let pat = text.split_once(" if ").map_or(text.as_ref(), |(p, _)| p); + (!words(pat.as_bytes(), name.as_bytes(), 0, pat.len()).is_empty()).then_some(skip_ws(body, from)) + }) + .max() +} + /// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { let mut found = None; @@ -3770,8 +4057,8 @@ fn pred_text(src: &[u8]) -> String { } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the -/// offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { @@ -3787,7 +4074,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - out.push((pred, at)); + out.push((pred, at, end)); } } out @@ -3834,32 +4121,47 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => { - // A `#[path]` outside inline modules is relative to the file's directory; inside them, - // to the inline modules' directory under the file's module. - let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { - base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); - } - for seg in want.chain { - base = join_path(&base, seg); - } - join_path(&base, &rel) == want.path + // A `#[path]` outside inline modules is relative to the file's directory; inside them, to + // the inline modules' directory under the file's module. + let resolves = |rel: &str| { + let mut base = dir.to_owned(); + if !want.chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); } + for seg in want.chain { + base = join_path(&base, seg); + } + join_path(&base, rel) == want.path + }; + let default = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => resolves(&rel), None => &m[start..end] == want.name.as_bytes(), }; - if !loads { - continue; - } + // `#[cfg_attr(, path = "…")]` loads the other file only when the condition holds. + let conditional = cfg_path_attr(&m, src.as_bytes(), item, at); + let gate = match &conditional { + Some((cond, rel, _, _)) => match (resolves(rel), default) { + (true, true) => None, + (true, false) => Some(cond.clone()), + (false, true) => Some(format!("not({cond})")), + (false, false) => continue, + }, + None if default => None, + None => continue, + }; // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); + // Every line of an attribute counts, so an edit to the value line of a multi-line `cfg` does. + let span = |from: usize, to: usize| lines.of(from)..=lines.of(to); at_lines.push(lines.of(at)); - at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); - let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); - for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + at_lines.extend(attrs.iter().flat_map(|a| span(a.at, a.end))); + if let Some((_, _, from, to)) = conditional { + at_lines.extend(span(from, to)); + } + let mut preds: Vec = attrs.into_iter().map(|a| a.pred).chain(gate).collect(); + for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); - at_lines.push(lines.of(a)); + at_lines.extend(span(a, e)); } each.push(preds); } @@ -3885,6 +4187,27 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { }) } +/// The condition and path of a `#[cfg_attr(, path = "…")]` attribute in `m[from..to]`, +/// with the offsets of its `cfg_attr` and closing `]`. +fn cfg_path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<(String, String, usize, usize)> { + words(m, b"cfg_attr", from, to).into_iter().find_map(|at| { + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + let open = skip_ws(m, at + "cfg_attr".len()); + let close = (attr && m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten()?; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') { + return None; + } + let text = pred_text(&src[open + 1..close]); + let cuts = top_level_at(&text, ","); + let &first = cuts.first()?; + let starts = cuts.iter().map(|c| c + 1); + let ends = cuts[1..].iter().copied().chain([text.len()]); + let rel = starts.zip(ends).find_map(|(s, e)| text.get(s..e)?.strip_prefix("path=\"")?.strip_suffix('"').map(str::to_owned))?; + Some((text[..first].to_owned(), rel, at, end)) + }) +} + /// `rel` joined to the directory `base`, with `.` and `..` resolved. fn join_path(base: &str, rel: &str) -> String { let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); @@ -3937,57 +4260,66 @@ struct Gates { fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } - if !gates.preds.is_empty() { - out.insert(path.clone(), gates); + let mut sources = vec![]; + let preds = route_preds(path, read, &mut sources, 0); + if !preds.is_empty() { + out.insert(path.clone(), Gates { preds, sources }); } } out } +/// The predicates under which the module file `at` is loaded. Every file that loads it is another +/// way in (a library and a binary root can both load it): each route joins the gates of its own +/// declaration with those of the file that holds it, and the routes join into one `any(all(…), …)`, +/// so its tests are off only when every route leaves them out. The lines of each declaration go to +/// `sources`. +fn route_preds(at: &str, read: &dyn Fn(&str) -> Option, sources: &mut Vec<(String, Vec)>, depth: usize) -> Vec { + if depth >= 16 { + return vec![]; + } + let Some((name, mut candidates)) = module_parent(at) else { return vec![] }; + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + return vec![]; + }; + let mut chain: Vec = vec![]; + for _ in 0..4 { + let want = Loaded { path: at, name, chain: &chain }; + let found: Vec<_> = candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); + if !found.is_empty() { + let mut routes: Vec> = vec![]; + for (parent, (mut preds, lines)) in found { + sources.push((parent.clone(), lines)); + preds.extend(route_preds(&parent, read, sources, depth + 1)); + routes.push(preds); + } + return match routes.len() { + 1 => routes.pop().unwrap_or_default(), + _ if routes.iter().any(Vec::is_empty) => vec![], + _ => vec![format!("any({})", routes.iter().map(|r| format!("all({})", r.join(","))).collect::>().join(","))], + }; + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { return vec![] }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { return vec![] }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + vec![] +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); // A change to an attribute that turns the test off counts as a change to the test. - let attr_lines: Vec = local.iter().map(|&(_, at)| v.file.lines.of(at)).collect(); - let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); + // Every line of a multi-line attribute counts. + let attr_lines: Vec = local.iter().flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect(); + let mut preds: Vec = local.into_iter().map(|(p, _, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -4034,15 +4366,25 @@ fn names_rect(op: &str) -> bool { return false; } let b = op.as_bytes(); + // For each open parenthesis, whether it opens a call's arguments rather than a tuple or group. + let mut calls: Vec = vec![]; let mut i = 0; while i < b.len() { + match b[i] { + b'(' => calls.push(i > 0 && (is_ident(b[i - 1]) || b[i - 1] == b'!' || b[i - 1] == b'>')), + b')' => { + calls.pop(); + } + _ => {} + } if !is_ident(b[i]) || (i > 0 && is_ident(b[i - 1])) { i += 1; continue; } let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); let w = &op[i..end]; - if w == "rect" || w.starts_with("rect_") || w.ends_with("_rect") { + // A rect read inside a call's arguments (`bucket(rect.min.x)`) is the call's input, not the operand. + if (w == "rect" || w.starts_with("rect_") || w.ends_with("_rect")) && !calls.contains(&true) { let mut after = end; if b.get(after) == Some(&b'(') { after = matching(b, after).map_or(b.len(), |c| c + 1); @@ -4256,6 +4598,12 @@ mod tests { assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish"); let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n"; assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success"); + let panics = "#[test]\nfn t() {\n for c in CASES {\n assert!(c.valid.is_some());\n if accepts(c.invalid) {\n panic!(\"accepted invalid input\");\n }\n }\n}\n"; + assert_eq!(census_in(panics, &ctx()), [], "a panic when invalid input is accepted checks a rejection"); + for enforcing in ["parse(c.valid).is_err()", "!parse(c.valid).is_ok()", "let Err(_) = parse(c.valid)"] { + let src = panics.replace("accepts(c.invalid)", enforcing); + assert_eq!(census_in(&src, &ctx()), [(2, "census")], "{enforcing}: a panic that only enforces success"); + } let mapped = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| { verify_entry(c); c }).all(|c| c.is_some()));\n}\n"; assert_eq!(census_in(mapped, &ctx()), [], "a helper in the .all(…) receiver runs for every entry"); assert_eq!(census_in(&mapped.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]); @@ -5604,6 +5952,20 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); let parameter = src.replace("fn t()", "fn t(body: fn())"); assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); + let later = src.replace(" keeping(body);", " keeping(body);\n {\n let body = || {};\n let _ = body;\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &later, &ctx), [], "a binding in a later block does not reach the call"); + let after = src.replace(" keeping(body);", " keeping(body);\n let body = || {};\n let _ = body;"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "a binding after the call"); + let looped = src.replace(" keeping(body);", " for body in [|| {}] {\n keeping(body);\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &looped, &ctx), [(8, "no-assertion")], "a loop pattern shadows the helper in the loop body"); + let after_loop = src.replace(" keeping(body);", " for body in [|| {}] {\n let _ = body;\n }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after_loop, &ctx), [], "the helper after the loop"); + let unused = src.replace(" keeping(body);", " let _unused = (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "a tuple that is never called"); + let dropped = src.replace(" keeping(body);", " (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a tuple in a statement of its own"); + let table = src.replace(" keeping(body);", " let cases = [(\"case\", body)];\n run(&cases);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &table, &ctx), [], "a table of named cases"); let idle = src.replace("assert_eq!(f(), 1);", "f();"); let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); @@ -5628,6 +5990,10 @@ mod tests { assert_eq!(hits(&early), [(6, "all-unguarded")], "the receiver changed between the binding and the assertion"); let taken = pinned.replace(" assert!(r.items()", " assert!(r.take_items().is_some());\n assert!(r.items()"); assert_eq!(hits(&taken), [(6, "all-unguarded")], "an assertion changes the receiver after the pinning assertion"); + let reset = pinned.replace(" assert!(r.items()", " reset(&r);\n assert!(r.items()"); + assert_eq!(hits(&reset), [(6, "all-unguarded")], "a shared borrow passed to a call may change interior-mutable items"); + let bound = pinned.replace(" assert!(r.items()", " let n = count(&r);\n assert!(r.items()"); + assert_eq!(hits(&bound), [], "a shared borrow read into a binding"); let counted = pinned.replace(" assert!(r.items()", " assert_eq!(r.unhandled_rejection_count(), 2);\n assert!(r.items()"); assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); @@ -5652,6 +6018,10 @@ mod tests { assert_eq!(hits(&shadowed), [(8, "all-unguarded")], "a local binding shadows the file's function"); let state = src.replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); assert_eq!(hits(&state), [(7, "all-unguarded")], "a filter on the state the test builds"); + let mut_ref = src.replace("app: &App", "mut app: &App").replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); + assert_eq!(hits(&mut_ref), [(7, "all-unguarded")], "a filter on a `mut` reference parameter"); + let pattern = src.replace("app: &App, wide: bool", "(app, wide): (&App, bool)").replace("reasons(&app, true)", "reasons((&app, true))"); + assert_eq!(hits(&pattern), [(7, "all-unguarded")], "a parameter pattern that is not a plain name"); let mapped = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map(|r| app.reason(r)).filter(|r| r.is_some())"); assert_eq!(hits(&mapped), [(7, "all-unguarded")], "a filter on values mapped from that state"); let map_while = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map_while(|r| app.reason(r))"); @@ -5923,6 +6293,63 @@ mod tests { assert_eq!(declared(twice, &child), Some(vec!["any(all(target_os=\"macos\"),all(target_os=\"linux\"))".to_owned()])); let attr = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\nmod child;\n"; assert_eq!(declared(attr, &child), Some(vec!["any(not(unix),target_os=\"macos\")".to_owned()])); + let conditional = "#[cfg_attr(unix, path = \"portable.rs\")]\nmod imp;\n"; + assert_eq!(declared(conditional, &imp), Some(vec!["not(unix)".to_owned()]), "unix loads portable.rs instead"); + let portable = Loaded { path: "src/portable.rs", name: "portable", chain: &[] }; + assert_eq!(declared(conditional, &portable), Some(vec!["unix".to_owned()]), "the conditional path"); + assert_eq!(declared("#[path = \"portable.rs\"]\nmod imp;\n", &portable), Some(vec![]), "a plain `#[path]`"); + } + + #[test] + fn deleting_the_last_ci_route_counts_for_the_child_tests() { + let gates_of = |lib: &str, main: &str| { + let files: HashMap<&str, String> = + [("crates/x/src/lib.rs", lib.to_owned()), ("crates/x/src/main.rs", main.to_owned()), ("crates/x/src/child.rs", String::new())] + .into_iter() + .collect(); + module_gates(&["crates/x/src/child.rs".to_owned()], &|p: &str| files.get(p).cloned()).remove("crates/x/src/child.rs") + }; + let mac = "#[cfg(target_os = \"macos\")]\nmod child;\n"; + let main: BTreeMap>> = + [("crates/x/src/main.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + let (then, now) = (gates_of(mac, "mod child;\n"), gates_of(mac, "")); + assert!(!gate_changed(now.as_ref(), &main), "no line of the remaining route changed"); + assert!(gates_moved(now.as_ref(), then.as_ref(), &main), "the unconditional route is gone"); + let other: BTreeMap>> = + [("crates/x/src/main.rs".to_owned(), Some([2].into_iter().collect()))].into_iter().collect(); + let (then, now) = (gates_of(mac, "mod child;\nmod other;\n"), gates_of(mac, "mod child;\n")); + assert!(!gates_moved(now.as_ref(), then.as_ref(), &other), "a CI route remains"); + } + + #[test] + fn a_parent_edit_compares_tests_by_name_and_line() { + let path = "crates/x/src/child.rs"; + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\n"; + let now = Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }; + let off: Vec<(usize, String)> = newly_off(path, src, &now, &ctx()).into_iter().map(|h| (h.line, h.test)).collect(); + assert_eq!(off, [(10, "smoke".to_owned())], "b::smoke ran before; a::smoke was already off"); + } + + #[test] + fn each_load_route_keeps_its_own_ancestor_gates() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"platform/mod.rs\"]\nmod platform;\n"), + ("crates/x/src/main.rs", "#[path = \"platform.rs\"]\nmod platform;\n"), + ("crates/x/src/platform/mod.rs", "mod child;\n"), + ("crates/x/src/platform.rs", "mod child;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); + assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), None, "main.rs loads it on every target"); + // Without main.rs's declaration, nothing loads platform.rs. + let mac = + files.iter().map(|(&p, &s)| (p, if p.ends_with("main.rs") || p.ends_with("platform.rs") { "" } else { s })).collect::>(); + let read = |p: &str| mac.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); + assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); } #[test] @@ -5949,6 +6376,17 @@ mod tests { assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); + let multi: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "mod plain;\n#[cfg(\n target_os = \"macos\"\n)]\nmod child;\n"), ("crates/x/src/child.rs", "")] + .into_iter() + .collect(); + let read = |p: &str| multi.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the value line of a multi-line cfg"); + let local = "#[cfg(\n target_os = \"macos\"\n)]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", local, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[2].into_iter().collect())), "the value line of a multi-line cfg on the inline module"); } #[test] @@ -5984,6 +6422,8 @@ mod tests { assert_eq!(px("assert_eq!(dock_rect.width(), 120.0);"), [(4, "exact-pixel")], "a name that only starts with doc"); assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); + assert_eq!(px("assert_eq!(bucket(rect.min.x), 3);"), [], "a coordinate passed to a call"); + assert_eq!(px("assert_eq!((rect.min.x, rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); } @@ -5998,6 +6438,13 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + assert_eq!(only("reads-source", &dir.replace("\"data.json\"", "name")), [], "a file name the test does not spell out"); + assert_eq!(only("reads-source", &dir.replace(".join(\"data.json\")", "")), [(3, "reads-source")], "a literal final join"); + let formatted = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{dir}/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [(3, "reads-source")], "a format! template"); + let concat = "#[test]\nfn t() {\n let s = fs::read_to_string(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", concat), [(3, "reads-source")], "a concat! of literals"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); @@ -6021,6 +6468,16 @@ mod tests { assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); } + #[test] + fn a_match_arm_binding_shadows_the_outer_one_in_its_arm() { + let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => {}\n }\n}\n"; + assert_eq!(only("fixture-only", arm), []); + let block = arm.replace("Some(n) => assert_eq!(n, 1),", "Some(n) => {\n assert_eq!(n, 1);\n }"); + assert_eq!(only("fixture-only", &block), [], "a block arm"); + let after = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => consume(n),\n None => {}\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the match"); + } + #[test] fn nested_cfg_attr_gates_apply() { let nested = "#[cfg_attr(unix, cfg_attr(test, cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; From 06828e647f643374d2c53f43c07061329df9332a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 14:44:51 -0800 Subject: [PATCH 30/60] xtask: test-lint ends closure scopes and drops unsound all-unguarded guards - A closure parameter shadows a name only inside the closure's body, so a helper passed after `let _cb = |body| { ... };` counts again, and a closure parameter no longer resolves to an outer literal for `fixture-only`. - `if (parse(x).is_err()) { panic!(...) }` is read without its parentheses, so it counts as a success check, not a rejection. - An equality assertion guards `.all(...)` only when it compares the same call the receiver is bound to, or a snapshot of the receiver that nothing changes before the assertion. - A function over a constant table guards `.all(...)` only when it keeps every row of a table the file declares with a non-zero length; a filter can drop every row. - `ends_with(".rs")` is a `reads-source` hit only in a file that lists a directory (`read_dir`, `walkdir`, `glob`, `git ls-files`), and a `read_to_string` path follows the last argument only of path builders (`join`, `Path::new`, `PathBuf::from`, `format!`, `concat!`). - `never-run` skips later attributes that hold `;`, such as `#[test_case(1; "one")]`, and joins inline load routes from further up with the file that declares the module directly. - A deleted file keeps its old path in the change map, so the files below a deleted parent are checked. --- xtask/src/test_lint.rs | 293 +++++++++++++++++++++++++++-------------- 1 file changed, 193 insertions(+), 100 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e31150df25..ddc40bf920 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -539,19 +539,21 @@ fn changed_lines(root: &Path, base: &str) -> Result BTreeMap>> { let mut out: BTreeMap>> = BTreeMap::new(); - let mut current: Option = None; + let (mut current, mut old_path): (Option, Option) = (None, None); // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. let (mut header, mut new_file) = (false, false); for line in diff.lines() { if line.starts_with("diff --git ") { - (header, new_file) = (true, false); + (header, new_file, old_path) = (true, false, None); } else if header && line.starts_with("new file mode") { new_file = true; + } else if let Some(path) = line.strip_prefix("--- ").filter(|_| header) { + old_path = patch_path(path).and_then(|p| p.strip_prefix("a/").map(str::to_owned)); } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { - current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); + current = if path == "/dev/null" { old_path.clone() } else { patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)) }; if let Some(p) = ¤t { out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); } @@ -1464,31 +1466,57 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { } /// Whether a closure before `pos` takes a parameter that binds `name`, and `pos` lies inside the -/// innermost brackets around the closure (`keeping(|body| keeping(body))`). +/// closure's body (`keeping(|body| keeping(body))`). fn closure_binds(body: &[u8], name: &[u8], pos: usize) -> bool { - let mut at = 0; + closure_binding(body, name, pos).is_some() +} + +/// The opening `|` of the innermost closure whose parameters bind `name` and whose body holds `pos`. +fn closure_binding(body: &[u8], name: &[u8], pos: usize) -> Option { + let (mut at, mut found) = (0, None); while at < pos { let head = body[..at].trim_ascii_end(); let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); if body[at] == b'|' && opens { - let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return found }; let binds = split_args(body, at + 1, close).into_iter().any(|(start, end)| { let pattern = &body[start..end]; let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); !words(pattern, name, 0, end).is_empty() }); - if binds && close < pos { - let group = enclosing_open(body, at).and_then(|o| matching(body, o)).unwrap_or(body.len()); - if pos < group { - return true; - } + if binds && close < pos && pos < closure_end(body, close) { + found = Some(at); } at = close; } at += 1; } - false + found +} + +/// The end of the closure whose parameter list closes at `bar`: past the `}` of a block body, else at +/// the `,` or `;` that ends the expression or the bracket that holds it. +fn closure_end(body: &[u8], bar: usize) -> usize { + let mut i = bar + 1; + while i < body.len() && body[i].is_ascii_whitespace() { + i += 1; + } + if body[i..].starts_with(b"->") { + // A closure with a return type has a block body. + return body[i..].iter().position(|&c| c == b'{').and_then(|p| matching(body, i + p)).map_or(body.len(), |c| c + 1); + } + if body.get(i) == Some(&b'{') { + return matching(body, i).map_or(body.len(), |c| c + 1); + } + while i < body.len() { + match body[i] { + b'(' | b'[' | b'{' => i = matching(body, i).map_or(body.len(), |c| c + 1), + b',' | b';' | b')' | b']' | b'}' => return i, + _ => i += 1, + } + } + body.len() } /// The innermost unclosed `(`, `[` or `{` before `at`. @@ -1855,15 +1883,16 @@ fn panic_rejects(body: &[u8]) -> bool { if raw.iter().any(|c| matches!(c, b';' | b'{' | b'}')) { return false; } - let cond = norm(raw); + let normed = norm(raw); + let cond = unparenthesized(&normed); if let Some(pattern) = cond.strip_prefix("let") { // `if let Ok(_) = …` and `if let Some(_) = …` panic on success. return pattern.starts_with("Ok(") || pattern.starts_with("Some("); } - let negated = if !top_level_at(&cond, "&&").is_empty() || !top_level_at(&cond, "||").is_empty() { + let negated = if !top_level_at(cond, "&&").is_empty() || !top_level_at(cond, "||").is_empty() { format!("!({cond})") } else if let Some(rest) = cond.strip_prefix('!') { - rest.to_owned() + unparenthesized(rest).to_owned() } else if let Some(rest) = cond.strip_suffix(".is_err()") { format!("{rest}.is_ok()") } else if let Some(rest) = cond.strip_suffix(".is_none()") { @@ -2168,12 +2197,12 @@ fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { /// Whether an earlier equality assertion compares what `receiver` is made from with a non-empty /// literal: a plain local whose binding reads `receiver` (`let got = r.items()….collect(); -/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`), or a call on the same plain local -/// as the call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(ids(&word), [a, b, c])`). +/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`, with `got` unchanged in between), or +/// the same call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(gaps(&word), [a, b])`). fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { let r = array_receiver(receiver); let init = |name: &str, at: usize| let_init(body, name, at).and_then(|(init, _)| init); - // For a receiver bound to `f(&x)`: `x`, and where the binding of `x` it reads ends. + // For a receiver bound to `f(&x)`: the call `f(&x)`, `x`, and where the binding of `x` it reads ends. let source = if plain_local(r) { let_init(body, r, body.len()).and_then(|(init, bound)| { let (text, _) = init?; @@ -2182,7 +2211,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { return None; } let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); - Some((s, at)) + Some((norm(text.as_bytes()), s, at)) }) } else { None @@ -2196,13 +2225,20 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { if literal_len(literal, sizes) == 0 { return false; } - // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), and - // nothing changes the receiver's source from the binding on. + // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), nothing + // changes the binding before the assertion, and nothing changes the receiver's source + // from the binding on. let read = !plain_local(r) && plain_local(pinned) - && init(pinned, a.at) - .is_some_and(|(text, at)| keeping_base(&text, true) == r && !touched_after(body, root_local(r), statement_end(body, at), r)); - read || source.as_ref().is_some_and(|(s, at)| single_local_arg(pinned) == Some(s.as_str()) && !touched_after(body, s, *at, r)) + && init(pinned, a.at).is_some_and(|(text, at)| { + let bound = statement_end(body, at); + keeping_base(&text, true) == r + && !touched_after(&body[..a.at], pinned, bound, pinned) + && !touched_after(body, root_local(r), bound, r) + }); + // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its + // literal is what the receiver holds. + read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r)) }) }) } @@ -2261,10 +2297,10 @@ fn single_local_arg(call: &str) -> Option<&str> { plain_local(arg).then_some(arg) } -/// Whether `receiver` calls a function of the file whose body lists a constant table -/// (`TABLE.iter()…`, `Kind::ALL.iter()…`) and filters it only on parameters that are not -/// references: which rows it gives depends on the table and plain values, not on the state the -/// test builds. +/// Whether `receiver` calls a function of the file whose body lists every row of a non-empty +/// constant table of the file (`const TABLE: [T; 3]`, `TABLE.iter()…`) without filtering it: the +/// call gives at least one row whatever state the test builds. A filter, even one on plain values, +/// may drop every row, so it leaves the function out. fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let r = array_receiver(receiver); let Some(open) = r.find('(') else { return false }; @@ -2287,35 +2323,15 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; let signature = norm(&file[params_close + 1..body_open]); let return_type = signature.strip_prefix("->").unwrap_or(""); - // The binding name of each reference parameter, `app` of `mut app: &App`; a parameter whose - // pattern is not a plain name leaves the function out. - let mut refs: Vec = vec![]; - for (f, t) in split_args(file, params_open + 1, params_close) { - let param = String::from_utf8_lossy(&file[f..t]); - let Some((pattern, ty)) = param.split_once(':') else { return false }; - let pattern = pattern.trim(); - let pattern = pattern.strip_prefix("mut").filter(|r| r.starts_with(char::is_whitespace)).map_or(pattern, str::trim_start); - if !plain_local(pattern) { - return false; - } - if norm(ty.as_bytes()).starts_with('&') { - refs.push(pattern.to_owned()); - } - } let body = norm(&file[body_open + 1..body_close]); let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); let table = &body[..table_end]; - let screaming = table - .rsplit("::") - .next() - .is_some_and(|last| !last.is_empty() && last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')); - if !screaming || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); + if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { return false; } - // The body is the chain alone, of steps that keep or filter rows; everything up to the end - // of the last `filter`, maps before it included, reads no reference parameter. + // The body is the chain alone, of steps that keep every row. let mut at = table_end; - let mut decided = 0; while at < body.len() { let Some(rest) = body[at..].strip_prefix('.') else { return false }; let method_len = rest.bytes().take_while(|&c| is_ident(c)).count(); @@ -2335,13 +2351,11 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { return false; } } - "filter" => decided = close + 1, _ => return false, } at = close + 1; } - let decided = &body[..decided]; - refs.iter().all(|p| words(decided.as_bytes(), p.as_bytes(), 0, decided.len()).is_empty()) + true }) } @@ -3520,6 +3534,9 @@ fn reads_source_hits(file: &File) -> Vec { let m = &file.m; // The source with comments blanked and literals kept: a path in a comment is not read. let code = mask_parts(&String::from_utf8_lossy(file.src), true, false); + // A suffix check keeps Rust files only where the file lists a directory; elsewhere + // `ends_with(".rs")` may test any text, such as a rendered command line. + let walks = ["read_dir", "WalkDir", "walkdir", "ls-files", "glob"].iter().any(|w| !words(&code, w.as_bytes(), 0, code.len()).is_empty()); let mut out = vec![]; let words_and_notes = [ (&b"include_str"[..], "includes a .rs file as text"), @@ -3535,7 +3552,7 @@ fn reads_source_hits(file: &File) -> Vec { let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); let rs = match word { - b"ends_with" => literal == "\".rs\"", + b"ends_with" => walks && literal == "\".rs\"", // The literal at the end of the path names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")` or // `root.join("fixtures.rs").join(name)`. @@ -3603,11 +3620,22 @@ fn terminal_literal(arg: &str) -> Option<&str> { let ends = commas.iter().copied().chain([close]); let pieces: Vec<&str> = starts.zip(ends).map(|(s, e)| &arg[s..e]).filter(|p| !p.is_empty()).collect(); let head = &arg[..open]; + let ident = |c: char| c.is_ascii_alphanumeric() || c == '_'; + let callee = head.strip_suffix('!').unwrap_or(head); + let receiver = callee.trim_end_matches(ident); + let name = &callee[receiver.len()..]; let Some(&last) = pieces.last() else { - let method = head.trim_end_matches(|c: char| c.is_ascii_alphanumeric() || c == '_'); - return method.strip_suffix('.').and_then(terminal_literal); + // A conversion keeps the path its receiver names: `"x.rs".to_owned()`. + let converts = ["to_owned", "to_string", "into", "as_ref", "to_path_buf", "as_path", "clone"].contains(&name); + return receiver.strip_suffix('.').filter(|_| converts && !head.ends_with('!')).and_then(terminal_literal); }; - terminal_literal(if head.ends_with("format!") { pieces[0] } else { last }) + // Only calls that build a path from their arguments name the file in them; others, such as + // `"data.json.rs".trim_end_matches(".rs")`, change the text in other ways. + let builds = if head.ends_with('!') { ["format", "concat"].contains(&name) } else { ["join", "new", "from", "with_file_name"].contains(&name) }; + if !builds { + return None; + } + terminal_literal(if name == "format" { pieces[0] } else { last }) } // ---- Mirrors, echoes, never-run tests and exact pixels ---- @@ -3764,8 +3792,9 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), @@ -4066,7 +4095,12 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let enclosing = m[..at].iter().rposition(|&c| c == b'{'); enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) } else { - let after = end + 1; + // Later attributes can hold `;` (`#[test_case(1; "one")]`); skip them whole. + let mut after = end + 1; + while m[skip_ws(m, after)..].starts_with(b"#[") { + let Some(close) = matching(m, skip_ws(m, after) + 1) else { break }; + after = close + 1; + } let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; match (m[open], matching(m, open)) { (b'{', Some(close)) => (at, close), @@ -4287,30 +4321,30 @@ fn route_preds(at: &str, read: &dyn Fn(&str) -> Option, sources: &mut Ve }) else { return vec![]; }; + // Routes from every level: a file declaring `mod ;` directly, and files further up that + // declare it inside inline modules (`mod platform { mod child; }`). let mut chain: Vec = vec![]; + let mut routes: Vec> = vec![]; for _ in 0..4 { let want = Loaded { path: at, name, chain: &chain }; let found: Vec<_> = candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if !found.is_empty() { - let mut routes: Vec> = vec![]; - for (parent, (mut preds, lines)) in found { - sources.push((parent.clone(), lines)); - preds.extend(route_preds(&parent, read, sources, depth + 1)); - routes.push(preds); - } - return match routes.len() { - 1 => routes.pop().unwrap_or_default(), - _ if routes.iter().any(Vec::is_empty) => vec![], - _ => vec![format!("any({})", routes.iter().map(|r| format!("all({})", r.join(","))).collect::>().join(","))], - }; + for (parent, (mut preds, lines)) in found { + sources.push((parent.clone(), lines)); + preds.extend(route_preds(&parent, read, sources, depth + 1)); + routes.push(preds); } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { return vec![] }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { return vec![] }; + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; chain.insert(0, seg); candidates = next; module_dir = up; } - vec![] + match routes.len() { + 0 => vec![], + 1 => routes.pop().unwrap_or_default(), + _ if routes.iter().any(Vec::is_empty) => vec![], + _ => vec![format!("any({})", routes.iter().map(|r| format!("all({})", r.join(","))).collect::>().join(","))], + } } /// A test that a `cfg` compiles out on every target CI runs tests on. @@ -4600,7 +4634,15 @@ mod tests { assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success"); let panics = "#[test]\nfn t() {\n for c in CASES {\n assert!(c.valid.is_some());\n if accepts(c.invalid) {\n panic!(\"accepted invalid input\");\n }\n }\n}\n"; assert_eq!(census_in(panics, &ctx()), [], "a panic when invalid input is accepted checks a rejection"); - for enforcing in ["parse(c.valid).is_err()", "!parse(c.valid).is_ok()", "let Err(_) = parse(c.valid)"] { + let rejecting = panics.replace("accepts(c.invalid)", "(parse(c.invalid).is_ok())"); + assert_eq!(census_in(&rejecting, &ctx()), [], "a panic on a parenthesized is_ok checks a rejection"); + for enforcing in [ + "parse(c.valid).is_err()", + "!parse(c.valid).is_ok()", + "let Err(_) = parse(c.valid)", + "(parse(c.valid).is_err())", + "!(parse(c.valid).is_ok())", + ] { let src = panics.replace("accepts(c.invalid)", enforcing); assert_eq!(census_in(&src, &ctx()), [(2, "census")], "{enforcing}: a panic that only enforces success"); } @@ -5671,8 +5713,13 @@ mod tests { fn reading_rust_source_is_reported_outside_the_audits() { let bad = "#[test]\nfn t() {\n let src = include_str!(\"../lib.rs\");\n assert_eq!(src.matches(\"x\").count(), 1);\n}\n"; assert_eq!(hits(bad), [(3, "reads-source")]); - let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + let walk = + "#[test]\nfn t() {\n let n = fs::read_dir(d).unwrap().map(name).filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; assert_eq!(hits(walk), [(3, "reads-source")]); + let helper = "fn files() -> Vec {\n fs::read_dir(d).unwrap().map(name).collect()\n}\n#[test]\nfn t() {\n let n = files().into_iter().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(only("reads-source", helper), [(6, "reads-source")], "a walk in a helper of the file"); + let output = "#[test]\nfn t() {\n assert!(render_command().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", output), [], "a suffix check on text in a file that lists no directory"); assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; assert_eq!(hits(data), []); @@ -5706,6 +5753,9 @@ mod tests { assert_eq!(got.len(), 2); assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); assert_eq!(got["crates/x/src/n.rs"], None); + let deleted = "diff --git a/crates/x/src/main.rs b/crates/x/src/main.rs\ndeleted file mode 100644\n--- a/crates/x/src/main.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-mod child;\n-fn main() {}\n"; + let got = parse_diff(deleted); + assert_eq!(got.get("crates/x/src/main.rs"), Some(&Some([1].into_iter().collect())), "a deleted file keeps its old path"); } #[test] @@ -5950,6 +6000,12 @@ mod tests { ); let closure = src.replace(" keeping(body);", " keeping(|body| keeping(body));"); assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); + let block_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| { drop(body); };\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &block_closure, &ctx), [], "a closure parameter's scope ends with the closure"); + let expr_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| drop(body);\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &expr_closure, &ctx), [], "an expression closure's scope ends at its semicolon"); + let inner = src.replace(" keeping(body);", " let _cb = |body: fn()| { keeping(body); };"); + assert_eq!(hits_in("crates/x/src/tests.rs", &inner, &ctx), [(8, "no-assertion")], "the parameter inside its closure"); let parameter = src.replace("fn t()", "fn t(body: fn())"); assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); let later = src.replace(" keeping(body);", " keeping(body);\n {\n let body = || {};\n let _ = body;\n }"); @@ -5998,39 +6054,46 @@ mod tests { assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); assert_eq!(hits(&chained), [(5, "all-unguarded")], "a list that is not empty without the receiver's items"); - let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(ids(&plain), [1, 2, 3]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; + let reassigned = pinned.replace(" assert_eq!(got", " got = vec![1, 2];\n assert_eq!(got"); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "the snapshot was replaced before the assertion"); + let pushed = pinned.replace(" assert_eq!(got", " got.push(1);\n assert_eq!(got"); + assert_eq!(hits(&pushed), [(6, "all-unguarded")], "the snapshot changed before the assertion"); + let read_first = pinned.replace(" assert_eq!(got", " assert!(got.len() < 9);\n assert_eq!(got"); + assert_eq!(hits(&read_first), [], "a read of the snapshot before the assertion"); + let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(gaps(&plain), [0.0, 0.0]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; assert_eq!(hits(word), []); - assert_eq!(hits(&word.replace("ids(&plain)", "ids(&other)")), [(6, "all-unguarded")], "a literal about another value"); + assert_eq!(hits(&word.replace("gaps(&plain), [", "gaps(&other), [")), [(6, "all-unguarded")], "a literal about another value"); + assert_eq!(hits(&word.replace("gaps(&plain), [", "ids(&plain), [")), [(6, "all-unguarded")], "a literal about another call on the value"); let emptied = word.replace(" let gaps = gaps(&plain);\n", " let mut gaps = gaps(&plain);\n gaps.clear();\n"); assert_eq!(hits(&emptied), [(7, "all-unguarded")], "a receiver that may change after its binding"); - let rebound = word.replace(" assert_eq!(ids(&plain), [1, 2, 3]);\n", "").replace( + let rebound = word.replace(" assert_eq!(gaps(&plain), [0.0, 0.0]);\n", "").replace( " let gaps = gaps(&plain);", - " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(ids(&plain), [1, 2, 3]);", + " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(gaps(&plain), [0.0, 0.0]);", ); assert_eq!(hits(&rebound), [(7, "all-unguarded")], "the assertion reads a later binding of the source"); } #[test] - fn all_over_a_constant_table_filtered_on_plain_values_is_guarded() { - let src = "fn reasons(app: &App, wide: bool) -> Vec> {\n TABLE.iter().filter(|r| r.wide == wide).map(|r| app.reason(r)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, true).iter().all(|r| r.is_none()));\n}\n"; + fn all_over_every_row_of_a_constant_table_is_guarded() { + let src = "const TABLE: [u8; 2] = [1, 2];\nfn reasons(app: &App, key: u8) -> Vec> {\n TABLE.iter().map(|r| app.reason(r, key)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, 2).iter().all(|r| r.is_none()));\n}\n"; assert_eq!(hits(src), []); - let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: bool| Vec::>::new();\n assert!"); - assert_eq!(hits(&shadowed), [(8, "all-unguarded")], "a local binding shadows the file's function"); - let state = src.replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); - assert_eq!(hits(&state), [(7, "all-unguarded")], "a filter on the state the test builds"); - let mut_ref = src.replace("app: &App", "mut app: &App").replace("filter(|r| r.wide == wide)", "filter(|r| app.has(r))"); - assert_eq!(hits(&mut_ref), [(7, "all-unguarded")], "a filter on a `mut` reference parameter"); - let pattern = src.replace("app: &App, wide: bool", "(app, wide): (&App, bool)").replace("reasons(&app, true)", "reasons((&app, true))"); - assert_eq!(hits(&pattern), [(7, "all-unguarded")], "a parameter pattern that is not a plain name"); - let mapped = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map(|r| app.reason(r)).filter(|r| r.is_some())"); - assert_eq!(hits(&mapped), [(7, "all-unguarded")], "a filter on values mapped from that state"); - let map_while = src.replace(".filter(|r| r.wide == wide).map(|r| app.reason(r))", ".map_while(|r| app.reason(r))"); - assert_eq!(hits(&map_while), [(7, "all-unguarded")], "another step that drops rows"); + let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: u8| Vec::>::new();\n assert!"); + assert_eq!(hits(&shadowed), [(9, "all-unguarded")], "a local binding shadows the file's function"); + let keyed = src.replace(".map(|r|", ".filter(|r| **r == key).map(|r|"); + assert_eq!(hits(&keyed), [(8, "all-unguarded")], "a filter on a plain value may drop every row"); + let state = src.replace(".map(|r|", ".filter(|r| app.has(r)).map(|r|"); + assert_eq!(hits(&state), [(8, "all-unguarded")], "a filter on the state the test builds"); + let empty = src.replace("[u8; 2] = [1, 2]", "[u8; 0] = []"); + assert_eq!(hits(&empty), [(8, "all-unguarded")], "an empty table"); + let elsewhere = src.replace("const TABLE: [u8; 2] = [1, 2];\n", ""); + assert_eq!(hits(&elsewhere), [(7, "all-unguarded")], "a table whose length the file does not show"); + let map_while = src.replace(".map(|r| app.reason(r, key))", ".map_while(|r| app.reason(r, key))"); + assert_eq!(hits(&map_while), [(8, "all-unguarded")], "another step that drops rows"); let optional = src .replace("-> Vec>", "-> Option>>") - .replace(".map(|r| app.reason(r))", ".map(|r| Some(app.reason(r)))") + .replace(".map(|r| app.reason(r, key))", ".map(|r| Some(app.reason(r, key)))") .replace(".all(|r| r.is_none())", ".all(|r| r.len() == 1)"); - assert_eq!(hits(&optional), [(7, "all-unguarded")], "collecting into an option can discard every row"); + assert_eq!(hits(&optional), [(8, "all-unguarded")], "collecting into an option can discard every row"); } #[test] @@ -6091,7 +6154,7 @@ mod tests { assert_eq!(hits(&src.replace(".rs", ".svg")), [], "{literal} with a fixture"); assert_eq!(hits_in(SOURCE_AUDITS[0], &src, &ctx()), [], "{literal} in an audit"); } - let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; + let walk = "#[test]\nfn t() {\n let n = fs::read_dir(d).unwrap().map(name).filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; assert_eq!(hits(walk), [(3, "reads-source")]); } @@ -6240,6 +6303,8 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", other), [], "a cfg on another item"); + let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); } #[test] @@ -6350,6 +6415,18 @@ mod tests { let read = |p: &str| mac.get(p).map(|s| (*s).to_owned()); let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + // An inline route one level up joins the external one. + let inline: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod platform;\n"), + ("crates/x/src/main.rs", "mod platform {\n mod child;\n}\n"), + ("crates/x/src/platform.rs", "mod child;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| inline.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read); + assert_eq!(gates.get("crates/x/src/platform/child.rs").map(|g| g.preds.clone()), None, "main.rs's inline module loads it on every target"); } #[test] @@ -6440,6 +6517,12 @@ mod tests { assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); assert_eq!(only("reads-source", &dir.replace("\"data.json\"", "name")), [], "a file name the test does not spell out"); assert_eq!(only("reads-source", &dir.replace(".join(\"data.json\")", "")), [(3, "reads-source")], "a literal final join"); + let trimmed = data.replace("root.join(\"data.json\")", "\"data.json.rs\".trim_end_matches(\".rs\")"); + assert_eq!(only("reads-source", &trimmed), [], "a call that is not a path builder"); + let owned = data.replace("root.join(\"data.json\")", "\"src/lib.rs\".to_owned()"); + assert_eq!(only("reads-source", &owned), [(3, "reads-source")], "a conversion of a literal path"); + let new = data.replace("root.join(\"data.json\")", "Path::new(\"src/lib.rs\")"); + assert_eq!(only("reads-source", &new), [(3, "reads-source")], "a Path::new of a literal path"); let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{dir}/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", formatted), [(3, "reads-source")], "a format! template"); @@ -6468,6 +6551,16 @@ mod tests { assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); } + #[test] + fn a_closure_parameter_shadows_the_outer_binding_in_its_body() { + let closure = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|n| assert_eq!(n, 1));\n}\n"; + assert_eq!(only("fixture-only", closure), []); + let block = closure.replace("|n| assert_eq!(n, 1)", "|n| {\n assert_eq!(n, 1);\n }"); + assert_eq!(only("fixture-only", &block), [], "a block body"); + let after = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|n| consume(n));\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the closure"); + } + #[test] fn a_match_arm_binding_shadows_the_outer_one_in_its_arm() { let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => {}\n }\n}\n"; From 938de6e8a3dbd7f159f1b8fe16cc244a6bf936bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:31:33 -0800 Subject: [PATCH 31/60] JavaScript: Symbol keys reach a proxy's target, Reflect keeps Symbol keys, and a sealed global skips Proxy and Reflect - A Symbol key on a proxy now goes to its innermost target for every operation: a definition, write or deletion no longer lands on the proxy object itself. Object.freeze, Object.seal, Object.isFrozen and Object.isSealed therefore work on a proxy whose target has Symbol properties instead of throwing a TypeError. - Reflect.get, set, has, defineProperty, deleteProperty and getOwnPropertyDescriptor keep a Symbol key as a Symbol, and Reflect.ownKeys lists Symbol keys after the string keys. - A realm whose global object an earlier run made non-extensible runs its ECMAScript 2015 code without Proxy and Reflect, instead of failing every run with an installation error. - JSON.stringify charges a replacer array's names to the heap as they are kept, not the array's whole length up front. - for-in checks each name's descriptor from the object that listed it, so a proxy that did not list a name does not hide an inherited one. - An Array subclass constructed with a proxy newTarget runs the proxy's get trap before any revoked inner proxy is reached. - The legacy reflect.find reads its lists without calling proxy traps. --- crates/js/src/builtins/json.rs | 15 ++- crates/js/src/builtins/object.rs | 21 ----- crates/js/src/builtins/reflect.rs | 82 ++++++++++++++--- crates/js/src/class_ops.rs | 4 +- crates/js/src/heap.rs | 6 +- crates/js/src/interp.rs | 46 +++++++--- crates/js/src/proxy.rs | 2 +- crates/js/src/proxy_tests.rs | 148 ++++++++++++++++++++++++------ crates/js/src/realm.rs | 4 +- crates/js/src/reflect.rs | 8 +- crates/js/src/symbol.rs | 29 ++++-- docs/mcp.md | 29 +++--- docs/target-app-parity.md | 2 +- 13 files changed, 286 insertions(+), 110 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 4d9c87a4d9..f0ce3384c6 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult { struct Settings { replacer: Option, properties: Option>, + _held_properties: Option, gap: Vec, } @@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { /// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8). fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult { - let mut s = Settings { replacer: None, properties: None, gap: Vec::new() }; + let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() }; if let Value::Object(r) = replacer { if interp.is_callable(replacer) { s.replacer = Some(replacer.clone()); } else if interp.is_array(replacer)? { - s.properties = Some(property_list(interp, *r)?); + let crate::interp::HeldKeys { keys, held } = property_list(interp, *r)?; + s.properties = Some(keys); + s._held_properties = Some(held); } } let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone()); @@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { +/// Each name kept is charged to the heap for as long as the returned holder lives. +fn property_list(interp: &mut Interp, r: ObjId) -> JsResult { let len = super::collections::length_of(interp, r)?; if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { @@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult> { } // The list lives until the call returns, so its names are rooted. interp.temp_roots.push(Value::String(s)); + held.add(interp, ELEMENT_BYTES)?; list.push(k); } } - Ok(list) + Ok(crate::interp::HeldKeys { keys: list, held }) } /// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 599519c0e0..8237c11f34 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -259,13 +259,11 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// 15.2.3.8 and 15.2.3.9). A proxy that does not become non-extensible is a `TypeError`. fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; - check_integrity_symbols(interp, o)?; if !interp.prevent_extensions(o)? { let what = if freeze { "frozen" } else { "sealed" }; return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible"))); } let (keys, _held) = own_prop_keys(interp, o)?; - check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; let desc = if freeze { @@ -279,7 +277,6 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { }; interp.define_own_pk(o, k, &desc, true)?; } - check_integrity_symbols(interp, o)?; Ok(Value::Object(o)) } @@ -308,12 +305,10 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; - check_integrity_symbols(interp, o)?; if interp.is_extensible(o)? { return Ok(Value::Bool(false)); } let (keys, _held) = own_prop_keys(interp, o)?; - check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; let Some(prop) = interp.own_pk(o, &k)? else { continue }; @@ -321,7 +316,6 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { return Ok(Value::Bool(false)); } } - check_integrity_symbols(interp, o)?; Ok(Value::Bool(true)) } @@ -329,21 +323,6 @@ fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult locked(interp, &arg(args, 0), false) } -fn check_integrity_symbols(interp: &mut Interp, o: ObjId) -> JsResult<()> { - if !interp.is_proxy(o) { - return Ok(()); - } - let mut current = o; - loop { - if interp.object(current)?.syms.as_ref().is_some_and(|m| m.len() != 0) { - return Err(interp.type_error("proxy integrity operations with symbol properties are not supported")); - } - let Some(target) = interp.symbol_lookup_target(current)? else { return Ok(()) }; - interp.use_fuel()?; - current = target; - } -} - fn is_frozen(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { locked(interp, &arg(args, 0), true) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 0b0f60cacf..a49833739c 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -6,17 +6,24 @@ use std::rc::Rc; use super::object::{from_prop, names_array, to_desc}; use super::{arg, method, native}; -use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key}; +use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; +use crate::symbol::{PropKey, Sym}; use crate::value::Value; /// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them /// after earlier runs, a global of the same name that a script defined stays as it is. Each /// global is defined after its functions, so an install that stops part way leaves no global -/// that a later install would keep without them. +/// that a later install would keep without them. A global object that an earlier run made +/// non-extensible cannot become extensible again, so a name it lacks is left out and the realm's +/// runs go on without it. pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> { let global = interp.global; + if keep && interp.heap.object(global).is_some_and(|g| !g.extensible) { + interp.es2015_installed = true; + return Ok(()); + } if !(keep && interp.get_own_property(global, &key("Proxy"))?.is_some()) { let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; // Naming a new method can collect, and the constructor is reachable from nowhere else @@ -161,32 +168,41 @@ fn construct(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult /// property was defined. fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "defineProperty")?; - interp.with_key(&arg(args, 1), |interp, k| { + interp.with_prop_key(&arg(args, 1), |interp, k| { let desc: Desc = to_desc(interp, &arg(args, 2))?; let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, false)).map(Value::Bool) + interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, false)).map(Value::Bool) }) } /// `Reflect.deleteProperty(target, propertyKey)` (section 26.1.4): whether the property is gone. fn delete_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "deleteProperty")?; - interp.with_key(&arg(args, 1), |interp, k| interp.delete(o, &k, false)).map(Value::Bool) + interp.with_prop_key(&arg(args, 1), |interp, k| interp.delete_pk(o, &k, false)).map(Value::Bool) } /// `Reflect.get(target, propertyKey[, receiver])` (section 26.1.5). fn get(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "get")?; let receiver = if args.len() > 2 { arg(args, 2) } else { Value::Object(o) }; - interp.with_key(&arg(args, 1), |interp, k| interp.get_from(o, &k, &receiver)) + interp.with_prop_key(&arg(args, 1), |interp, k| match k { + PropKey::Str(k) => interp.get_from(o, &k, &receiver), + PropKey::Sym(s) => interp.get_sym_from(o, &s, &receiver), + }) } /// `Reflect.getOwnPropertyDescriptor(target, propertyKey)` (section 26.1.6). fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "getOwnPropertyDescriptor")?; - interp.with_key(&arg(args, 1), |interp, k| match interp.own_property(o, &k)? { - Some(p) => from_prop(interp, &p), - None => Ok(Value::Undefined), + interp.with_prop_key(&arg(args, 1), |interp, k| { + let prop = match k { + PropKey::Str(k) => interp.own_property(o, &k)?, + PropKey::Sym(s) => interp.get_own_sym(o, &s)?, + }; + match prop { + Some(p) => from_prop(interp, &p), + None => Ok(Value::Undefined), + } }) } @@ -199,7 +215,12 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// `Reflect.has(target, propertyKey)` (section 26.1.8). fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "has")?; - interp.with_key(&arg(args, 1), |interp, k| interp.has_property_indexed(o, &k)).map(Value::Bool) + interp + .with_prop_key(&arg(args, 1), |interp, k| match k { + PropKey::Str(k) => interp.has_property_indexed(o, &k), + PropKey::Sym(s) => Ok(interp.find_sym(o, &s)?.is_some()), + }) + .map(Value::Bool) } /// `Reflect.isExtensible(target)` (section 26.1.9). @@ -208,11 +229,23 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.is_extensible(o).map(Value::Bool) } -/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not. +/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not, +/// then the own Symbol keys in the order they were added. A proxy's Symbol keys are its +/// target's. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; let names = interp.ecma_own_keys(o)?; - names_array(interp, names) + let count = names.len(); + let syms = interp.own_symbols(o)?; + let a = names_array(interp, names)?; + let Value::Object(id) = a else { return Ok(a) }; + interp.rooted(&[Value::Object(id)], |interp| { + for (i, s) in syms.into_iter().enumerate() { + interp.use_fuel()?; + super::create_at(interp, id, (count + i) as f64, Value::Symbol(s))?; + } + Ok(Value::Object(id)) + }) } /// `Reflect.preventExtensions(target)` (section 26.1.11): whether the object is now not @@ -228,7 +261,30 @@ fn set(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult 3 { arg(args, 3) } else { Value::Object(o) }; let v = arg(args, 2); - interp.with_key(&arg(args, 1), |interp, k| interp.set_with_receiver(o, k, v, &receiver)).map(Value::Bool) + interp + .with_prop_key(&arg(args, 1), |interp, k| match k { + PropKey::Str(k) => interp.set_with_receiver(o, k, v, &receiver), + PropKey::Sym(s) => set_sym(interp, o, s, v, &receiver), + }) + .map(Value::Bool) +} + +/// OrdinarySet (section 9.1.9.1) for a Symbol key: whether `receiver` took the value. +fn set_sym(interp: &mut Interp, o: ObjId, s: Sym, v: Value, receiver: &Value) -> JsResult { + match interp.find_sym(o, &s)? { + Some(Prop::Accessor { set: Some(f), .. }) => return interp.call(&Value::Object(f), receiver, &[v]).map(|_| true), + Some(Prop::Accessor { set: None, .. }) => return Ok(false), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return Ok(false), + _ => {} + } + let Value::Object(r) = receiver else { return Ok(false) }; + let desc = match interp.get_own_sym(*r, &s)? { + Some(Prop::Accessor { .. }) => return Ok(false), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return Ok(false), + Some(Prop::Data { .. }) => Desc { value: Some(v), ..Desc::default() }, + None => Desc::data(v, OPEN), + }; + interp.define_own_sym(*r, s, &desc, false) } /// `Reflect.setPrototypeOf(target, proto)` (section 26.1.13): whether the prototype was set. A diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index ced17a3507..99b63f4f56 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -313,7 +313,9 @@ impl Interp { Some(Func::Native { f: native, constructor: true, name, .. }) => { // `Proxy` does not read `new.target` (section 26.2.1.1). let subclass = nt != callee && name != "Proxy"; - if !boundary && subclass && !forwarding && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { + // A built-in that can be subclassed takes any `newTarget`, so its proxies are not + // unwrapped, and a revoked inner proxy does not stop the outer one's traps. + if !boundary && subclass && !forwarding && !self.subclassable(callee)? && self.unwrapped_proxy_target(nt)? != callee { return Err(self.type_error("this built-in cannot be subclassed")); } let intrinsic = match self.get_own_property(callee, &key("prototype"))? { diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 89fb2c0a2e..2417e3bd7a 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -211,10 +211,12 @@ pub(crate) struct ArgMap { pub(crate) names: Vec>, } -/// A `for-in` loop's state: the names listed when it started, and the object they came from. +/// A `for-in` loop's state: the names listed when it started, the object on the prototype chain +/// that listed each name, and the object they came from. #[derive(Clone, Debug)] pub(crate) struct ForIn { pub(crate) keys: Vec, + pub(crate) from: Vec, pub(crate) pos: usize, pub(crate) object: Option, } @@ -1178,7 +1180,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } } Class::ForIn(state) => { - work.extend(state.object.iter().map(|o| o.0)); + work.extend(state.object.iter().chain(state.from.iter()).map(|o| o.0)); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); } Class::Symbol(s) => strings.add_symbol(s), diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f92cf9500f..3a3f8e1461 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3283,27 +3283,37 @@ impl Interp { /// /// For a String object, the heap budget for all its index names is checked before any is /// built. Each index name and each property visited takes a unit of fuel. - fn enumerable_keys(&mut self, id: ObjId) -> JsResult> { + /// + /// With each name comes the object on the chain that listed it. Those objects stay in + /// `temp_roots` after a successful return, for the caller to keep or drop. + fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, Vec)> { if self.options.e4x && self.is_xml(&Value::Object(id)) { - return self.xml_enumerate(id); + let keys = self.xml_enumerate(id)?; + let from = vec![id; keys.len()]; + return Ok((keys, from)); } let slot = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); let r = self.enumerable_keys_from(id, slot); - self.temp_roots.truncate(slot); + if r.is_err() { + self.temp_roots.truncate(slot); + } r } /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its /// `ownKeys` trap and the next object with its `getPrototypeOf` trap. /// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype. - /// Descriptors are checked when iteration reaches each name. - fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { + /// Descriptors are checked when iteration reaches each name, starting at the object that + /// listed it. Each object on the chain is pushed to `temp_roots` after `slot`. + fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, Vec)> { let mut seen = std::collections::HashSet::new(); let mut held = HeldBytes::new(self); let mut out = Vec::new(); + let mut from = Vec::new(); let mut cur = Some(id); while let Some(o) = cur { + self.temp_roots.push(Value::Object(o)); if self.is_proxy(o) { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(o); @@ -3317,6 +3327,7 @@ impl Interp { held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; seen.insert(k.clone()); out.push(k); + from.push(o); } cur = self.get_prototype_of(o)?; if let Some(root) = self.temp_roots.get_mut(slot) { @@ -3340,6 +3351,7 @@ impl Interp { held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; seen.insert(k.clone()); out.push(k); + from.push(o); } } } @@ -3361,17 +3373,18 @@ impl Interp { for (k, p) in obj.props.iter() { if seen.insert(k.clone()) && p.enumerable() { out.push(k.clone()); + from.push(o); } } cur = obj.proto; } - Ok(out) + Ok((out, from)) } fn op_for_in_start(&mut self) -> JsResult<()> { let v = self.peek(0)?; - let (keys, object) = if v.is_nullish() { - (Vec::new(), None) + let ((keys, from), object) = if v.is_nullish() { + ((Vec::new(), Vec::new()), None) } else { let o = self.to_object(&v)?; // A wrapper made by ToObject is not on the stack; a collection while the names are @@ -3380,16 +3393,18 @@ impl Interp { self.temp_roots.push(Value::Object(o)); // Listing a namespace object's exports does not read them (ECMA-262 2015 section // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. - let keys = self.enumerable_keys(o).and_then(|keys| { + let keys = self.enumerable_keys(o).and_then(|(keys, from)| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); - Ok(keys) + Ok((keys, from)) }); + // Allocating the iterator does not collect, so the objects that listed the names stay + // alive until it holds them. self.temp_roots.truncate(saved); (keys?, Some(o)) }; - let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, pos: 0, object })), None)); + let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, from, pos: 0, object })), None)); self.replace(1, Value::Object(iter)) } @@ -3398,10 +3413,17 @@ impl Interp { loop { let Class::ForIn(state) = &mut self.object_mut(iter)?.class else { return internal("not a for-in iterator") }; let Some(k) = state.keys.get(state.pos).cloned() else { return self.jump_to(target) }; + let lister = state.from.get(state.pos).copied(); state.pos += 1; let object = state.object; let Some(o) = object else { continue }; - let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(o, &k)? }; + // The check starts at the object that listed the name, so a proxy that did not list + // it does not hide it. + let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { + self.scope_has(o, &k)? + } else { + self.for_in_still_has(lister.unwrap_or(o), &k)? + }; if visit { return self.push(Value::String(Str::from_rc(k))); } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 7a53949a83..fa88173b16 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -30,7 +30,7 @@ impl Interp { matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_))) } - /// The target that a lookup of a Symbol key on the proxy `id` goes on to, since traps take + /// The target that an operation on a Symbol key of the proxy `id` goes on to, since traps take /// string property names only; `None` when `id` is not a proxy. A revoked proxy is a /// `TypeError`. pub(crate) fn symbol_lookup_target(&mut self, id: ObjId) -> JsResult> { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index a3ed321311..01495b4fc5 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -119,23 +119,16 @@ fn late_proxy_and_reflect_installation_respects_global_extensibility() { [("", false, false), ("var Proxy = 7;", true, false), ("var Reflect = 8;", false, true), ("var Proxy = 7, Reflect = 8;", true, true)] { let mut realm = Realm::new(); - assert_eq!(realm.run(&format!("{setup} var runs = 0; Object.{operation}(this); 0")), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run(&format!("{setup} Object.{operation}(this); 0")), Ok(JsValue::Number(0.0))); realm.set_es2015(true); - if has_proxy && has_reflect { - assert_eq!(realm.run("Proxy + Reflect"), Ok(JsValue::Number(15.0))); - } else { - for _ in 0..2 { - let err = realm.run("runs++").unwrap_err(); - assert_eq!(err.kind, RunErrorKind::Internal); - assert!(err.message.contains("Proxy and Reflect could not be installed"), "{err:?}"); - assert!(err.message.contains("the object is not extensible"), "{err:?}"); - let missing = if has_proxy { "Reflect" } else { "Proxy" }; - assert!(err.message.contains(missing), "{err:?}"); - } + // ES2015 runs go on without the names the sealed global lacks. + let names = format!("{} {}", if has_proxy { "number" } else { "undefined" }, if has_reflect { "number" } else { "undefined" }); + for _ in 0..2 { + assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String(names.clone().into())), "{operation}: {setup}"); } realm.set_es2015(false); let check = format!( - "runs === 0 && !Object.isExtensible(this) && this.hasOwnProperty('Proxy') === {has_proxy} + "!Object.isExtensible(this) && this.hasOwnProperty('Proxy') === {has_proxy} && this.hasOwnProperty('Reflect') === {has_reflect} && (typeof Proxy === 'undefined' || Proxy === 7) && (typeof Reflect === 'undefined' || Reflect === 8)" ); @@ -626,6 +619,43 @@ fn reflect_methods_answer_with_booleans_and_receivers() { ); } +#[test] +fn reflect_keeps_symbol_keys_as_symbols() { + truth( + "var s = Symbol('x'), o = { a: 1 }; o[s] = 7; + var read = Reflect.get(o, s) === 7 && Reflect.has(o, s) && !Reflect.has(o, Symbol('x')) + && Reflect.getOwnPropertyDescriptor(o, s).value === 7; + var written = Reflect.set(o, s, 8) && o[s] === 8; + var r = {}, base = {}; Object.defineProperty(base, s, { value: 1, writable: true }); + var received = Reflect.set(base, s, 2, r) && r[s] === 2 && base[s] === 1; + var fixed = {}; Object.defineProperty(fixed, s, { value: 1 }); + var refused = !Reflect.set(fixed, s, 2) && !Reflect.deleteProperty(fixed, s); + var t = Symbol('t'), defined = Reflect.defineProperty(o, t, { value: 3, configurable: true }) && o[t] === 3; + var deleted = Reflect.deleteProperty(o, t) && !(t in o) && o['Symbol(t)'] === undefined; + var keys = Reflect.ownKeys(o); + read && written && received && refused && defined && deleted && keys.length === 2 && keys[0] === 'a' && keys[1] === s", + ); + // A proxy's Symbol keys are its target's. + truth( + "var s = Symbol('x'), t = { a: 1 }; t[s] = 1; + var keys = Reflect.ownKeys(new Proxy(t, {})); + keys.length === 2 && keys[0] === 'a' && keys[1] === s", + ); +} + +#[test] +fn a_subclassable_built_in_runs_the_outer_get_trap_of_a_new_target_whose_inner_proxy_is_revoked() { + // The outer trap runs; its invariant check then reads the revoked target and throws + // (ECMA-262 2020 section 9.5.8, step 9). + truth( + "class DerivedArray extends Array {} + var P = {}, inner = Proxy.revocable(function () {}, {}), reads = 0; + var outer = new Proxy(inner.proxy, { get: function (t, k) { if (k === 'prototype') { reads++; return P; } } }); + inner.revoke(); + type_error(function () { Reflect.construct(DerivedArray, [], outer); }) && reads === 1", + ); +} + #[test] fn reflect_construct_gives_a_built_in_object_the_prototype_of_new_target() { truth( @@ -949,24 +979,45 @@ fn transparent_builtin_constructors_read_the_proxy_new_target_prototype() { } #[test] -fn proxy_integrity_operations_reject_symbol_properties() { +fn proxy_integrity_operations_include_the_targets_symbol_properties() { truth( "var s = Symbol('x'), t = {}; t[s] = 1; var p = new Proxy(new Proxy(t, {}), {}); - var freeze = type_error(function () { Object.freeze(p); }); - var seal = type_error(function () { Object.seal(p); }); - var extensible = Object.isExtensible(t); - Object.preventExtensions(t); - freeze && seal && extensible && type_error(function () { Object.isFrozen(p); }) && - type_error(function () { Object.isSealed(p); }) && Object.getOwnPropertyDescriptor(t, s).writable", + var before = !Object.isFrozen(p) && !Object.isSealed(p); + Object.freeze(p); + var d = Object.getOwnPropertyDescriptor(t, s); + before && Object.isFrozen(p) && Object.isSealed(p) && !d.writable && !d.configurable && t[s] === 1", ); truth( - "var p = new Proxy({}, {}); p[Symbol('x')] = 1; - type_error(function () { Object.freeze(p); }) && type_error(function () { Object.isFrozen(p); })", + "var s = Symbol('x'), t = {}; t[s] = 1; Object.preventExtensions(t); + var p = new Proxy(t, {}); + var open = !Object.isSealed(p); + Object.seal(p); + var d = Object.getOwnPropertyDescriptor(t, s); + open && Object.isSealed(p) && !Object.isFrozen(p) && d.writable && !d.configurable", ); truth( - "var p = new Proxy({}, { ownKeys: function () { p[Symbol('x')] = 1; return []; } }); - type_error(function () { Object.freeze(p); })", + "var s = Symbol('x'), p = new Proxy({}, { ownKeys: function () { return []; } }); + p[s] = 1; + Object.freeze(p); + Object.isFrozen(p) && !Object.getOwnPropertyDescriptor(p, s).writable", + ); +} + +#[test] +fn symbol_keys_pass_through_a_proxy_to_its_target() { + truth( + "var s = Symbol('x'), t = {}, p = new Proxy(t, {}); + Object.defineProperty(p, s, { value: 7, writable: true, configurable: true }); + var defined = t[s] === 7 && p[s] === 7 && Object.getOwnPropertySymbols(p)[0] === s; + p[s] = 8; + var written = t[s] === 8; + delete p[s]; + var self = null, u = {}; Object.defineProperty(u, s, { set: function () { self = this; } }); + var q = new Proxy(u, {}); q[s] = 1; + defined && written && !(s in t) && self === q && type_error(function () { + var pair = Proxy.revocable({}, {}); pair.revoke(); Object.defineProperty(pair.proxy, s, { value: 1 }); + })", ); } @@ -1244,7 +1295,7 @@ fn for_in_keeps_a_proxy_reachable_after_its_own_keys_trap_detaches_it() { })); var seen = []; for (var k in o) seen.push(k); - reads === 1 && seen.length === 0 && Object.getPrototypeOf(o) === null", + reads === 1 && seen.join() === 'first,second' && Object.getPrototypeOf(o) === null", ); } @@ -1295,6 +1346,18 @@ fn for_in_checks_proxy_descriptors_only_when_each_candidate_is_reached() { for (var k in p) { seen.push(k); calls.push('body'); } seen.join() === 'x' && calls.join() === 'x,body,y'", ); + // A name the proxy did not list is checked on the prototype that listed it, so the proxy's + // descriptor for it does not hide it. + truth( + "var asked = [], seen = []; + var p = new Proxy({}, { + ownKeys: function () { return []; }, + getPrototypeOf: function () { return { x: 1 }; }, + getOwnPropertyDescriptor: function (t, k) { asked.push(k); return { value: 0, enumerable: false, configurable: true }; } + }); + for (var k in p) seen.push(k); + seen.join() === 'x' && asked.length === 0", + ); } #[test] @@ -1475,6 +1538,19 @@ fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); } +#[test] +fn legacy_reflect_find_reads_a_proxy_receiver_without_its_traps() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var r = ({{ a: 1 }}).reflect, find = r.find, calls = 0; + var p = new Proxy(r, {{ getOwnPropertyDescriptor: function (t, k) {{ calls++; return Object.getOwnPropertyDescriptor(t, k); }} }}); + find.call(r, 'a') !== null && type_error(function () {{ find.call(p, 'a'); }}) && calls === 0" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + #[test] fn transparent_proxy_and_reflect_membership_use_host_indexers() { let index: HostFunction = Rc::new(|args| { @@ -1625,6 +1701,14 @@ fn json_proxy_replacer_lengths_use_to_length() { ); } +#[test] +fn json_replacer_lists_charge_only_the_names_they_keep() { + // A long, sparse replacer array keeps one name, so only that name counts against the heap. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let src = "var r = ['a']; r.length = 50000; JSON.stringify({ a: 1, b: 2 }, r) === '{\"a\":1}'"; + assert_eq!(Realm::with_options(es_options(), limits).run(src), Ok(JsValue::Bool(true))); +} + #[test] fn json_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { @@ -1650,13 +1734,19 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { ), LimitKind::Fuel ); + // A replacer list's length alone is not charged to the heap; the names it keeps are. let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run( + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : undefined; } }); + JSON.stringify({ a: 1 }, p) === '{}'" + ), + Ok(JsValue::Bool(true)) + ); assert_eq!( limit( - "var p = new Proxy([], { get: function (t, k) { - if (k === 'length') return 1000000; - throw new Error('element read'); - } }); JSON.stringify({}, p)", + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : 'name' + k; } }); + JSON.stringify({}, p)", limits, ), LimitKind::Heap diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index aeb4db0227..f71b1d3f42 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -254,7 +254,9 @@ impl Realm { /// `const` names earlier runs declared stay visible when it is turned off. A run begun with /// [`Realm::start`] that is still going keeps the language it started with for the code it /// evaluates; the new one applies once it ends. A realm made without the option gets `Proxy` - /// and `Reflect` at its first run with it, and keeps them when it is turned off. + /// and `Reflect` at its first run with it, and keeps them when it is turned off. A global of + /// either name that an earlier run defined keeps its value, and a global object that an + /// earlier run made non-extensible gets neither name. pub fn set_es2015(&mut self, es2015: bool) { if self.is_running() || self.interp.waiting { self.interp.next_es2015 = Some(es2015); diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 62c63c6bb0..2949ccba0c 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -328,15 +328,17 @@ fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult flat_charged(interp, &s)?, Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?, _ => continue, diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index e90652ec00..d4e451e766 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -315,8 +315,15 @@ impl Interp { self.reject(true, &name, why) } + /// The object that holds `id`'s Symbol-keyed properties: for a proxy, its innermost target, + /// since Symbol keys pass through proxies without traps; otherwise `id` itself. A revoked + /// proxy on the way is a `TypeError`. + pub(crate) fn sym_home(&mut self, id: ObjId) -> JsResult { + self.unwrapped_proxy_target(id) + } + pub(crate) fn get_own_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { - self.symbol_lookup_target(id)?; + let id = self.sym_home(id)?; Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) } @@ -326,13 +333,11 @@ impl Interp { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { + let o = self.sym_home(o)?; if let Some(p) = self.get_own_sym(o, k)? { return Ok(Some(p)); } - cur = match self.symbol_lookup_target(o)? { - Some(target) => Some(target), - None => self.object(o)?.proto, - }; + cur = self.object(o)?.proto; if cur.is_some() { self.use_fuel()?; } @@ -365,7 +370,7 @@ impl Interp { /// Adds or replaces an own property directly, keeping the heap estimate. pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> { - self.symbol_lookup_target(id)?; + let id = self.sym_home(id)?; let o = self.object_mut(id)?; if o.syms.get_or_insert_with(Box::default).insert(k, prop) { self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES); @@ -375,6 +380,7 @@ impl Interp { /// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key. pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult { + let id = self.sym_home(id)?; let Some(current) = self.get_own_sym(id, &k)? else { if !self.object(id)?.extensible { return self.reject_sym_bool(throw, &k, "the object is not extensible"); @@ -399,6 +405,9 @@ impl Interp { /// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key. pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> { + // A setter gets the object written to as `this`, a proxy included. + let receiver = Value::Object(id); + let id = self.sym_home(id)?; match self.get_own_sym(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -409,7 +418,7 @@ impl Interp { } return Ok(()); } - Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &receiver, &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), None => {} } @@ -417,6 +426,7 @@ impl Interp { let mut inherited = None; let mut steps = 0usize; while let Some(object) = cur { + let object = self.sym_home(object)?; if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) { return self.reject_sym(throw, &k, "a module namespace object is read-only"); } @@ -434,7 +444,7 @@ impl Interp { } } match inherited { - Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &receiver, &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"), _ => {} @@ -471,6 +481,7 @@ impl Interp { /// [[Delete]] (section 9.1.10) for a Symbol key. pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult { + let id = self.sym_home(id)?; match self.get_own_sym(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -490,7 +501,7 @@ impl Interp { /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and /// the heap for the list is checked first. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { - self.symbol_lookup_target(id)?; + let id = self.sym_home(id)?; let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { diff --git a/docs/mcp.md b/docs/mcp.md index 63ec896128..c7f3ecc035 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2867,8 +2867,8 @@ or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first ECMAScript 2015 run and keeps them for later `.jsx` runs. A `.jsx` script or a `source` string run as a script has neither global in a fresh engine. -Existing globals with either name are preserved. If a missing global cannot be added because the global object -is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. +Existing globals with either name are preserved. When an earlier run made the global object nonextensible, sealed +or frozen, the engine does not add either global, and its ECMAScript 2015 runs go on without them. An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)` and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor @@ -2891,7 +2891,8 @@ A conversion or syntax error throws before that prototype getter runs. membership checks use host collection indexers, including numeric indices and named items. `JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys -or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped. +or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped, +and each distinct name a replacer array keeps counts against it until the call returns. Its `toJSON` lookup skips host collection indexers through empty-handler proxies and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before @@ -2900,21 +2901,25 @@ the maximum safe integer. Reviver traversal keys count against the heap limit un In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating -its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations -and symbol enumeration on a revoked proxy also throw `TypeError`. -`Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, -then other strings in insertion order; an array's `length` precedes its other non-index strings. -A proxy's `ownKeys` trap determines its key order. A `for-in` prototype walk keeps the current proxy reachable -through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain. -A `for-in` loop checks each proxy candidate's descriptor -when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate +its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without +calling proxy traps, so a proxy receiver throws `TypeError`. A Symbol property key on a proxy goes to its innermost +target without calling a trap: reads, writes, definitions, deletion and descriptor reads act on that target's +Symbol properties. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. +The `Reflect` functions take Symbol keys as well as strings. `Reflect.ownKeys` returns the string keys, then the +Symbol keys in the order they were added; a proxy's Symbol keys are its innermost target's. Ordinary targets list +array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other +non-index strings. A proxy's `ownKeys` trap determines the order of its string keys. A `for-in` prototype walk keeps +the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from +the receiver's prototype chain. A `for-in` loop checks each name's descriptor when iteration reaches that name, +starting at the object on the prototype chain that listed it, so a proxy that did not list a name does not hide an +inherited one. An `ownKeys` result is read and its elements are validated before duplicate names are rejected; a later getter's exception takes precedence over the duplicate-name error. Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay reachable during proxy callbacks, including callbacks that revoke a nested target proxy. `Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Object.isFrozen` -and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties. +and `Object.isSealed` on a proxy include its innermost target's Symbol properties. `Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace object before it finds the property. `Reflect.getOwnPropertyDescriptor` and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. Proxy invariant diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 241ea00306..b6fb4090aa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1189,7 +1189,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key on a proxy goes to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. From da8e9cc197cbea035bdd840d6b70764934b250cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:03:36 -0800 Subject: [PATCH 32/60] xtask: test-lint census leaves out loops that run each entry through a computation A loop over a whole table whose body passes the entry to a call together with other state (a command run, a file written, a render, a parse of other input) checks behavior for each entry, so the census rule no longer reports it. A lookup, a call on the entry alone, literal arguments and calls in a failure message still count as a census. The call counts only where it runs whenever the loop's assertions pass: not after an `||`, not on the right of an `&&` whose result is not asserted, not inside an `if`, `else`, `match` arm, `while` or async body, and not inside a closure the loop never calls. A name counts as the entry from the `let` that binds it from the entry to the end of its block, and not where a nested loop, a closure parameter or another `let` rebinds it or where it names a field. An asserting helper keeps a loop out of the census only where it runs the same way, and a round trip can read the entry as its receiver (`k.parse()`). --- xtask/src/test_lint.rs | 799 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 793 insertions(+), 6 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 449885209f..9746b77bcd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -45,7 +45,9 @@ //! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of //! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`, //! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or -//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. A loop that +//! passes the entry to a call together with other state (a command run, a file written, a +//! render) is a table of behavior cases and is not reported; //! * `mirror`: `assert_eq!(f(a), f(b) …)`, where the expected side derives its value from a //! second call of the same function (same path) with arithmetic, so a fault in `f` moves both //! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same @@ -1173,6 +1175,11 @@ const COMMON: &[&str] = &[ /// The names called in `m[from..to]`: functions (`name(`, also through a path), methods /// (`.name(`), including calls with turbofish arguments, and macros (`name!`). fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + calls_at(m, from, to).into_iter().map(|(name, method, _)| (name, method)).collect() +} + +/// [`calls`] with the offset where each name starts. +fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(String, bool, usize)> { let m = &m[..to]; let mut out = vec![]; let mut i = from; @@ -1189,7 +1196,7 @@ fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { let name = String::from_utf8_lossy(&m[i..end]).into_owned(); let method = i > 0 && m[i - 1] == b'.'; if !KEYWORDS.contains(&name.as_str()) { - out.push((if bang { format!("{name}!") } else { name }, method)); + out.push((if bang { format!("{name}!") } else { name }, method, i)); } } i = end; @@ -1619,7 +1626,12 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let weak_in = |from: usize, to: usize, var: &str| { let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); let body = &unmessaged[from - v.t.open..to - v.t.open]; - helpers_in(from, to).is_empty() + // A helper counts only where it runs whenever the assertions pass, not after an `||`. + let (f, t) = (from + 1 - v.t.open, to - v.t.open); + let helper_runs = calls_at(&unmessaged, f, t).into_iter().any(|(n, method, at)| { + !(n.ends_with('!') && is_assert_macro(&n)) && is_helper_call(&n, method, helpers) && runs_with_assertion(&unmessaged, f, t, at) + }); + !helper_runs && !rejects(body) && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::>(), var)) @@ -1636,6 +1648,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { && helpers_in(kw + 2, open).is_empty() && words(m, b"break", open, close).is_empty() && weak_in(open, close, var) + && !feeds_entry(&unmessaged, &pattern, open + 1 - v.t.open, close - v.t.open) { return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; } @@ -1649,6 +1662,511 @@ fn census(v: &View, helpers: &HashSet) -> Vec { vec![] } +/// Calls that read or look up a value rather than compute one, so passing the entry to one of them +/// together with other state does not make the loop a behavior table. +const LOOKUPS: &[&str] = &[ + "contains", + "contains_key", + "starts_with", + "ends_with", + "get", + "get_mut", + "iter", + "into_iter", + "any", + "find", + "position", + "binary_search", + "eq", + "ne", + "find_map", +]; + +/// The lowercase names a `for` or `let` pattern binds. A field label (`Row { c: other }`) binds +/// the name after it. +fn pattern_names(pattern: &str) -> impl Iterator + '_ { + let b = pattern.as_bytes(); + pattern + .match_indices(|c: char| c.is_ascii_alphanumeric() || c == '_') + .filter(move |&(at, _)| at == 0 || !is_ident(b[at - 1])) + .map(move |(at, _)| (at, at + b[at..].iter().take_while(|&&c| is_ident(c)).count())) + .filter(move |&(at, end)| { + // Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`). + let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count(); + let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count(); + !in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':') + }) + .map(move |(at, end)| &pattern[at..end]) + .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) + .map(str::to_owned) +} + +/// Whether the body `b[from..to]` of a loop whose pattern is `pattern` feeds the entry into a +/// computation with other inputs: a call (not one of [`LOOKUPS`], nor a macro) whose receiver and +/// arguments include a value read from the entry and another value that is not a literal, such as +/// `app.run("…", json!({"id": id}))`, `export(&doc, &Options { level, .. })` or `check(SCHEMA, ¶ms)` +/// with `params` bound from the entry inside the loop. Such a loop runs, renders or writes something +/// for each entry, so it is a table of behavior cases. A call that takes the entry alone (`menu(c)`, +/// `Kind::from_id(k.id())`) is still a lookup. +fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { + // The names that hold the entry, each from the end of its binding to the end of its block. + let mut derived: Vec<(String, usize, usize)> = pattern_names(pattern).map(|n| (n, from, to)).collect(); + // Where a binding does not read the entry, the name holds another value until its scope ends. + let mut shadows: Vec<(String, usize, usize)> = vec![]; + for at in words(b, b"for", from, to) { + let Some(&kw) = words(b, b"in", at + 3, to).first() else { continue }; + let Some(open) = loop_open(b, kw + 2, to) else { continue }; + let Some(close) = matching(b, open).filter(|&c| c < to) else { continue }; + shadows.extend(pattern_names(&String::from_utf8_lossy(&b[at + 3..kw])).map(|n| (n, open + 1, close))); + } + // Simple closure parameters shadow captures in both block and expression bodies. + for at in from..to { + if b[at] != b'|' || b.get(at + 1) == Some(&b'|') { + continue; + } + let head = b[from..at].trim_ascii_end(); + let head = head.strip_suffix(b"move").unwrap_or(head).trim_ascii_end(); + if !head.is_empty() && !matches!(head.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) { + continue; + } + let Some(end) = (at + 1..to).find(|&i| b[i] == b'|') else { continue }; + // Parameters may carry types (`|c: Command|`, `|p: &[u8]|`). + if !b[at + 1..end] + .iter() + .all(|&c| is_ident(c) || c.is_ascii_whitespace() || matches!(c, b',' | b'&' | b':' | b'<' | b'>' | b'(' | b')' | b'[' | b']' | b'\'')) + { + continue; + } + let mut until = skip_ws(b, end + 1); + if b.get(until) == Some(&b'{') { + until = matching(b, until).unwrap_or(to).min(to); + } else { + while until < to && !matches!(b[until], b',' | b';' | b')' | b']' | b'}') { + until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 }; + } + } + // Each parameter binds the names before its type. + let params = String::from_utf8_lossy(&b[at + 1..end]).into_owned(); + let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); + shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); + } + // A field access (`options.c`) or a field label (`Row { c: x }`) names a field, not the binding. + let is_field = |at: usize, len: usize| { + b[..at].trim_ascii_end().last() == Some(&b'.') || { + let next = skip_ws(b, at + len); + b.get(next) == Some(&b':') && b.get(next + 1) != Some(&b':') + } + }; + let live = |f: usize, t: usize, names: &[(String, usize, usize)], shadows: &[(String, usize, usize)]| { + names.iter().any(|(n, since, until)| { + words(b, n.as_bytes(), f.max(*since), t.min(*until)) + .into_iter() + .any(|at| !is_field(at, n.len()) && !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z)) + }) + }; + // Names bound inside the loop from the entry count as the entry. + for at in words(b, b"let", from, to) { + let Some(eq) = + (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + else { + continue; + }; + let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); + let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + if live(eq + 1, end, &derived, &shadows) { + // Rebinding from the entry suspends earlier shadows until this block ends. + let until = block_close(b, at).min(to); + let mut resumed = vec![]; + for s in shadows.iter_mut().filter(|s| names.contains(&s.0) && s.1 <= at && at < s.2) { + if until < s.2 { + resumed.push((s.0.clone(), until, s.2)); + } + s.2 = end; + } + shadows.extend(resumed); + derived.extend(names.into_iter().map(|n| (n, end, until))); + } else { + let until = block_close(b, at).min(to); + shadows.extend(names.into_iter().filter(|n| derived.iter().any(|(d, _, _)| d == n)).map(|n| (n, end, until))); + } + } + let reads = |f: usize, t: usize| live(f, t, &derived, &shadows); + let literal = |s: &[u8]| { + let s = norm(s); + let s = s.trim_start_matches(['&', '*']); + // String, byte and raw literals keep their prefix after masking (`r"…"`, `b'…'`, `br#"…"#`). + let s = match s.find(['"', '\'']) { + Some(q) if q <= 3 && s[..q].bytes().all(|c| matches!(c, b'b' | b'c' | b'r' | b'#')) => &s[q..], + _ => s, + }; + // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. + // A minus sign makes a literal only in front of a number (`-2`, not `-offset`). + let s = s.strip_prefix('-').unwrap_or(s); + let mut start = 0; + let mut operands = 0; + let mut numeric = true; + for (i, c) in s.char_indices().chain([(s.len(), '+')]) { + if !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { + continue; + } + let head = &s[start..i]; + if i < s.len() + && matches!(c, '+' | '-') + && head + .strip_suffix(['e', 'E']) + .is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.bytes().all(|c| c.is_ascii_digit() || matches!(c, b'_' | b'.'))) + { + continue; + } + if !head.is_empty() { + operands += 1; + numeric &= numeric_literal(head); + } + start = i + c.len_utf8(); + } + let numeric = numeric && operands > 0; + s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None") + }; + (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { + let mut start = name_end; + while start > from && is_ident(b[start - 1]) { + start -= 1; + } + let name = String::from_utf8_lossy(&b[start..name_end]); + if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) { + return false; + } + let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; + let args = split_args(b, open + 1, close); + let mut inputs = args.clone(); + if start > from && b[start - 1] == b'.' { + // The receiver: the chain of names, calls and indexing before the dot. + let mut r = start - 1; + while r > from { + match b[r - 1] { + c if is_ident(c) || c == b'.' => r -= 1, + // A chain rustfmt splits over lines continues with a `.` after the line break. + c if c.is_ascii_whitespace() && b[r..start].iter().find(|c| !c.is_ascii_whitespace()) == Some(&b'.') => r -= 1, + b')' | b']' => match (from..r - 1).rev().find(|&o| matching(b, o) == Some(r - 1)) { + Some(o) => r = o, + None => break, + }, + _ => break, + } + } + inputs.push((r, start - 1)); + } + let fed = inputs.iter().any(|&(f, t)| reads(f, t)); + // A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only + // another argument (`u.parse(&text)`) makes it a computation. + let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs }; + let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(f, t)); + fed && other + }) +} + +/// Whether the whitespace-free `s` is one numeric literal (`1`, `0x1F`, `2.5f32`, `1_000`, `1e-3`), not +/// an expression that starts with one (`1+offset`, `1..limit`). +fn numeric_literal(s: &str) -> bool { + let b = s.as_bytes(); + let radix = match b.get(..2) { + Some(b"0x") => 16, + Some(b"0o") => 8, + Some(b"0b") => 2, + _ => 10, + }; + let mut i = if radix == 10 { 0 } else { 2 }; + let mut digits = 0; + while let Some(&c) = b.get(i) { + if (c as char).is_digit(radix) { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 || !b.first().is_some_and(u8::is_ascii_digit) { + return false; + } + if radix == 10 { + if b.get(i) == Some(&b'.') { + i += 1; + if i < b.len() && !b[i].is_ascii_digit() { + return false; + } + while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'_') { + i += 1; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + let mut digits = 0; + while let Some(&c) = b.get(i) { + if c.is_ascii_digit() { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 { + return false; + } + } + } + matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") +} + +/// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the +/// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. +fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { + let before = open; + if before > from && is_ident(b[before - 1]) { + return Some(before); + } + if before == from || b[before - 1] != b'>' { + return None; + } + let mut depth = 0usize; + for i in (from..before).rev() { + match b[i] { + b'>' if i == 0 || b[i - 1] != b'-' => depth += 1, + b'<' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + let head = b[from..i].trim_ascii_end(); + let end = head.strip_suffix(b"::")?.trim_ascii_end().len(); + return (end > 0 && is_ident(b[from + end - 1])).then_some(from + end); + } + } + b';' | b'{' | b'}' => return None, + _ => {} + } + } + None +} + +/// Whether a call starting at `start` in the loop body `b[from..to]` runs whenever the loop's +/// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`, +/// also with a block as the right operand); the right side of `&&` has to run only in an asserted +/// condition. A call inside a closure bound with `let` runs only when the loop calls +/// that closure. +fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { + runs_with_assertion_within(b, from, to, start, &[]) +} + +/// [`runs_with_assertion`], where `active` holds the calls whose check is in progress, so a closure +/// that calls itself does not recurse without end. +fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { + if active.contains(&start) { + return false; + } + let mut active = active.to_vec(); + active.push(start); + if in_uncalled_closure(b, from, to, start, &active) { + return false; + } + // Check enclosing blocks independently of the call's statement: an earlier semicolon inside + // a conditional block does not make its later statements run unconditionally. + for open in (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) { + let mut head = open; + while head > from { + head -= 1; + match b[head] { + b')' | b']' => { + let Some(back) = (from..head).rev().find(|&i| matching(b, i) == Some(head)) else { return false }; + head = back; + } + b';' | b'{' | b'}' => { + head += 1; + break; + } + _ => {} + } + } + let prefix = b[head..open].trim_ascii(); + if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { + if !runs_with_assertion_within(b, from, to, open, &active) { + return false; + } + } else if !prefix.ends_with(b"|") + && !(prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace)) + && (prefix.ends_with(b"=>") + || [b"async".as_slice(), b"async move"] + .iter() + .any(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) + || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) + || (!words(prefix, b"loop", 0, prefix.len()).is_empty() + && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) + { + // A nested `for` body is taken to run, like the loop body itself; [`feeds_entry`] keeps + // its own bindings apart. + return false; + } + } + // The statement starts after a `;` or an unmatched brace, except for the `{` of a block that is + // the operand of `||` or `&&`. + let mut stmt = from; + let mut braces = 0usize; + for i in (from..start).rev() { + match b[i] { + // A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`) + // unless an operator joins the call's expression to it. + b'}' if braces == 0 && { + let after = b[i + 1..start].trim_ascii_start(); + !(after.starts_with(b"||") || after.starts_with(b"&&") || after.starts_with(b".") || after.starts_with(b"?")) + } => + { + stmt = i + 1; + break; + } + b'}' => braces += 1, + b'{' if braces > 0 => braces -= 1, + b'{' => { + let before = b[from..i].trim_ascii_end(); + if !(before.ends_with(b"||") || before.ends_with(b"&&")) { + stmt = i + 1; + break; + } + } + b';' if braces == 0 => { + stmt = i + 1; + break; + } + _ => {} + } + } + // Only an operator at the call's own nesting level or an enclosing one counts, not one inside + // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; + // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. + // Earlier sibling elements cannot skip the call, but guards around their group still can. + let mut depth = 0usize; + let params = (stmt..start).find_map(|pipe| { + if b[pipe] != b'|' { + return None; + } + let head = b[stmt..pipe].trim_ascii(); + let head = head.strip_suffix(b"move").or_else(|| head.strip_suffix(b"async")).unwrap_or(head).trim_ascii_end(); + if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { + return None; + } + (pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end)) + }); + let mut closure = params.map(|(pipe, _)| pipe); + let mut sibling = false; + for i in (stmt + 1..start).rev() { + if params.is_some_and(|(pipe, end)| pipe <= i && i <= end) { + continue; + } + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => sibling = false, + b'(' | b'[' | b'{' => depth -= 1, + _ => {} + } + if depth != 0 { + continue; + } + if b[i] == b',' { + sibling = true; + } + if sibling { + continue; + } + if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') { + break; + } + if b[i] == b'&' + && b[i - 1] == b'&' + && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + && !asserted_conjunction(b, from, to, i - 1) + { + return false; + } + if b[i] == b'|' && b[i - 1] == b'|' { + let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); + let prefix = &b[stmt..end]; + let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); + let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); + if !moved + && !asynchronous + && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + { + return false; + } + closure = Some(stmt + prefix.len()); + } + } + // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. + let Some(end) = closure else { return true }; + let head = String::from_utf8_lossy(&b[stmt..end]); + let head = head.trim(); + let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true }; + let Some(name) = pattern_names(binding).last() else { return true }; + words(b, name.as_bytes(), end, to).into_iter().any(|at| { + // `other.run()` calls a method, not the closure. + b[..at].trim_ascii_end().last() != Some(&b'.') + && b.get(skip_ws(b, at + name.len())) == Some(&b'(') + && runs_with_assertion_within(b, from, to, at, &active) + }) +} + +/// Whether an `&&` is at the top level of an assertion's first argument. +fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool { + macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| { + let Some(&(mut f, mut t)) = a.args.first() else { return false }; + loop { + f += b[f..t].len() - b[f..t].trim_ascii_start().len(); + t = f + b[f..t].trim_ascii_end().len(); + if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) { + break; + } + f += 1; + t -= 1; + } + // A top-level `||` lets the assertion pass without the conjunction. + let cond = String::from_utf8_lossy(&b[f..t]); + f <= at && at < t && top_level_at(&cond, "||").is_empty() && top_level_at(&cond, "&&").contains(&(at - f)) + }) +} + +/// Whether `start` lies in the block body of a closure bound with `let` in +/// `b[from..to]` (`let run = || { … };`, also `move` or `async`) that the loop never calls. +fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { + let mut depth = 0usize; + for i in (from..start).rev() { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' if depth > 0 => depth -= 1, + b'{' if depth > 0 => depth -= 1, + b'{' => { + let Some(params) = b[from..i].trim_ascii_end().strip_suffix(b"|") else { continue }; + let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; + let head = params[..pipe].trim_ascii_end(); + let head = String::from_utf8_lossy(head); + let head = head.trim_end(); + let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue }; + let Some(name) = pattern_names(binding).last() else { continue }; + let close = matching(b, i).unwrap_or(to); + if !words(b, name.as_bytes(), close, to).into_iter().any(|at| { + b[..at].trim_ascii_end().last() != Some(&b'.') + && b.get(skip_ws(b, at + name.len())) == Some(&b'(') + && runs_with_assertion_within(b, from, to, at, active) + }) { + return true; + } + } + _ => {} + } + } + false +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -1881,8 +2399,8 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { /// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole /// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so /// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's -/// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is -/// not a round trip of the entry. +/// arguments (`Kind::from_id(k.id())`) or its receiver (`k.parse()`) must read the loop entry `var`; +/// a lookup of a fixed key is not a round trip of the entry. fn round_trip_call(op: &str, var: &str) -> bool { let mut op = op.trim_start_matches(['&', '*']); loop { @@ -1898,7 +2416,11 @@ fn round_trip_call(op: &str, var: &str) -> bool { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',', '&']) - && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) + && matching(op.as_bytes(), open).is_some_and(|close| { + // The entry is read in the arguments (`Kind::from_id(k.id())`) or is the receiver (`k.parse()`). + let receiver = op[..at].strip_suffix('.').is_some_and(|r| reads_ident(r, var)); + only_unwraps(&op[close + 1..]) && (receiver || reads_ident(&op[open + 1..close], var)) + }) }) }) } @@ -7307,4 +7829,269 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn census_follows_the_calls_that_run_for_each_entry() { + let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| census_in(&loop_of(body)); + assert_eq!(census("assert!(menu(c).is_some() || verify_fallback(c).is_ok());"), [(2, "census")], "a helper after || can be skipped"); + assert_eq!(census("assert!(menu(c).is_some() && verify_fallback(c).is_ok());"), [], "a helper after && runs"); + assert_eq!(census("assert!(menu(c).is_some()); { let c = fallback(); app.run(c); }"), [(2, "census")], "a shadowed entry name"); + assert_eq!(census("assert!(menu(c).is_some()); app.run(c);"), [], "the entry itself"); + assert_eq!(census("let _run = || app.run(c); assert!(menu(c).is_some());"), [(2, "census")], "a closure that is never called"); + assert_eq!( + census("let _run = || { let r = app.run(c); r }; assert!(menu(c).is_some());"), + [(2, "census")], + "a block closure that is never called" + ); + assert_eq!(census("let run = || { let r = app.run(c); r }; assert!(run().is_ok());"), [], "a block closure the loop calls"); + assert_eq!( + census("let params = fallback(); app.run(params); let params = c; assert!(menu(c).is_some());"), + [(2, "census")], + "a binding from the entry does not reach back to an earlier use of its name" + ); + assert_eq!( + census("{ let params = c; } app.run(params); assert!(menu(c).is_some());"), + [(2, "census")], + "a binding from the entry ends with its block" + ); + assert_eq!(census("app.run(options.c); assert!(menu(c).is_some());"), [(2, "census")], "a field with the entry's name"); + assert_eq!(census("assert!(app.run::(c).is_ok());"), [], "a call with a turbofish"); + assert_eq!(census("assert!(menu::(c).is_some());"), [(2, "census")], "an entry-only call with a turbofish"); + assert_eq!(census("assert!(render(c, -offset).is_ok());"), [], "a negated variable is another input"); + assert_eq!(census("assert!(render(c, -2).is_ok());"), [(2, "census")], "a negative literal is not"); + assert_eq!( + census("let _ = menu(c).is_some() || { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a block on the right of || can be skipped" + ); + assert_eq!( + census("let _ = menu(c).is_some() || { foo(); app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a semicolon keeps the enclosing ||" + ); + assert_eq!(census("assert!(menu(c).is_some() && { foo(); app.run(c).is_ok() });"), [], "a semicolon keeps the enclosing &&"); + assert_eq!( + census("let _ = (menu(c).is_some() || other(c).is_some()) && { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a discarded conjunction can skip the block when its left side is false" + ); + assert_eq!(census("assert!(menu(c).is_some()); if first || second {} app.run(c);"), [], "an || in a finished if does not skip the call"); + assert_eq!( + census("let entry = c; let c = fallback(); let c = entry; assert!(menu(c).is_some()); app.run(c);"), + [], + "a name rebound from the entry is the entry again" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; } assert!(menu(entry).is_some()); app.run(c);"), + [(2, "census")], + "an inner entry binding does not end the outer fallback binding" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; app.run(c); } assert!(menu(entry).is_some());"), + [], + "the inner entry binding is live inside its block" + ); + assert_eq!( + census("let Row { c: other } = fallback(); assert!(menu(c).is_some()); app.run(c);"), + [], + "a field label does not rebind the entry" + ); + let receiver = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(k.parse(), k);\n }\n}\n"; + assert_eq!(census_in(receiver), [(2, "census")], "a round trip with the entry as receiver"); + let fixed = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(registry.lookup(\"baseline\"), k);\n }\n}\n"; + assert_eq!(census_in(fixed), [], "a lookup of a fixed key"); + } + + #[test] + fn census_follows_conditions_and_scopes_around_the_call() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _ = false && app.run(c).is_ok(); assert!(menu(c).is_some());"), + [(2, "census")], + "a discarded conjunction can skip the call" + ); + assert_eq!( + census("let ok = ready && app.run(c).is_ok(); assert!(menu(c).is_some());"), + [(2, "census")], + "a bound conjunction can skip the call" + ); + assert_eq!(census("debug_assert!(menu(c).is_some() && app.run(c).is_ok());"), [], "an asserted conjunction requires the call"); + assert_eq!( + census("assert!(other(c).is_some() && app.run(c).is_ok() || menu(c).is_some());"), + [(2, "census")], + "an || after the conjunction lets the assertion pass without it" + ); + assert_eq!(census("let _ = &&app.run(c); assert!(menu(c).is_some());"), [], "a double borrow does not short-circuit the call"); + assert_eq!( + census("let run = || app.run(c); assert!(menu(c).is_some() || run().is_ok());"), + [(2, "census")], + "a closure invocation after || can be skipped" + ); + assert_eq!( + census("let run = || { app.run(c) }; assert!(menu(c).is_some() || run().is_ok());"), + [(2, "census")], + "a block closure invocation after || can be skipped" + ); + assert_eq!(census("let run = || app.run(c); assert!(run().is_ok());"), [], "a closure invocation required by the assertion runs"); + assert_eq!( + census("let run = || app.run(c); other.run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a method of the same name does not call the closure" + ); + assert_eq!( + census("let run = || app.run(c).and(run()); assert!(menu(c).is_some());"), + [(2, "census")], + "a recursive closure does not establish that its body runs" + ); + assert_eq!(census("if false { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an if can skip the call"); + assert_eq!(census("if flag {} else { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an else can skip the call"); + assert_eq!( + census("match flag { true => { app.run(c); }, false => {} } assert!(menu(c).is_some());"), + [(2, "census")], + "a match arm can skip the call" + ); + assert_eq!(census("while flag { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a while can skip the call"); + assert_eq!(census("let entry = c; { let c = entry; app.run(c); } assert!(menu(c).is_some());"), [], "a plain block runs"); + assert_eq!(census("for c in defaults() { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a nested loop shadows the entry"); + assert_eq!(census("for c in app.defaults(c) { app.run(c); } assert!(menu(c).is_some());"), [], "the loop source reads the outer entry"); + assert_eq!( + census("for c in defaults() { let params = c; app.run(params); } assert!(menu(c).is_some());"), + [(2, "census")], + "a nested binding stays shadowed through aliases" + ); + assert_eq!(census("for c in defaults() {} app.run(c); assert!(menu(c).is_some());"), [], "the nested loop's shadow ends with its body"); + assert_eq!(census("for x in 0..3 { app.run(c, x); } assert!(menu(c).is_some());"), [], "a nested loop body runs the call"); + assert_eq!( + census("let run = |c| app.run(c); run(default()); assert!(menu(c).is_some());"), + [(2, "census")], + "a closure parameter shadows the entry" + ); + assert_eq!( + census("let run = |other| app.run(c); run(default()); assert!(menu(c).is_some());"), + [], + "another closure parameter keeps the entry" + ); + assert_eq!( + census("let run = |c| { app.run(c); }; run(default()); assert!(menu(c).is_some());"), + [(2, "census")], + "a block closure parameter shadows the entry" + ); + assert_eq!( + census("let run = |other| { app.run(c); }; run(default()); assert!(menu(c).is_some());"), + [], + "a called block closure keeps its capture" + ); + } + + #[test] + fn census_follows_block_initializers_argument_guards_and_parameterized_closures() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("let result = { verify(c) }; assert!(result.is_ok());"), [], "a block initializer runs its helper"); + assert_eq!( + census("let _future = async { app.run(c); }; assert!(menu(c).is_some());"), + [(2, "census")], + "an unpolled async block does not run its body" + ); + assert_eq!( + census("let result = if ready { verify(c) } else { Ok(()) }; assert!(result.is_ok());"), + [(2, "census")], + "a conditional initializer can skip its helper" + ); + assert_eq!( + census("let _ = false && accept(0, app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an enclosing conjunction survives argument commas" + ); + assert_eq!(census("let _ = accept(flag || other, app.run(c)); assert!(menu(c).is_some());"), [], "a sibling argument cannot skip the call"); + assert_eq!( + census("let _ = ready || accept(0, app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an enclosing disjunction survives argument commas" + ); + assert_eq!( + census("let _ = ready && accept((flag || other, 0), app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a nested sibling keeps the enclosing guard" + ); + assert_eq!(census("assert!(ready && accept(0, app.run(c)));"), [], "an asserted enclosing conjunction requires the argument"); + assert_eq!(census("let _ = accept(0, { app.run(c) }); assert!(menu(c).is_some());"), [], "an argument block runs"); + assert_eq!( + census("let _run = |_: ()| app.run(c); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled typed closure can skip its body" + ); + assert_eq!(census("let run = |_: ()| app.run(c); assert!(run(()).is_ok());"), [], "an asserted typed closure invocation runs its body"); + assert_eq!( + census("let run = move |x| app.run(c, x); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled move closure can skip its body" + ); + assert_eq!(census("let run = move |x| app.run(c, x); assert!(run(0).is_ok());"), [], "an asserted move closure invocation runs its body"); + assert_eq!( + census("let run = |_: ()| app.run(c); assert!(menu(c).is_some() || run(()).is_ok());"), + [(2, "census")], + "a guarded typed closure invocation can skip its body" + ); + assert_eq!( + census("let run = |c: Command| app.run(c); run(default()); assert!(menu(c).is_some());"), + [(2, "census")], + "a typed closure parameter shadows the entry" + ); + } + + #[test] + fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let run = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app.session.execute(CMD, &json!({\"way\": k})).is_ok());\n }\n}\n"; + assert_eq!(census(run), [], "a command run for each entry"); + let split = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app\n .run(k)\n .is_ok());\n }\n}\n"; + assert_eq!(census(split), [], "a chain split over lines keeps its receiver"); + let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n"; + assert_eq!(census(rendered), [], "a file written for each entry"); + let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(check_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; + assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema"); + let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n"; + assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census"); + let alone = "#[test]\nfn t() {\n for c in COMMANDS {\n let m = menu(c);\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(alone), [(2, "census")], "a call on the entry alone is a lookup"); + let constant = + "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c, 2, \"x\", r\"y\", b'z', br#\"w\"#).is_some());\n }\n}\n"; + assert_eq!(census(constant), [(2, "census")], "literal arguments are not other inputs"); + let message = "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some(), \"{}\", app.describe(c));\n }\n}\n"; + assert_eq!(census(message), [(2, "census")], "a call in a failure message runs only after a failure"); + let closure = "#[test]\nfn t() {\n let tree = tree();\n for p in PLACES {\n let m = tree.iter().find(|t| t == p).map(|(_, items)| items.len());\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(closure), [(2, "census")], "a closure passed along a lookup is not another input"); + let registry = "#[test]\nfn t() {\n let registry = registry();\n for k in Kind::ALL {\n assert_eq!(registry.lookup(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip"); + let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n"; + assert_eq!(census(parsed), [], "parsing other input with each entry computes a result"); + let skipped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() || app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(skipped), [(2, "census")], "a call after || may never run"); + let joined = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(joined), [], "a call after && runs whenever the assertion passes"); + let grouped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!((menu(c).is_some() || other(c).is_some()) && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(grouped), [], "an || inside an earlier group does not skip the call"); + let deferred = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(deferred), [], "a zero-argument closure feeds the entry into a computation"); + let moved = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = move || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(moved), [], "a move closure feeds the entry into a computation"); + let deferred_async = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = async || app.run(c);\n assert!(block_on(run()).is_ok());\n }\n}\n"; + assert_eq!(census(deferred_async), [], "an async closure feeds the entry into a computation"); + let sibling = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let result = (flag || other, app.run(c));\n assert!(result.1.is_ok());\n }\n}\n"; + assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); + } + + #[test] + fn numeric_literals_are_one_token() { + for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] { + assert!(numeric_literal(s), "{s}"); + } + for s in ["1+offset", "1..limit", "1usize-offset", "1<<4"] { + assert!(!numeric_literal(s), "{s}"); + } + } } From 7e3feff63111a8ed93e9293b5a8bd09d6a0c7fa5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:32:34 -0800 Subject: [PATCH 33/60] Tests: drop a String-to-String conversion in the sealed-global proxy test Clippy's useless_conversion lint stopped the gate at crates/js/src/proxy_tests.rs:127, where `names.clone().into()` converted a String to itself. The assertion compares the same value. --- crates/js/src/proxy_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 01495b4fc5..cac32535b4 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -124,7 +124,7 @@ fn late_proxy_and_reflect_installation_respects_global_extensibility() { // ES2015 runs go on without the names the sealed global lacks. let names = format!("{} {}", if has_proxy { "number" } else { "undefined" }, if has_reflect { "number" } else { "undefined" }); for _ in 0..2 { - assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String(names.clone().into())), "{operation}: {setup}"); + assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String(names.clone())), "{operation}: {setup}"); } realm.set_es2015(false); let check = format!( From 8a3fe259e8f4f55a0bc8d204c1a539bfa5e7ba02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:41:23 -0800 Subject: [PATCH 34/60] Print: file.print in the app passes maxPages on to the engine The app's file.print forwarded preset, settings, format, level and flattenerPreset to the engine but dropped maxPages, so a script that set a page limit through Document.print (added in #9087) still printed or saved every page. The app now forwards it, returns the engine's {pages, format} without printing or saving when the job is past the limit, and passes an explicit null on so the engine rejects it instead of treating it as no limit. The command text in both catalogs lists the parameter. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/tests_print.rs | 26 +++++++++++++++++++++++ crates/ui-egui/src/io/export.rs | 5 +++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/print.rs | 9 ++++++-- 5 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 6852f317b3..e9e85a3e0d 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", ), ( "print.printers", diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 183d6f1056..137b9dffb7 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -620,3 +620,29 @@ fn every_number_and_length_field_is_named() { } } } + +#[test] +fn print_past_max_pages_neither_prints_nor_saves() { + // Three artboards × 2 copies is 6 pages: a limit of 5 sends no job. + let (mut app, jobs) = app(); + let r = app.run("file.print", json!({"settings": {"copies": 2}, "maxPages": 5})).unwrap(); + assert_eq!(r, json!({"pages": 6, "format": "pdf"})); + assert!(jobs.borrow().is_empty(), "nothing is sent"); + // Within the limit the job prints as before. + let r = app.run("file.print", json!({"settings": {"copies": 2}, "maxPages": 6})).unwrap(); + assert_eq!((r["pages"].clone(), r["printed"].clone()), (json!(6), json!(true))); + assert_eq!(jobs.borrow().len(), 1); + // Saved to a path, a job past the limit writes nothing. + let written: Written = Rc::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { + w.borrow_mut().push((p.to_string(), b.to_vec())); + Ok(()) + })); + let r = app.run("file.print", json!({"path": "/tmp/job.pdf", "settings": {"copies": 2}, "maxPages": 5})).unwrap(); + assert_eq!(r, json!({"pages": 6, "format": "pdf"})); + assert!(written.borrow().is_empty(), "nothing is written"); + // A null limit is an error, not "no limit". + assert!(app.run("file.print", json!({"maxPages": null})).is_err()); + assert_eq!(jobs.borrow().len(), 1, "nothing more is sent"); +} diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index c82c4c76de..7f95ad3249 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -351,6 +351,11 @@ fn write_output( then: impl FnOnce(&mut VectorcraftApp, String, Value) -> Result + 'static, ) -> Result { let mut v = app.session.execute(id, ¶ms).map_err(|e| e.to_string())?; + // `file.print` past its `maxPages` composes nothing: its `{pages, format}` is the answer and no + // file is written. + if params.get("maxPages").is_some() && v.get("dataBase64").is_none() { + return Ok(v); + } let bytes = take_output(&mut v)?; let write = move |app: &mut VectorcraftApp, path: String| { write_reporting(app, &path, &bytes)?; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index b4cf91497d..084c74d168 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", ), ( "print.printers", diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 61860ee915..e5bc13c6e0 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -148,8 +148,9 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let postscript = s("format").as_deref() == Some("postscript") || s("path").is_some_and(|path| fileio::extension(&path) == "ps"); let to_file = p.get("toFile").and_then(Value::as_bool).unwrap_or(false) || s("path").is_some() || postscript; let mut q = json!({}); - for k in ["preset", "settings", "format", "level", "flattenerPreset"] { - if let Some(v) = p.get(k).filter(|v| !v.is_null()) { + for k in ["preset", "settings", "format", "level", "flattenerPreset", "maxPages"] { + // An explicit null `maxPages` goes on, so the engine rejects it instead of printing every page. + if let Some(v) = p.get(k).filter(|v| !v.is_null() || k == "maxPages") { q[k] = v.clone(); } } @@ -175,6 +176,10 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { q["forPrinter"] = json!(true); } let mut v = app.session.execute("file.print", &q).map_err(|e| e.to_string())?; + // A job past `maxPages` is not composed: the reply is `{pages, format}` and nothing is sent. + if q.get("maxPages").is_some() && v.get("dataBase64").is_none() { + return Ok(v); + } let data = v.as_object_mut().and_then(|o| o.remove("dataBase64")); let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?; let title = app.session.active().map(|d| d.title()).unwrap_or_default(); From cbd1936ae65ebbb5bbda6720e3280c1b59515587 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:45:37 -0800 Subject: [PATCH 35/60] xtask: test-lint no longer reports helper, diagnostic and fixed-size false alarms no-assertion: - A call in a top-level test reaches the helper its own file defines. A non-asserting helper of the same name in another file of the crate no longer hides it. Names the file also calls with a path, and definitions below the file's top level, keep the crate's verdict. - An `#[ignore = "reason"]` test that prints is a diagnostic and needs no assertion. - An asserting function passed by name as a value (`keeping_settings(the_body)`, `run(&[body])`) counts as the test's check, also through a helper that passes it, unless a local binding, loop pattern, match arm or parameter shadows the name in scope, or the value is dropped (`drop(body)`, `let _ = Some(body)`, `(body,);`). all-unguarded: - A parenthesized range of literals or constants, `(0..3).all(...)`. - A receiver whose source an earlier `assert_eq!` compares with a non-empty literal: a local collected from the receiver, or the call the receiver is bound to, when nothing changes the source in between. A shared borrow passed to a call outside an assertion may change it. - A call to a function of the file that lists every row of a non-empty constant table without filtering it; every function of that name in the file has to do so. --- xtask/src/test_lint.rs | 788 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 765 insertions(+), 23 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 449885209f..f6b8a6e2b1 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -16,8 +16,12 @@ //! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, //! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later //! code may shrink or replace them; and fields the file declares only as arrays of a positive -//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change -//! anywhere in the test counts as a change to the hit; +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. Also +//! left out: a parenthesized range of literals or constants (`(0..3).all(…)`); a receiver whose +//! source an earlier equality assertion compares with a non-empty literal (a local bound from the +//! receiver, or the call the receiver is bound to), when nothing changes the source in between; +//! and a call to a function of the file that lists every row of a non-empty constant table +//! without filtering it. A change anywhere in the test counts as a change to the hit; //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that @@ -26,7 +30,10 @@ //! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no //! output, with a status check in any condition or compared operand of a standard assertion; //! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, -//! and no `#[should_panic]`; +//! and no `#[should_panic]`. An asserting helper passed by name as a value +//! (`keeping_settings(the_body)`) counts, unless a local binding or parameter shadows the name, +//! and so does an `#[ignore = "…"]` test that prints. A top-level test's call reaches the helper +//! of its own file when the file defines one of that name at its top level; //! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value //! from the code under test. Left out: a return after an assertion in its block, one whose //! statement or line has a comment or a printed note saying why, and guards on files, fonts, @@ -1315,35 +1322,92 @@ fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { type Def = (String, bool, Vec); /// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test -/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. Each file of `files` +/// also gets an entry under its path ([`helpers_for`]): a call in a top-level test reaches the +/// function of that name the file defines only when all its definitions are at the file's top +/// level and the file does not call that name with a path. Other names keep the crate's verdict. pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { let mut defs: HashMap> = HashMap::new(); + // Each file's path, its definitions, and the names its own definitions decide. + let mut by_file: Vec<(&str, Vec, HashSet)> = vec![]; for (path, src) in files { let m = mask(src); let regions = test_regions(path, &m, &tests_in(&m)); - let crate_defs = defs.entry(crate_of(path)).or_default(); - for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { - if in_regions(®ions, at) { - crate_defs.extend(definition(&m, at)); - } - } + let depths = brace_depths(&m); + let mut nested = HashSet::new(); + let own: Vec = words(&m, b"fn", 0, m.len()) + .into_iter() + .chain(words(&m, b"macro_rules", 0, m.len())) + .filter(|&at| in_regions(®ions, at)) + .filter_map(|at| { + let def = definition(&m, at)?; + if depths[at] != 0 { + nested.insert(def.0.clone()); + } + Some(def) + }) + .collect(); + // A call with a path (`other::near(…)`) may reach another module's function, and calls + // keep only the last name, so a name the file also calls with a path keeps the crate's + // verdict. A definition below the file's top level also keeps the crate's verdict. + let names = own.iter().map(|d| d.0.clone()).filter(|n| !nested.contains(n) && !called_with_path(&m, n)).collect(); + defs.entry(crate_of(path)).or_default().extend(own.iter().cloned()); + by_file.push((path, own, names)); } let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); - defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() + let mut out: HashMap> = defs + .iter() + .map(|(krate, own)| (krate.clone(), checking(HashSet::new(), own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))) + .collect(); + for (path, own, names) in by_file { + if names.is_empty() { + continue; + } + let base = out.get(&crate_of(path)).map(|set| set.difference(&names).cloned().collect()).unwrap_or_default(); + out.insert(path.to_owned(), checking(base, own.iter().filter(|d| names.contains(&d.0)))); + } + out +} + +/// Whether the masked file names `name` (a function, or `name!` for a macro) after a `::` path. +fn called_with_path(m: &[u8], name: &str) -> bool { + let name = name.trim_end_matches('!'); + words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::")) +} + +/// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's +/// own entry of [`asserting_helpers`] if present; otherwise, its crate's. +fn helpers_for<'a>(ctx: &'a Ctx, path: &str, top_level: bool) -> Option<&'a HashSet> { + if top_level { ctx.helpers.get(path).or_else(|| ctx.helpers.get(&crate_of(path))) } else { ctx.helpers.get(&crate_of(path)) } +} + +/// The brace depth before each byte of masked text. +fn brace_depths(m: &[u8]) -> Vec { + let mut depth = 0usize; + m.iter() + .map(|&c| { + let before = depth; + match c { + b'{' => depth += 1, + b'}' => depth = depth.saturating_sub(1), + _ => {} + } + before + }) + .collect() } /// The crate whose test helpers every crate can call. const TESTKIT: &str = "crates/testkit"; -/// The names among `defs` that check something, directly or through another of `defs`. Calls do -/// not say which of several functions with one name they reach, so a name counts only when every -/// definition with that name checks. -fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { +/// `known` and the names among `defs` that check something, directly or through another of +/// `defs` or a name of `known`. Calls do not say which of several functions with one name they +/// reach, so a name counts only when every definition with that name checks. +fn checking<'a>(mut known: HashSet, defs: impl Iterator + Clone) -> HashSet { let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); for d in defs { by_name.entry(d.0.as_str()).or_default().push(d); } - let mut known: HashSet = HashSet::new(); loop { let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); let more: Vec = by_name @@ -1380,7 +1444,14 @@ fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { fn definition(m: &[u8], at: usize) -> Option { let (name, is_macro, open, close) = item_at(m, at)?; let name = String::from_utf8_lossy(name).into_owned(); - let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + let called = calls(m, open, close) + .into_iter() + .filter(|(_, method)| !method) + .map(|(n, _)| n) + .chain( + passed_names(m, open, close).into_iter().filter(|(name, pos)| !shadows_helper(m, at, open, close, name.as_bytes(), *pos)).map(|(n, _)| n), + ) + .collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1391,6 +1462,8 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// The brace depth before each byte of [`File::m`] ([`brace_depths`]). + depths: Vec, /// [`File::m`] with the functions and macros declared inside each test blanked: declaring /// one does not run its body ([`executed`]). exec: Vec, @@ -1435,11 +1508,12 @@ impl File<'_> { /// Every hit in one file, exemptions applied. pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); + let depths = brace_depths(&m); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); let exec = executed(&m, &tests); let cfgs = cfg_spans(&m, src.as_bytes()); - let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions, cfgs }; + let file = File { path, src: src.as_bytes(), m, depths, exec, lines: Lines::new(src), tests, regions, cfgs }; let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); hits.extend(ignore_hits(&file)); hits.extend(sleep_hits(&file)); @@ -1493,19 +1567,24 @@ struct View<'a> { delegates: bool, checks: bool, should_panic: bool, + /// An ignored test with a reason that prints what it measures ([`ignored_with_reason`], + /// [`prints`]): a diagnostic run by hand, which has nothing to assert. + diagnostic: bool, } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { let m = &file.exec; let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); let none = HashSet::new(); - let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); + let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); let delegates = calls(m, t.open, t.close) .iter() - .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) + || passes_helper(m, t, helpers); let checks = checks_itself(m, t.open, t.close); let should_panic = should_panic_attr(m, t.attr, t.fn_at); - let v = View { file, t, asserts, delegates, checks, should_panic }; + let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close); + let v = View { file, t, asserts, delegates, checks, should_panic, diagnostic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); hits.extend(early_returns(&v)); @@ -1517,6 +1596,183 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits } +/// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple +/// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings +/// and parameters that shadow helper names. +fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { + passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| { + name != t.name + && !COMMON.contains(&name.as_str()) + && helpers.contains(&name) + && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos) + }) +} + +/// Whether a parameter of the function at `at` (body `open..close`), or a local binding in scope at +/// `pos`, shadows the helper `name`. +fn shadows_helper(m: &[u8], at: usize, open: usize, close: usize, name: &[u8], pos: usize) -> bool { + binds_parameter(&m[at..=open], name) || bound_at(&m[open + 1..close], name, pos - (open + 1)) +} + +/// Whether a binding of `name` in `body` is in scope at `pos`: a `let` from the end of its statement +/// to the end of its block (an `if let` or `while let` in its block only), a `for` pattern in the +/// loop body, a match-arm pattern inside its arm, or a closure parameter inside the closure's body. +fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { + let lets = words(body, b"let", 0, pos).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + if words(body, name, start, end).is_empty() { + return false; + } + let head = body[..at].trim_ascii_end(); + let conditional = + [&b"if"[..], b"while"].into_iter().any(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); + if conditional { + return let_body(body, start).is_some_and(|(_, open, close)| open < pos && pos < close); + } + statement_end(body, at) < pos && pos < block_close(body, at) + }); + let loops = words(body, b"for", 0, pos).into_iter().any(|at| { + let Some((open, close)) = block_after(body, at + 3) else { return false }; + let Some(&in_at) = words(body, b"in", at + 3, open).first() else { return false }; + open < pos && pos < close && !words(body, name, at + 3, in_at).is_empty() + }); + let name = String::from_utf8_lossy(name); + lets || loops || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() +} + +/// The innermost unclosed `(`, `[` or `{` before `at`. +fn enclosing_open(m: &[u8], at: usize) -> Option { + let mut depth = 0usize; + for i in (0..at).rev() { + match m[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => return Some(i), + b'(' | b'[' | b'{' => depth -= 1, + _ => {} + } + } + None +} + +/// The bare identifiers, with their offsets, passed as arguments or as tuple or array elements in +/// the body between `open` and `close`. An element of a tuple, array or constructor counts only +/// where its value is kept: not in a statement of its own (`(body,);`), a `let _` or `let _name` +/// binding, or a `drop` or `forget` call. +fn passed_names(m: &[u8], open: usize, close: usize) -> Vec<(String, usize)> { + let mut names = Vec::new(); + let mut at = open + 1; + while at < close { + if !is_ident(m[at]) || (at > 0 && (is_ident(m[at - 1]) || m[at - 1] == b'.')) { + at += 1; + continue; + } + let end = at + m[at..close].iter().take_while(|&&c| is_ident(c)).count(); + let before = m[..at].trim_ascii_end().last().copied(); + let after = m.get(skip_ws(m, end)).copied(); + if matches!(before, Some(b'(' | b'[' | b',')) && matches!(after, Some(b')' | b']' | b',')) && value_kept(m, open, at) { + names.push((String::from_utf8_lossy(&m[at..end]).into_owned(), at)); + } + at = end; + } + names +} + +/// Whether the element at `at` is a call's argument, or sits in a tuple or array whose statement +/// keeps it ([`passed_names`]). +fn value_kept(m: &[u8], open: usize, at: usize) -> bool { + let Some(mut group) = enclosing_open(m, at).filter(|&g| g > open) else { return false }; + // A name in a `let` or `for` pattern (`let (body,) = …`) binds a value rather than passing one. + let from = m[open + 1..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(open + 1, |p| open + 2 + p); + if words(m, b"let", from, at).last().is_some_and(|&l| !m[l..at].contains(&b'=')) + || words(m, b"for", from, at).last().is_some_and(|&f| words(m, b"in", f, at).is_empty()) + { + return false; + } + loop { + let head = m[..group].trim_ascii_end(); + let call = m[group] != b'{' && head.last().is_some_and(|&c| is_ident(c) || c == b'!' || c == b'>'); + let mut start = group; + if call { + // A call runs even when its result is dropped; constructors only store the value. + let name = &head[head.len() - head.iter().rev().take_while(|&&c| is_ident(c)).count()..]; + let constructor = name.first().is_some_and(u8::is_ascii_uppercase) || head.ends_with(b"!") || head.ends_with(b"::new"); + if !constructor { + return !matches!(name, b"drop" | b"forget"); + } + start = head.len() - head.iter().rev().take_while(|&&c| is_ident(c) || matches!(c, b':' | b'!')).count(); + } + if let Some(outer) = enclosing_open(m, group).filter(|&g| g > open && m[g] != b'{') { + group = outer; + continue; + } + let statement = m[..start].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let statement = m[statement..start].trim_ascii(); + // `let _ = …` and `let _name = …` drop or ignore the value. + let discarded = statement + .strip_prefix(b"let") + .filter(|r| r.first().is_some_and(u8::is_ascii_whitespace)) + .is_some_and(|r| r.trim_ascii_start().starts_with(b"_")); + return !discarded && !statement.iter().all(|&c| c.is_ascii_whitespace() || c == b'&'); + } +} + +/// Whether a function or closure in `body` takes a parameter that binds `name`. +fn binds_parameter(body: &[u8], name: &[u8]) -> bool { + let binds = |from, to| { + split_args(body, from, to).into_iter().any(|(start, end)| { + let pattern = &body[start..end]; + let end = pattern.iter().position(|&c| c == b':').unwrap_or(pattern.len()); + !words(pattern, name, 0, end).is_empty() + }) + }; + if words(body, b"fn", 0, body.len()).into_iter().any(|at| { + let Some(open) = body[at + 2..].iter().position(|&c| c == b'(').map(|p| at + 2 + p) else { return false }; + matching(body, open).is_some_and(|close| binds(open + 1, close)) + }) { + return true; + } + let mut at = 0; + while at < body.len() { + let head = body[..at].trim_ascii_end(); + let opens = head.last().is_some_and(|c| matches!(c, b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"return", b"=>"].iter().any(|word| head.ends_with(word)); + if body[at] == b'|' && opens { + let Some(close) = body[at + 1..].iter().position(|&c| c == b'|').map(|p| at + 1 + p) else { return false }; + if binds(at + 1, close) { + return true; + } + at = close; + } + at += 1; + } + false +} + +/// Whether the attributes in `file.m[from..to]` include `#[ignore = "…"]` with a non-blank reason. +fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool { + let m = &file.m; + words(m, b"ignore", from, to).into_iter().any(|at| { + let j = skip_ws(m, at + "ignore".len()); + m[..at].ends_with(b"#[") + && m.get(j) == Some(&b'=') + && ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + }) +} + +/// Whether the masked text prints: `println!`, `eprintln!`, `print!` or `eprint!`. +fn prints(m: &[u8], from: usize, to: usize) -> bool { + macro_calls(m, from, to).iter().any(|c| matches!(c.name.as_str(), "println" | "eprintln" | "print" | "eprint")) +} + /// Whether the attributes in `m[from..to]` include an applied `should_panic`: `#[should_panic]`, /// `#[should_panic(…)]`, or one inside `#[cfg_attr(test, …)]`. Another `cfg_attr` predicate may /// not hold, so it does not count. @@ -2029,7 +2285,233 @@ fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); let none_match = not_equal_conjunction(body); let (receiver, need) = receiver_need(&cond[..i], sizes); - !none_match && least_items(receiver, test_body, sizes) < need + // A parenthesized range of literals or constants: `(0..3).all(…)`. + let range = if receiver.starts_with('(') { expr_len(receiver, sizes, "") } else { 0 }; + let known = least_items(receiver, test_body, sizes).max(range); + !none_match && known < need && !(need == 1 && (pinned_source(receiver, test_body, sizes) || fixed_table_call(receiver, test_body, sizes))) + }) +} + +/// Whether an earlier equality assertion compares what `receiver` is made from with a non-empty +/// literal: a plain local whose binding reads `receiver` (`let got = r.items()….collect(); +/// assert_eq!(got, [a, b])` before `r.items().iter().all(…)`, with `got` unchanged in between), or +/// the same call `receiver` is bound to (`let gaps = gaps(&word); assert_eq!(gaps(&word), [a, b])`). +fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let init = |name: &str, at: usize| let_init(body, name, at).and_then(|(init, _)| init); + // For a receiver bound to `f(&x)`: the call `f(&x)`, `x`, and where the binding of `x` it reads ends. + let source = if plain_local(r) { + let_init(body, r, body.len()).and_then(|(init, bound)| { + let (text, _) = init?; + let s = single_local_arg(&text)?.to_owned(); + if binds(&body[bound..], s.as_bytes()) { + return None; + } + let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); + Some((norm(text.as_bytes()), s, at)) + }) + } else { + None + }; + macro_calls(body, 0, body.len()).into_iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) || a.args.len() < 2 || !body_level_statement(body, a.at) { + return false; + } + let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1])); + [(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| { + if literal_len(literal, sizes) == 0 { + return false; + } + // The binding keeps the receiver's items (`r.items().iter().map(…).collect()`), nothing + // changes the binding before the assertion, and nothing changes the receiver's source + // from the binding on. + let read = !plain_local(r) + && plain_local(pinned) + && init(pinned, a.at).is_some_and(|(text, at)| { + let bound = statement_end(body, at); + keeping_base(&text, true) == r + && !touched_after(&body[..a.at], pinned, bound, pinned) + && !touched_after(body, root_local(r), bound, r) + }); + // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its + // literal is what the receiver holds. + read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r)) + }) + }) +} + +/// Whether an expression starts a statement of the test body or a plain nested block. +fn body_level_statement(body: &[u8], mut at: usize) -> bool { + while body[..at].trim_ascii_end().ends_with(b"::") { + at = body[..at].trim_ascii_end().len() - 2; + at = body[..at].trim_ascii_end().len(); + while at > 0 && is_ident(body[at - 1]) { + at -= 1; + } + } + let mut statement = true; + let mut i = 0; + while i < at { + match body[i] { + b'{' if statement => {} + b'(' | b'[' | b'{' => { + let Some(close) = matching(body, i).filter(|&close| close < at) else { return false }; + statement = body[i] == b'{'; + i = close + 1; + continue; + } + b';' | b'}' => statement = true, + c if c.is_ascii_whitespace() => {} + _ => statement = false, + } + i += 1; + } + statement +} + +/// The local a receiver path starts from: `r` of `r.items()`. +fn root_local(expr: &str) -> &str { + let end = expr.bytes().take_while(|&c| is_ident(c)).count(); + &expr[..end] +} + +/// Whether code after `from` uses `name` other than through a read-only use of `receiver`, a shared +/// borrow `&name` read in an assertion, or a getter named `len`, `is_empty` or +/// ending in `_count`. Other uses, including assertion arguments, may change what it holds. +/// A read bound to another local or passed to a call outside an assertion may give out an alias. +fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { + if !plain_local(name) { + return true; + } + words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { + let rest = norm(&body[at..statement_end(body, at)]); + let head = body[..at].trim_ascii_end(); + // A shared borrow reads the value in an assertion or in the receiver's own binding; passed to + // a call elsewhere (`reset(&r);`, `let old = reset(&r);`), it may change what an + // interior-mutable value holds. + let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let raw = body[statement..at].trim_ascii_start(); + let macro_name = &raw[..raw.iter().take_while(|&&c| is_ident(c)).count()]; + let assertion = raw.get(macro_name.len()) == Some(&b'!') + && PLAIN_ASSERTS.iter().any(|p| macro_name.strip_prefix(p.as_bytes()).is_some_and(|r| r.is_empty() || r.starts_with(b"_"))); + // The `let` that binds the receiver itself (`let gaps = gaps(&plain);`) reads its source. + let binds_receiver = raw + .strip_prefix(b"let") + .map(<[u8]>::trim_ascii_start) + .is_some_and(|r| r.starts_with(receiver.as_bytes()) && !r.get(receiver.len()).copied().is_some_and(is_ident)); + let shared = head.ends_with(b"&") && !head.ends_with(b"&&") && (assertion || binds_receiver); + let getter = rest + .strip_prefix(name) + .and_then(|r| r.strip_prefix('.')) + .and_then(|r| r.split_once('(')) + .is_some_and(|(method, _)| plain_local(method) && (matches!(method, "len" | "is_empty") || method.ends_with("_count"))); + let read = rest.strip_prefix(receiver).is_some_and(|tail| { + tail.is_empty() + || tail.starts_with([')', ']', '}', ',']) + || [".iter()", ".len()", ".is_empty()", ".first()", ".last()", ".get(", ".contains("].iter().any(|method| tail.starts_with(method)) + }); + let read_only = assertion || binds_receiver || body_level_statement(body, at); + !((read || getter) && read_only || shared) + }) +} + +/// The plain local of a call with one argument, `f(&x)` or `f(x)`. +fn single_local_arg(call: &str) -> Option<&str> { + let open = call.find('(')?; + let head = &call[..open]; + if head.is_empty() || !head.bytes().all(|c| is_ident(c) || c == b':') || matching(call.as_bytes(), open) != Some(call.len() - 1) { + return None; + } + let arg = &call[open + 1..call.len() - 1]; + let arg = arg.strip_prefix('&').unwrap_or(arg); + plain_local(arg).then_some(arg) +} + +/// Whether `receiver` calls a function of the file whose body lists every row of a non-empty +/// constant table of the file (`const TABLE: [T; 3]`, `TABLE.iter()…`) without filtering it: the +/// call gives at least one row whatever state the test builds. A filter, even one on plain values, +/// may drop every row, so it leaves the function out. +fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { + let r = array_receiver(receiver); + let Some(open) = r.find('(') else { return false }; + let name = &r[..open]; + if !plain_local(name) + || matching(r.as_bytes(), open) != Some(r.len() - 1) + || let_binds(test_body, name.as_bytes()) + || binds_parameter(test_body, name.as_bytes()) + { + return false; + } + let file = sizes.file; + let defs: Vec = words(file, name.as_bytes(), 0, file.len()) + .into_iter() + .filter(|&at| { + let head = file[..at].trim_ascii_end(); + head.ends_with(b"fn") && !(head.len() > 2 && is_ident(head[head.len() - 3])) + }) + .collect(); + // Functions of one name in several modules: the call may reach any of them, so every one has + // to list the table. + if defs.is_empty() { + return false; + } + defs.into_iter().all(|at| { + let head = file[..at].trim_ascii_end(); + let Some((_, _, body_open, body_close)) = item_at(file, head.len() - 2) else { return false }; + let params_open = skip_ws(file, at + name.len()); + let Some(params_close) = (file.get(params_open) == Some(&b'(')).then(|| matching(file, params_open)).flatten() else { return false }; + let signature = norm(&file[params_close + 1..body_open]); + let return_type = signature.strip_prefix("->").unwrap_or(""); + let body = norm(&file[body_open + 1..body_close]); + let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); + let table = &body[..table_end]; + let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); + if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + return false; + } + // The body is the chain alone, of steps that keep every row. + let mut at = table_end; + while at < body.len() { + let Some(rest) = body[at..].strip_prefix('.') else { return false }; + let method_len = rest.bytes().take_while(|&c| is_ident(c)).count(); + let method = &rest[..method_len]; + let mut open = at + 1 + method_len; + let mut target = None; + if method == "collect" && body[open..].starts_with("::<") { + let Some(close) = body[open..].find(">(") else { return false }; + target = Some(&body[open + 3..open + close]); + open += close + 1; + } + let Some(close) = (body.as_bytes().get(open) == Some(&b'(')).then(|| matching(body.as_bytes(), open)).flatten() else { return false }; + match method { + "iter" | "into_iter" | "map" | "copied" | "cloned" | "enumerate" | "rev" => {} + "collect" => { + if !known_collection(target.unwrap_or(if close + 1 == body.len() { return_type } else { "" })) { + return false; + } + } + _ => return false, + } + at = close + 1; + } + true + }) +} + +/// Whether a `let` pattern in masked `body` contains `name` as a whole word. +fn let_binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let start = at + 3; + let mut end = start; + while end < body.len() { + if matches!(body[end], b'=' | b';') + || (body[end..].starts_with(b"else") && !is_ident(body[end - 1]) && !body.get(end + 4).copied().is_some_and(is_ident)) + { + break; + } + end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; + } + !words(body, name, start, end).is_empty() }) } @@ -2907,7 +3389,7 @@ fn strip_stream_configuration(body: &mut [u8]) { } fn no_assertion(v: &View) -> Option { - if v.checks || v.delegates || v.should_panic { + if v.checks || v.delegates || v.should_panic || v.diagnostic { return None; } Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) @@ -7307,4 +7789,264 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn a_files_own_helper_decides_over_one_of_the_same_name_in_another_file() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n"; + let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n"; + let caller = "#[test]\nfn v() {\n near(f());\n}\n"; + let files = [ + ("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), + ("crates/x/tests/it/other.rs".to_owned(), other.to_owned()), + ("crates/x/tests/it/caller.rs".to_owned(), caller.to_owned()), + ]; + let ctx = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &ctx), [], "the file's own near asserts"); + let qualified = own.replace(" near(f());", " other::near(f());"); + let files = [files[0].clone(), files[1].clone(), ("crates/x/tests/it/q.rs".to_owned(), qualified.clone())]; + let ctx_q = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/q.rs", &qualified, &ctx_q), + [(3, "no-assertion")], + "a call with a path may reach the other file's near" + ); + assert_eq!( + hits_in("crates/x/tests/it/caller.rs", caller, &ctx), + [(2, "no-assertion")], + "a file that defines none cannot tell which it reaches" + ); + let nested = "mod a {\n fn near(a: f64) { assert!(a < 1.0); }\n}\nuse other::*;\n#[test]\nfn t() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/nested.rs".to_owned(), nested.to_owned()), files[1].clone()]; + let ctx_nested = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/nested.rs", nested, &ctx_nested), + [(6, "no-assertion")], + "a helper inside an inline module does not decide for the file's top-level call" + ); + let inner = + "fn near(a: f64) { assert!(a < 1.0); }\nmod inner {\n use super::other::*;\n #[test]\n fn t() {\n near(f());\n }\n}\n"; + let files = [("crates/x/tests/it/inner.rs".to_owned(), inner.to_owned()), files[1].clone()]; + let ctx_inner = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/inner.rs", inner, &ctx_inner), + [(5, "no-assertion")], + "a test inside an inline module may import the other file's near" + ); + let local = "#[test]\nfn t() {\n fn near(a: f64) { assert!(a < 1.0); }\n assert!(f());\n}\n#[test]\nfn u() {\n near(f());\n}\n"; + let files = [("crates/x/tests/it/local.rs".to_owned(), local.to_owned()), files[1].clone()]; + let ctx_local = Ctx { helpers: asserting_helpers(&files), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/tests/it/local.rs", local, &ctx_local), + [(7, "no-assertion")], + "a helper inside a test does not decide for another test's call" + ); + } + + #[test] + fn a_test_body_passed_to_a_wrapper_counts_as_its_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + let wrapper = src.replace(" keeping(body);", " wrapper();") + "fn wrapper() {\n keeping(body);\n}\n"; + let wrapper_ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), wrapper.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &wrapper, &wrapper_ctx), []); + let shadowed_wrapper = wrapper.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + let shadowed_wrapper_ctx = + Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), shadowed_wrapper.clone())]), ..Ctx::default() }; + assert_eq!( + hits_in("crates/x/src/tests.rs", &shadowed_wrapper, &shadowed_wrapper_ctx), + [(8, "no-assertion")], + "a local binding in a wrapper shadows the asserting helper" + ); + let shadowed = src.replace(" keeping(body);", " let body = || {};\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &shadowed, &ctx), [(8, "no-assertion")], "a local binding shadows the asserting helper"); + let destructured = src.replace(" keeping(body);", " let (body,) = (|| {},);\n keeping(body);"); + assert_eq!( + hits_in("crates/x/src/tests.rs", &destructured, &ctx), + [(8, "no-assertion")], + "a destructured binding shadows the asserting helper" + ); + let closure = src.replace(" keeping(body);", " keeping(|body| keeping(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [(8, "no-assertion")], "a closure parameter shadows the asserting helper"); + let block_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| { drop(body); };\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &block_closure, &ctx), [], "a closure parameter's scope ends with the closure"); + let expr_closure = src.replace(" keeping(body);", " let _cb = |body: fn()| drop(body);\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &expr_closure, &ctx), [], "an expression closure's scope ends at its semicolon"); + let inner = src.replace(" keeping(body);", " let _cb = |body: fn()| { keeping(body); };"); + assert_eq!(hits_in("crates/x/src/tests.rs", &inner, &ctx), [(8, "no-assertion")], "the parameter inside its closure"); + let parameter = src.replace("fn t()", "fn t(body: fn())"); + assert_eq!(hits_in("crates/x/src/tests.rs", ¶meter, &ctx), [(8, "no-assertion")], "a function parameter shadows the asserting helper"); + let later = src.replace(" keeping(body);", " keeping(body);\n {\n let body = || {};\n let _ = body;\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &later, &ctx), [], "a binding in a later block does not reach the call"); + let after = src.replace(" keeping(body);", " keeping(body);\n let body = || {};\n let _ = body;"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "a binding after the call"); + let looped = src.replace(" keeping(body);", " for body in [|| {}] {\n keeping(body);\n }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &looped, &ctx), [(8, "no-assertion")], "a loop pattern shadows the helper in the loop body"); + let after_loop = src.replace(" keeping(body);", " for body in [|| {}] {\n let _ = body;\n }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after_loop, &ctx), [], "the helper after the loop"); + let unused = src.replace(" keeping(body);", " let _unused = (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "a tuple that is never called"); + let dropped = src.replace(" keeping(body);", " (body,);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a tuple in a statement of its own"); + let table = src.replace(" keeping(body);", " let cases = [(\"case\", body)];\n run(&cases);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &table, &ctx), [], "a table of named cases"); + let idle = src.replace("assert_eq!(f(), 1);", "f();"); + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), idle.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &idle, &ctx), [(8, "no-assertion")], "a passed body that checks nothing"); + } + + #[test] + fn a_match_arm_binding_shadows_a_helper_only_in_its_arm() { + let src = "fn body() { assert_eq!(f(), 1); }\n#[test]\nfn t() {\n match Some(|| {}) { Some(body) => keeping(body), None => () }\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "no-assertion")], "a match-arm pattern shadows the helper"); + let after = src.replace("None => () }", "None => () }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match"); + } + + #[test] + fn a_dropped_helper_value_is_not_a_check() { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + let ctx = Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }; + let stored = src.replace(" keeping(body);", " let _unused = Some(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &stored, &ctx), [(8, "no-assertion")], "a constructor only stores the helper"); + let boxed = src.replace(" keeping(body);", " let _ = Box::new(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &boxed, &ctx), [(8, "no-assertion")], "a boxed helper that is dropped"); + let called = src.replace(" keeping(body);", " let _ = keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &ctx), [], "a call runs even when its result is dropped"); + let dropped = src.replace(" keeping(body);", " drop(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a dropped callback"); + for call in ["std::mem::drop", "mem::drop", "forget", "std::mem::forget", "mem::forget"] { + let forgotten = src.replace(" keeping(body);", &format!(" {call}(body);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &forgotten, &ctx), [(8, "no-assertion")], "a discarded callback: {call}"); + } + for value in ["[body]", "Some(body)"] { + let dropped = src.replace(" keeping(body);", &format!(" drop({value});")); + assert_eq!(hits_in("crates/x/src/tests.rs", &dropped, &ctx), [(8, "no-assertion")], "a discarded stored callback: {value}"); + } + let constructed = src.replace(" keeping(body);", " run(Some(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &constructed, &ctx), [], "a stored callback passed to a call"); + let passed = src.replace(" keeping(body);", " run(&[body]);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &passed, &ctx), [], "an array passed to a call"); + let array = src.replace(" keeping(body);", " [body];"); + assert_eq!(hits_in("crates/x/src/tests.rs", &array, &ctx), [(8, "no-assertion")], "a discarded array"); + for value in ["[body]", "[body, other]", "&[body]", "vec![body]"] { + let passed = src.replace(" keeping(body);", &format!(" run({value});")); + assert_eq!(hits_in("crates/x/src/tests.rs", &passed, &ctx), [], "an array argument: {value}"); + let kept = src.replace(" keeping(body);", &format!(" let cases = {value};\n run(cases);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &kept, &ctx), [], "a kept array: {value}"); + let unused = src.replace(" keeping(body);", &format!(" let _ = {value};")); + assert_eq!(hits_in("crates/x/src/tests.rs", &unused, &ctx), [(8, "no-assertion")], "an unused array: {value}"); + } + } + + #[test] + fn a_pin_counts_only_when_its_assertion_runs_and_no_alias_changes_the_source() { + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + for assertion in ["std::assert_eq!(got, vec![1, 2]);", "core::assert_eq!(got, vec![1, 2]);"] { + let qualified = pinned.replace("assert_eq!(got, vec![1, 2]);", assertion); + assert_eq!(hits(&qualified), [], "{assertion}"); + } + for assertion in [ + "let _check = || assert_eq!(got, vec![1]);", + "if ready { assert_eq!(got, vec![1]); }", + "match ready { true => assert_eq!(got, vec![1]), false => () }", + "while ready { assert_eq!(got, vec![1]); }", + "for _ in rounds { assert_eq!(got, vec![1]); }", + ] { + let conditional = pinned.replace("assert_eq!(got, vec![1, 2]);", assertion); + assert_eq!(only("all-unguarded", &conditional), [(5, "all-unguarded")], "{assertion}"); + } + let block = pinned.replace("assert_eq!(got, vec![1, 2]);", "{ { assert_eq!(got, vec![1]); } }"); + assert_eq!(hits(&block), [], "a plain nested block runs its assertion"); + let after_branch = pinned.replace(" assert_eq!(got", " if ready {} else {}\n assert_eq!(got"); + assert_eq!(hits(&after_branch), [], "an earlier branch does not contain the pinning assertion"); + for change in ["let items = r.items(); items.clear();", "let (items,) = (r.items(),); items.clear();", "clear(r.items());"] { + let aliased = pinned.replace(" assert!(r.items()", &format!(" {change}\n assert!(r.items()")); + assert_eq!(only("all-unguarded", &aliased), [(6, "all-unguarded")], "{change}"); + } + let read = pinned.replace(" assert!(r.items()", " r.items();\n assert!(r.items()"); + assert_eq!(hits(&read), [], "a standalone getter read preserves the pinned source"); + } + + #[test] + fn all_over_a_literal_range_or_a_pinned_source_is_guarded() { + let range = "#[test]\nfn t() {\n assert!((0..3).all(|i| a[i] == b[i]));\n}\n"; + assert_eq!(hits(range), []); + assert_eq!(hits(&range.replace("(0..3)", "(0..n)")), [(3, "all-unguarded")], "a range whose end the test does not show"); + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1, 2]);\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(pinned), []); + assert_eq!(hits(&pinned.replace("vec![1, 2]", "vec![]")), [(5, "all-unguarded")], "pinned to an empty list"); + assert_eq!(hits(&pinned.replace("= r.items()", "= other.items()")), [(5, "all-unguarded")], "a list made from another receiver"); + let shadowed = "#[test]\nfn t() {\n let got = f();\n assert_eq!(got, vec![1]);\n let got: Vec = r.items().iter().map(|j| j.n).collect();\n assert!(r.items().iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(shadowed), [(6, "all-unguarded")], "the pinned binding is not the one made from the receiver"); + let cleared = pinned.replace(" assert!(r.items()", " r.clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "the receiver changed after the assertion"); + let cleared_items = pinned.replace(" assert!(r.items()", " r.items().clear();\n assert!(r.items()"); + assert_eq!(hits(&cleared_items), [(6, "all-unguarded")], "the receiver's items changed after the assertion"); + let early = pinned.replace(" assert_eq!(got", " r.clear();\n assert_eq!(got"); + assert_eq!(hits(&early), [(6, "all-unguarded")], "the receiver changed between the binding and the assertion"); + let taken = pinned.replace(" assert!(r.items()", " assert!(r.take_items().is_some());\n assert!(r.items()"); + assert_eq!(hits(&taken), [(6, "all-unguarded")], "an assertion changes the receiver after the pinning assertion"); + let reset = pinned.replace(" assert!(r.items()", " reset(&r);\n assert!(r.items()"); + assert_eq!(hits(&reset), [(6, "all-unguarded")], "a shared borrow passed to a call may change interior-mutable items"); + let bound = pinned.replace(" assert!(r.items()", " let n = count(&r);\n assert!(r.items()"); + assert_eq!(hits(&bound), [(6, "all-unguarded")], "a call whose result is bound may still change interior-mutable items"); + let asserted = pinned.replace(" assert!(r.items()", " assert!(count(&r) > 0);\n assert!(r.items()"); + assert_eq!(hits(&asserted), [], "a shared borrow read in an assertion"); + let counted = pinned.replace(" assert!(r.items()", " assert_eq!(r.unhandled_rejection_count(), 2);\n assert!(r.items()"); + assert_eq!(hits(&counted), [], "a count getter preserves the pinned source"); + let chained = pinned.replace(".map(|j| j.n)", ".map(|j| j.n).chain([1])"); + assert_eq!(hits(&chained), [(5, "all-unguarded")], "a list that is not empty without the receiver's items"); + let reassigned = pinned.replace(" assert_eq!(got", " got = vec![1, 2];\n assert_eq!(got"); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "the snapshot was replaced before the assertion"); + let pushed = pinned.replace(" assert_eq!(got", " got.push(1);\n assert_eq!(got"); + assert_eq!(hits(&pushed), [(6, "all-unguarded")], "the snapshot changed before the assertion"); + let read_first = pinned.replace(" assert_eq!(got", " assert!(got.len() < 9);\n assert_eq!(got"); + assert_eq!(hits(&read_first), [], "a read of the snapshot before the assertion"); + let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(gaps(&plain), [0.0, 0.0]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; + assert_eq!(hits(word), []); + assert_eq!(hits(&word.replace("gaps(&plain), [", "gaps(&other), [")), [(6, "all-unguarded")], "a literal about another value"); + assert_eq!(hits(&word.replace("gaps(&plain), [", "ids(&plain), [")), [(6, "all-unguarded")], "a literal about another call on the value"); + let emptied = word.replace(" let gaps = gaps(&plain);\n", " let mut gaps = gaps(&plain);\n gaps.clear();\n"); + assert_eq!(hits(&emptied), [(7, "all-unguarded")], "a receiver that may change after its binding"); + let rebound = word.replace(" assert_eq!(gaps(&plain), [0.0, 0.0]);\n", "").replace( + " let gaps = gaps(&plain);", + " let gaps = gaps(&plain);\n let plain = other();\n assert_eq!(gaps(&plain), [0.0, 0.0]);", + ); + assert_eq!(hits(&rebound), [(7, "all-unguarded")], "the assertion reads a later binding of the source"); + } + + #[test] + fn all_over_every_row_of_a_constant_table_is_guarded() { + let src = "const TABLE: [u8; 2] = [1, 2];\nfn reasons(app: &App, key: u8) -> Vec> {\n TABLE.iter().map(|r| app.reason(r, key)).collect()\n}\n#[test]\nfn t() {\n let app = App::new();\n assert!(reasons(&app, 2).iter().all(|r| r.is_none()));\n}\n"; + assert_eq!(hits(src), []); + let shadowed = src.replace(" assert!", " let reasons = |_: &App, _: u8| Vec::>::new();\n assert!"); + assert_eq!(hits(&shadowed), [(9, "all-unguarded")], "a local binding shadows the file's function"); + let twice = format!("{src}mod other {{\n fn reasons(_: &App, _: u8) -> Vec> {{\n Vec::new()\n }}\n}}\n"); + assert_eq!(hits(&twice), [(8, "all-unguarded")], "another module defines a function of the same name"); + let keyed = src.replace(".map(|r|", ".filter(|r| **r == key).map(|r|"); + assert_eq!(hits(&keyed), [(8, "all-unguarded")], "a filter on a plain value may drop every row"); + let state = src.replace(".map(|r|", ".filter(|r| app.has(r)).map(|r|"); + assert_eq!(hits(&state), [(8, "all-unguarded")], "a filter on the state the test builds"); + let empty = src.replace("[u8; 2] = [1, 2]", "[u8; 0] = []"); + assert_eq!(hits(&empty), [(8, "all-unguarded")], "an empty table"); + let elsewhere = src.replace("const TABLE: [u8; 2] = [1, 2];\n", ""); + assert_eq!(hits(&elsewhere), [(7, "all-unguarded")], "a table whose length the file does not show"); + let map_while = src.replace(".map(|r| app.reason(r, key))", ".map_while(|r| app.reason(r, key))"); + assert_eq!(hits(&map_while), [(8, "all-unguarded")], "another step that drops rows"); + let optional = src + .replace("-> Vec>", "-> Option>>") + .replace(".map(|r| app.reason(r, key))", ".map(|r| Some(app.reason(r, key)))") + .replace(".all(|r| r.is_none())", ".all(|r| r.len() == 1)"); + assert_eq!(hits(&optional), [(8, "all-unguarded")], "collecting into an option can discard every row"); + } + + #[test] + fn an_ignored_diagnostic_that_prints_needs_no_assertion() { + let diagnostic = "#[test]\n#[ignore = \"manual timing\"]\nfn t() {\n let n = f();\n eprintln!(\"{n:?}\");\n}\n"; + assert_eq!(hits(diagnostic), []); + assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing"); + assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints"); + } } From 91f76bc40aae9e3899e3b923f1746fc45ca64c07 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:09:46 -0800 Subject: [PATCH 36/60] JavaScript: Symbol reads through a proxy call its get trap, and ownKeys traps may return Symbol keys A read of a Symbol key on a proxy, or on an object with a proxy on its prototype chain, now calls the proxy's get trap with the Symbol and the receiver (ECMA-262 9.5.8) and checks the result against the target's non-configurable Symbol properties. An ownKeys trap may now return Symbol keys (9.5.11). A Symbol given twice, a non-configurable Symbol key of the target left out, and for a non-extensible target any Symbol key left out or added throw a TypeError. The target's descriptors are read in its key order with one isExtensible call. Reflect.ownKeys, Object.getOwnPropertySymbols and the Object functions that list keys take a proxy's keys from one trap call and keep the order the trap gave, Symbols included. --- crates/js/src/builtins/object.rs | 17 +++- crates/js/src/builtins/reflect.rs | 39 +++++---- crates/js/src/builtins/symbol.rs | 13 ++- crates/js/src/proxy.rs | 140 +++++++++++++++++++++++------- crates/js/src/proxy_tests.rs | 104 +++++++++++++++++++++- crates/js/src/symbol.rs | 78 +++++++++++++++-- docs/mcp.md | 15 ++-- docs/target-app-parity.md | 2 +- 8 files changed, 336 insertions(+), 72 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 8237c11f34..f1e0dd3fae 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -146,12 +146,23 @@ pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator JsResult<(Vec, crate::interp::HeldBytes)> { + if interp.is_proxy(o) { + let list = interp.own_keys_and_symbols(o)?; + let count = list.names.len() + list.syms.len(); + let roots = list.sym_values(); + return interp.rooted(&roots, |interp| { + let (keys, mut held) = list.into_prop_keys(); + held.add(interp, count.saturating_mul(std::mem::size_of::()))?; + Ok((keys.collect(), held)) + }); + } let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + let syms = interp.own_symbols(o)?; let mut keys: Vec = names.into_iter().map(PropKey::Str).collect(); - keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); + keys.extend(syms.into_iter().map(PropKey::Sym)); Ok((keys, held)) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index a49833739c..c6f0381b7d 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -4,13 +4,13 @@ use std::rc::Rc; -use super::object::{from_prop, names_array, to_desc}; -use super::{arg, method, native}; +use super::object::{from_prop, to_desc}; +use super::{arg, create_at, method, native, new_array}; use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; use crate::symbol::{PropKey, Sym}; -use crate::value::Value; +use crate::value::{Str, Value}; /// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them /// after earlier runs, a global of the same name that a script defined stays as it is. Each @@ -229,22 +229,27 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.is_extensible(o).map(Value::Bool) } -/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not, -/// then the own Symbol keys in the order they were added. A proxy's Symbol keys are its -/// target's. +/// `Reflect.ownKeys(target)` (section 26.1.10): an ordinary object's own property names, +/// enumerable or not, then its Symbol keys in insertion order. A proxy's keys come from one call of +/// its `ownKeys` trap, in the order it gave them. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; - let names = interp.ecma_own_keys(o)?; - let count = names.len(); - let syms = interp.own_symbols(o)?; - let a = names_array(interp, names)?; - let Value::Object(id) = a else { return Ok(a) }; - interp.rooted(&[Value::Object(id)], |interp| { - for (i, s) in syms.into_iter().enumerate() { - interp.use_fuel()?; - super::create_at(interp, id, (count + i) as f64, Value::Symbol(s))?; - } - Ok(Value::Object(id)) + let list = interp.own_keys_and_symbols(o)?; + let roots = list.sym_values(); + interp.rooted(&roots, |interp| { + let (keys, _held) = list.into_prop_keys(); + let id = new_array(interp, 0)?; + interp.rooted(&[Value::Object(id)], |interp| { + for (i, k) in keys.enumerate() { + interp.use_fuel()?; + let v = match k { + PropKey::Str(k) => Value::String(Str::from_rc(k)), + PropKey::Sym(s) => Value::Symbol(s), + }; + create_at(interp, id, i as f64, v)?; + } + Ok(Value::Object(id)) + }) }) } diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index beec94c6a5..4503ffb5ca 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -169,9 +169,16 @@ fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let syms = interp.own_symbols(o)?; - let a = new_array(interp, 0)?; - interp.rooted(&[Value::Object(a)], |interp| { + let (syms, _held) = if interp.is_proxy(o) { + let list = interp.own_keys_and_symbols(o)?; + (list.syms, Some(list.names.held)) + } else { + (interp.own_symbols(o)?, None) + }; + let mut roots: Vec = syms.iter().cloned().map(Value::Symbol).collect(); + let a = interp.rooted(&roots, |interp| new_array(interp, 0))?; + roots.push(Value::Object(a)); + interp.rooted(&roots, |interp| { for (i, s) in syms.into_iter().enumerate() { interp.use_fuel()?; create_at(interp, a, i as f64, Value::Symbol(s))?; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index fa88173b16..1c9767c6c2 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -20,11 +20,15 @@ use crate::heap::{ CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, }; use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, HeldKeys, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; +use crate::symbol::{OwnKeyList, PropKey, Sym}; use crate::value::{Str, Value, index_key}; /// The most names an `ownKeys` trap may give. const MAX_OWN_KEYS: f64 = (1u64 << 24) as f64; +/// An `ownKeys` trap's names, its Symbol keys, and each Symbol's place in the whole list. +type TrapKeys = (Vec, Vec, Vec); + impl Interp { pub(crate) fn is_proxy(&self, id: ObjId) -> bool { matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_))) @@ -387,6 +391,24 @@ impl Interp { }) } + /// [[Get]] of a proxy (section 9.5.8) for the Symbol key `k`: the `get` trap with the Symbol + /// and `receiver`, or a read from the target when the handler has no `get` trap. + pub(crate) fn proxy_get_sym(&mut self, p: ObjId, k: &Sym, receiver: &Value) -> JsResult { + self.proxy_op(p, "read a property of", &[receiver.clone(), Value::Symbol(k.clone())], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_sym_from(target, k, receiver) }; + let v = i.call_trap(&trap, handler, &[Value::Object(target), Value::Symbol(k.clone()), receiver.clone()])?; + match i.get_own_sym(target, k)? { + Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { + Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) + } + Some(Prop::Accessor { get: None, flags, .. }) if flags & CONFIGURABLE == 0 && !matches!(v, Value::Undefined) => { + Err(i.invariant("get", "gave a value for a non-configurable property of its target that has no getter")) + } + _ => Ok(v), + } + }) + } + /// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property. pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &Key) -> JsResult { self.proxy_op(p, "delete a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { @@ -406,24 +428,44 @@ impl Interp { }) } - /// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object - /// of distinct strings, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable - /// name of the target, and of a non-extensible target exactly its names. Each name takes a - /// unit of fuel and counts against the heap limit until the caller drops the list. + /// The string names of a proxy's [[OwnPropertyKeys]] (section 9.5.11); see + /// [`Interp::proxy_own_keys_and_symbols`]. pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { + self.proxy_own_keys_and_symbols(p).map(|list| list.names) + } + + /// [[OwnPropertyKeys]] of a proxy (section 9.5.11): its string names and its Symbol keys, each + /// in the order the trap gave them. The trap must give an array-like object of distinct + /// strings and Symbols, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable + /// key of the target, and of a non-extensible target exactly its keys. Each key takes a unit + /// of fuel and counts against the heap limit until the caller drops the list. + pub(crate) fn proxy_own_keys_and_symbols(&mut self, p: ObjId) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.ecma_own_keys(target) }; + let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.own_keys_and_symbols(target) }; let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; - let mut held = HeldBytes::new(i); - let keys = i.trap_key_list(&result, &mut held)?; - i.check_own_keys(target, &keys)?; - Ok(HeldKeys { keys, held }) + let mark = i.temp_roots.len(); + let r = i.checked_trap_keys(target, &result); + i.temp_roots.truncate(mark); + r }) } + /// Steps 7 to 23 of section 9.5.11 for the `ownKeys` trap's `result`. Each Symbol it gives is + /// kept in the temporary roots, which the caller truncates. + fn checked_trap_keys(&mut self, target: ObjId, result: &Value) -> JsResult { + let mut held = HeldBytes::new(self); + let (keys, syms, slots) = self.trap_key_list(result, &mut held)?; + let extensible = self.is_extensible(target)?; + let target_list = self.own_keys_and_symbols(target)?; + self.temp_roots.extend(target_list.sym_values()); + self.check_own_keys(target, extensible, target_list, &keys, &syms)?; + Ok(OwnKeyList { names: HeldKeys { keys, held }, syms, slots }) + } + /// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result, refusing a value - /// that is not a string and a name given twice. - fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult> { + /// that is neither a string nor a Symbol and a key given twice. The string names and the + /// Symbol keys come back as separate lists, with each Symbol's place in the whole list. + fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult { let Value::Object(list) = result else { return Err(self.invariant("ownKeys", "returned a value that is not an object")) }; let length = self.get_from(*list, &key("length"), result)?; let n = self.to_number(&length)?; @@ -434,11 +476,28 @@ impl Interp { } let mut keys = Vec::new(); let mut seen: HashSet = HashSet::new(); + let mut syms = Vec::new(); + let mut slots = Vec::new(); + let mut seen_syms: HashSet = HashSet::new(); let mut duplicate = None; + let mut duplicate_sym = false; for index in 0..n as u32 { self.use_fuel()?; let v = self.get_from(*list, &index_key(index), result)?; - let Value::String(s) = v else { return Err(self.invariant("ownKeys", "returned a name that is not a string")) }; + let s = match v { + Value::String(s) => s, + Value::Symbol(sym) => { + self.temp_roots.push(Value::Symbol(sym.clone())); + held.add(self, 2 * KEY_ENTRY_BYTES)?; + if !seen_syms.insert(sym.addr()) { + duplicate_sym = true; + } + syms.push(sym); + slots.push(index as usize); + continue; + } + _ => return Err(self.invariant("ownKeys", "returned a key that is not a string or a Symbol")), + }; held.add(self, string_bytes(s.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; let k = s.flat(); if !seen.insert(k.clone()) && duplicate.is_none() { @@ -450,45 +509,60 @@ impl Interp { let name = String::from_utf16_lossy(&k); return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice"))); } - Ok(keys) + if duplicate_sym { + return Err(self.invariant("ownKeys", "returned a Symbol key twice")); + } + Ok((keys, syms, slots)) } - /// Steps 16 to 23 of section 9.5.11: the names `keys` the trap gave against the target's. - fn check_own_keys(&mut self, target: ObjId, keys: &[Key]) -> JsResult<()> { - let extensible = self.is_extensible(target)?; - let target_keys = self.own_keys(target)?; + /// Steps 16 to 23 of section 9.5.11: reads target descriptors in key order, then checks + /// the trap's string and Symbol keys against the non-configurable and configurable keys. + fn check_own_keys(&mut self, target: ObjId, extensible: bool, target_keys: OwnKeyList, keys: &[Key], syms: &[Sym]) -> JsResult<()> { + let count = target_keys.names.len() + target_keys.syms.len(); + let (target_keys, mut held) = target_keys.into_prop_keys(); + held.add(self, count.saturating_mul(std::mem::size_of::()))?; let mut fixed = Vec::new(); let mut configurable = Vec::new(); - for k in target_keys.iter() { + for k in target_keys { self.use_fuel()?; - if self.own_property(target, k)?.is_some_and(|p| !p.configurable()) { - fixed.push(k.clone()); + if self.own_pk(target, &k)?.is_some_and(|p| !p.configurable()) { + fixed.push(k); } else { - configurable.push(k.clone()); + configurable.push(k); } } if extensible && fixed.is_empty() { return Ok(()); } let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect(); - for k in &fixed { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target"))); + let mut unchecked_syms: HashSet = syms.iter().map(Sym::addr).collect(); + for (list, non_configurable) in [(&fixed, true), (&configurable, false)] { + if !non_configurable && extensible { + return Ok(()); } - } - if extensible { - return Ok(()); - } - for k in &configurable { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target"))); + for k in list { + match k { + PropKey::Str(k) if !unchecked.remove(&**k) => { + let name = String::from_utf16_lossy(k); + let what = if non_configurable { "non-configurable property" } else { "property" }; + let target = if non_configurable { "target" } else { "non-extensible target" }; + return Err(self.invariant("ownKeys", &format!("left out the {what} '{name}' of its {target}"))); + } + PropKey::Sym(k) if !unchecked_syms.remove(&k.addr()) => { + let name = self.sym_name(k)?; + let what = if non_configurable { "non-configurable property" } else { "property" }; + return Err(self.invariant("ownKeys", &format!("left out the {what} {name} of its target"))); + } + _ => {} + } } } if !unchecked.is_empty() { return Err(self.invariant("ownKeys", "gave a name its non-extensible target does not have")); } + if !unchecked_syms.is_empty() { + return Err(self.invariant("ownKeys", "gave a Symbol key its non-extensible target does not have")); + } Ok(()) } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index cac32535b4..22d56a6557 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -999,8 +999,7 @@ fn proxy_integrity_operations_include_the_targets_symbol_properties() { truth( "var s = Symbol('x'), p = new Proxy({}, { ownKeys: function () { return []; } }); p[s] = 1; - Object.freeze(p); - Object.isFrozen(p) && !Object.getOwnPropertyDescriptor(p, s).writable", + type_error(function () { Object.freeze(p); })", ); } @@ -1767,6 +1766,107 @@ fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { ); } +#[test] +fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() { + truth( + "var s = Symbol('s'), hidden = Symbol('h'), t = {}; t[hidden] = 1; + var calls = 0; + var open = new Proxy(t, { ownKeys: function () { calls++; return ['a', s]; } }); + var listed = Reflect.ownKeys(open); + var syms = Object.getOwnPropertySymbols(open); + listed.length === 2 && listed[0] === 'a' && listed[1] === s && syms.length === 1 && syms[0] === s && calls === 2", + ); + truth( + "var s = Symbol('s'); + var mixed = Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, 'a', 'b']; } })); + mixed.length === 3 && mixed[0] === s && mixed[1] === 'a' && mixed[2] === 'b'", + ); + type_errors(&[ + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return []; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, s]; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy(Object.preventExtensions({}), { ownKeys: function () { return [s]; } }))", + "Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [1]; } }))", + ]); + truth( + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return [s]; } })).length === 1", + ); +} + +#[test] +fn own_keys_checks_target_descriptors_in_combined_key_order() { + truth( + "var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 }; + t[s] = 3; t[u] = 4; + var reads = '', extensible = 0; + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a', u, 'b']; }, + isExtensible: function () { extensible++; return true; }, + getOwnPropertyDescriptor: function (t, k) { + reads += k; + Object.defineProperty(t, k === 'a' ? s : u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + var keys = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a']; } })); + keys.length === 2 && keys[0] === 'b' && keys[1] === 'a' && reads === 'ab' && extensible === 1", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + +#[test] +fn own_keys_consumers_keep_interleaved_trap_keys() { + truth( + "var s = Symbol('s'), u = Symbol('u'); + var p = new Proxy({}, { ownKeys: function () { return ['a', s, 'b', u, 'c']; } }); + var keys = Reflect.ownKeys(p); + keys.length === 5 && keys[0] === 'a' && keys[1] === s && keys[2] === 'b' && keys[3] === u && keys[4] === 'c'", + ); + truth( + "var s = Symbol('s'), t = { a: { value: 1 }, b: { value: 3 } }; + t[s] = { value: 2 }; + var order = []; + var props = new Proxy(t, { + ownKeys: function () { return ['a', s, 'b']; }, + get: function (t, k) { order.push(k); return t[k]; } + }); + var o = Object.defineProperties({}, props); + order.length === 3 && order[0] === 'a' && order[1] === s && order[2] === 'b' && o.a === 1 && o[s] === 2 && o.b === 3", + ); +} + +#[test] +fn symbol_reads_through_a_proxy_call_its_get_trap() { + truth( + "var s = Symbol('s'); var seen; + var p = new Proxy({}, { get: function (t, k, r) { seen = [k, r]; return 5; } }); + var child = Object.create(p); + p[s] === 5 && seen[0] === s && seen[1] === p && child[s] === 5 && seen[1] === child", + ); + truth( + "var s = Symbol('s'); var t = {}; t[s] = 3; + new Proxy(t, {})[s] === 3 && Object.create(new Proxy(t, {}))[s] === 3", + ); + type_errors(&["var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + new Proxy(t, { get: function () { return 2; } })[s]"]); + truth( + "var p = new Proxy({}, { get: function (t, k) { if (k === Symbol.toPrimitive) return function () { return 9; }; } }); + +p === 9", + ); +} + #[test] fn json_transparent_host_proxies_skip_indexers_but_call_get_traps() { let calls = Rc::new(RefCell::new(0)); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index d4e451e766..91a7119038 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -148,6 +148,35 @@ pub(crate) enum PropKey { Sym(Sym), } +/// An object's own property keys from one [[OwnPropertyKeys]] call (section 9.1.11), its names +/// and its Symbol keys apart. `slots[i]` is the place of `syms[i]` in the whole list, so a +/// proxy's keys keep the order its `ownKeys` trap gave them in. +pub(crate) struct OwnKeyList { + pub(crate) names: crate::interp::HeldKeys, + pub(crate) syms: Vec, + pub(crate) slots: Vec, +} + +impl OwnKeyList { + /// The Symbol keys as values, to keep them reachable while the caller allocates. + pub(crate) fn sym_values(&self) -> Vec { + self.syms.iter().cloned().map(Value::Symbol).collect() + } + + /// Iterates over the whole list in order, with its heap charge held separately. + pub(crate) fn into_prop_keys(self) -> (impl Iterator, crate::interp::HeldBytes) { + let crate::interp::HeldKeys { keys: names, held } = self.names; + let total = names.len() + self.syms.len(); + let mut names = names.into_iter(); + let mut syms = self.syms.into_iter().zip(self.slots).peekable(); + let keys = (0..total).filter_map(move |at| match syms.next_if(|(_, slot)| *slot == at) { + Some((s, _)) => Some(PropKey::Sym(s)), + None => names.next().map(PropKey::Str), + }); + (keys, held) + } +} + /// The well-known Symbols a realm has (section 6.1.5.1): `Symbol.iterator` and the others the /// language reads, with `Symbol.asyncIterator`, which nothing reads yet. pub(crate) struct WellKnown { @@ -349,13 +378,32 @@ impl Interp { Ok(None) } - /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. + /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. A proxy on the + /// prototype chain handles the read with its `get` trap (section 9.5.8). Each step to a + /// prototype takes a unit of fuel. pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult { - match self.find_sym(start, k)? { - None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), - Some(Prop::Data { value, .. }) => Ok(value), - Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + let mut cur = Some(start); + let mut steps = 0usize; + while let Some(o) = cur { + if self.is_proxy(o) { + return self.proxy_get_sym(o, k, receiver); + } + match self.get_own_sym(o, k)? { + None => {} + Some(Prop::Accessor { get: None, .. }) => return Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => return Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => return self.call(&Value::Object(g), receiver, &[]), + } + cur = self.object(o)?.proto; + if cur.is_some() { + self.use_fuel()?; + } + steps += 1; + if steps > 1_000_000 { + return Err(crate::interp::Abrupt::Internal("prototype chain too long".into())); + } } + Ok(Value::Undefined) } /// `base[k]` for any value. @@ -498,10 +546,24 @@ impl Interp { } } - /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and - /// the heap for the list is checked first. + /// An object's own property names in the order of section 9.1.11 and its own Symbol keys, + /// listed with one [[OwnPropertyKeys]] call; for a proxy, one call of its `ownKeys` trap. + pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + if self.is_proxy(id) { + return self.proxy_own_keys_and_symbols(id); + } + let names = self.ecma_own_keys(id)?; + let syms = self.own_symbols(id)?; + let slots = (names.len()..names.len() + syms.len()).collect(); + Ok(OwnKeyList { names, syms, slots }) + } + + /// An object's own Symbol keys in the order they were added; a proxy's come from its + /// `ownKeys` trap. Each takes a unit of fuel, and the heap for the list is checked first. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { - let id = self.sym_home(id)?; + if self.is_proxy(id) { + return self.proxy_own_keys_and_symbols(id).map(|list| list.syms); + } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { diff --git a/docs/mcp.md b/docs/mcp.md index 9b02f91101..e79cc1b818 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2908,11 +2908,16 @@ In E4X mode, a bare call resolves each scope once. An object binding still check when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without -calling proxy traps, so a proxy receiver throws `TypeError`. A Symbol property key on a proxy goes to its innermost -target without calling a trap: reads, writes, definitions, deletion and descriptor reads act on that target's -Symbol properties. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. -The `Reflect` functions take Symbol keys as well as strings. `Reflect.ownKeys` returns the string keys, then the -Symbol keys in the order they were added; a proxy's Symbol keys are its innermost target's. Ordinary targets list +calling proxy traps, so a proxy receiver throws `TypeError`. A read of a Symbol property key through a proxy, on +the proxy itself or on an object that has it as a prototype, calls the proxy's `get` trap with the Symbol and the +receiver, and reads from the target when the handler has no `get` trap. Other operations with a Symbol key on a proxy +go to its innermost target without calling a trap: writes, definitions, deletion and descriptor reads act on that +target's Symbol properties. An `ownKeys` trap may return Symbol keys as well as strings; a Symbol key given twice, a +non-configurable Symbol key of the target left out, and for a non-extensible target any of its Symbol keys left out +or one it lacks throw `TypeError`. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. +The `Reflect` functions take Symbol keys as well as strings. For ordinary objects, `Reflect.ownKeys` returns the string keys, +then the Symbol keys in the order they were added. A proxy's keys come from one call of its `ownKeys` trap and keep +the trap's order, including Symbol keys. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines the order of its string keys. A `for-in` prototype walk keeps the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index da3ad29e7d..0f98b4fdb1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1195,7 +1195,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key on a proxy goes to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key read through a proxy calls its `get` trap, an `ownKeys` trap may return Symbol keys, and other Symbol-key operations on a proxy go to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string or a Symbol), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. From df12f897d4be9797c91c96da84594646ea7717a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:11:04 -0800 Subject: [PATCH 37/60] xtask: test-lint reads a closure body past turbofish commas An expression closure such as `|body: fn()| forward::(body)` ended at the comma inside the turbofish, so a parameter named like an asserting helper stopped shadowing it at that comma. The closure body now skips a turbofish whole. A count or emptiness getter on a pinned snapshot (`let _ = got.len();`) keeps the pin; only a read of the receiver itself that is bound or passed to a call may hand out an alias. --- xtask/src/test_lint.rs | 46 +++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f6b8a6e2b1..ec88e985fd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2410,8 +2410,10 @@ fn touched_after(body: &[u8], name: &str, from: usize, receiver: &str) -> bool { || tail.starts_with([')', ']', '}', ',']) || [".iter()", ".len()", ".is_empty()", ".first()", ".last()", ".get(", ".contains("].iter().any(|method| tail.starts_with(method)) }); + // A read of the receiver bound to another local or passed to a call may hand out an alias; + // a count or emptiness getter returns a plain value. let read_only = assertion || binds_receiver || body_level_statement(body, at); - !((read || getter) && read_only || shared) + !(getter || (read && read_only) || shared) }) } @@ -4126,20 +4128,31 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { let end = match body.get(from) { Some(b'{') => matching(body, from), _ => { - let mut depth = 0usize; - (from..body.len()).find(|&k| match body[k] { - b'(' | b'[' | b'{' => { - depth += 1; - false + // The expression body ends at the first `,`, `;` or closing bracket outside its own + // brackets; a turbofish (`forward::(body)`) is skipped whole. + let (mut depth, mut k, mut end) = (0usize, from, None); + while k < body.len() { + let next = skip_turbofish(body, k); + if next != k { + k = next; + continue; } - b')' | b']' | b'}' if depth == 0 => true, - b')' | b']' | b'}' => { - depth -= 1; - false + match body[k] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' if depth == 0 => { + end = Some(k); + break; + } + b')' | b']' | b'}' => depth -= 1, + b',' | b';' if depth == 0 => { + end = Some(k); + break; + } + _ => {} } - b',' | b';' => depth == 0, - _ => false, - }) + k += 1; + } + end } }; if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) { @@ -7902,6 +7915,11 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "no-assertion")], "a match-arm pattern shadows the helper"); let after = src.replace("None => () }", "None => () }\n keeping(body);"); assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match"); + let turbofish = src.replace( + "match Some(|| {}) { Some(body) => keeping(body), None => () }", + "let cb = |body: fn()| forward::(body);\n cb(|| {});", + ); + assert_eq!(hits_in("crates/x/src/tests.rs", &turbofish, &ctx), [(3, "no-assertion")], "a turbofish comma does not end the closure"); } #[test] @@ -8002,7 +8020,7 @@ mod tests { assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "the snapshot was replaced before the assertion"); let pushed = pinned.replace(" assert_eq!(got", " got.push(1);\n assert_eq!(got"); assert_eq!(hits(&pushed), [(6, "all-unguarded")], "the snapshot changed before the assertion"); - let read_first = pinned.replace(" assert_eq!(got", " assert!(got.len() < 9);\n assert_eq!(got"); + let read_first = pinned.replace(" assert_eq!(got", " let _ = got.len();\n assert_eq!(got"); assert_eq!(hits(&read_first), [], "a read of the snapshot before the assertion"); let word = "#[test]\nfn t() {\n let plain = word();\n assert_eq!(gaps(&plain), [0.0, 0.0]);\n let gaps = gaps(&plain);\n assert!(gaps.iter().all(|g| g.abs() < 1e-6));\n}\n"; assert_eq!(hits(word), []); From b8e72d686c0a1543361d18256953510f2e3d57f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:55:10 -0800 Subject: [PATCH 38/60] xtask: test-lint checks a base file's blob size before reading it The changed-lines mode read each base file with `git show` and only then compared the length of the trimmed, lossily decoded text with the 16 MiB limit, so a large blob was loaded in full before it was skipped, and trailing whitespace and invalid UTF-8 changed the length it was judged by. The base reads now take each blob's size from one `git ls-tree -l` listing of `crates`, `apps` and `xtask` (or `git cat-file -s` for a path the listing does not hold) and run `git show` only for blobs within the limit. --- xtask/src/test_lint.rs | 111 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 109 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c95215cd4c..d44b044412 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -88,8 +88,9 @@ use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::io::Write; use std::path::Path; -use std::process::Command; +use std::process::{Command, Stdio}; /// Test files that read Rust source on purpose: they audit the source tree. pub const SOURCE_AUDITS: &[&str] = &[ @@ -343,7 +344,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // Files that load a module through `#[path]`, found with `git grep` (untracked files included) // instead of reading the tree, and the target roots beside a shared `tests//mod.rs`. let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files); - let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); + let base_sizes = base_blob_sizes(root, &base); + let read_base = cached_read(|p| read_base_blob(root, &base, p, MAX_FILE, base_sizes.as_ref())); // The base's target roots come from the base tree: a root the change deleted still loaded the // shared module beside it. let base_overrides = @@ -626,6 +628,74 @@ fn git(root: &Path, args: &[&str]) -> Result { Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) } +/// The file `path` as it is at `rev`, or `None` when it is missing there or its blob is larger +/// than `limit` bytes. `size` and `show` take the `rev:path` object name and give the blob's +/// size and text; a blob over the limit is never passed to `show`. +fn read_blob(rev: &str, path: &str, limit: u64, size: impl Fn(&str) -> Option, show: impl Fn(&str) -> Option) -> Option { + let spec = format!("{rev}:{path}"); + if size(&spec)? > limit { + return None; + } + show(&spec) +} + +/// [`read_blob`] through Git in `root`. +fn read_git_blob(root: &Path, rev: &str, path: &str, limit: u64) -> Option { + let size = |spec: &str| git(root, &["cat-file", "-s", spec]).ok()?.parse().ok(); + read_blob(rev, path, limit, size, |spec| git(root, &["show", spec]).ok()) +} + +fn read_base_blob(root: &Path, rev: &str, path: &str, limit: u64, sizes: Option<&HashMap>) -> Option { + match sizes.and_then(|sizes| sizes.get(path)).copied() { + Some(size) => read_blob(rev, path, limit, |_| Some(size), |spec| git(root, &["show", spec]).ok()), + None => read_git_blob(root, rev, path, limit), + } +} + +/// The size of each `.rs` blob in the tree at `rev`, or `None` when either Git command fails. +fn base_blob_sizes(root: &Path, rev: &str) -> Option> { + let list = git(root, &["ls-tree", "-r", "-z", "--name-only", rev, "--", "crates", "apps", "xtask"]).ok()?; + // Each batch request is one line; paths with newlines use read_git_blob instead. + let paths: Vec<&str> = list.split('\0').filter(|path| is_scanned(path) && !path.contains('\n')).collect(); + let input: String = paths.iter().map(|path| format!("{rev}:{path}\n")).collect(); + let mut child = Command::new("git") + .current_dir(root) + .arg("cat-file") + .arg("--batch-check=%(objectsize)") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .ok()?; + let mut stdin = child.stdin.take()?; + let output = std::thread::scope(|scope| { + let writer = match std::thread::Builder::new().spawn_scoped(scope, move || stdin.write_all(input.as_bytes())) { + Ok(writer) => writer, + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + }; + let output = child.wait_with_output().ok(); + writer.join().ok()?.ok()?; + output + })?; + if !output.status.success() { + return None; + } + let output = String::from_utf8_lossy(&output.stdout); + let mut lines = output.lines(); + let mut sizes = HashMap::new(); + for path in paths { + let size = lines.next()?; + if !size.ends_with("missing") { + sizes.insert(path.to_owned(), size.parse().ok()?); + } + } + Some(sizes) +} + fn resolve_base(root: &Path, explicit: Option) -> Result { if let Some(rev) = explicit.or_else(|| std::env::var("TEST_LINT_BASE").ok().filter(|v| !v.is_empty())) { return git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")]) @@ -7390,6 +7460,43 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn base_blobs_over_the_limit_are_not_read() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-blob-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + // 1 byte of text and 40 of trailing whitespace: the blob is 41 bytes. + std::fs::write(root.join("crates/x/src/padded.rs"), format!("x{}", " \n".repeat(20))).unwrap(); + std::fs::write(root.join("crates/x/src/small.rs"), "fn f() {}\n").unwrap(); + std::fs::write(root.join("crates/x/src/other.txt"), "other\n").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/padded.rs", 8), None, "the blob's size counts, not its trimmed text"); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/padded.rs", 41).as_deref(), Some("x")); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/small.rs", 10).as_deref(), Some("fn f() {}")); + assert_eq!(read_git_blob(&root, &base, "crates/x/src/missing.rs", 10), None); + let sizes = base_blob_sizes(&root, &base).unwrap(); + assert_eq!(sizes.get("crates/x/src/padded.rs"), Some(&41)); + assert!(!sizes.contains_key("crates/x/src/other.txt")); + assert_eq!(read_base_blob(&root, &base, "crates/x/src/other.txt", 6, Some(&sizes)).as_deref(), Some("other")); + assert_eq!(read_base_blob(&root, &base, "crates/x/src/other.txt", 5, Some(&sizes)), None); + assert_eq!(read_base_blob(&root, &base, "crates/x/src/padded.rs", 8, Some(&sizes)), None); + assert!(base_blob_sizes(&root, "missing-revision").is_none()); + // A blob over the limit is not read at all. + let shown = RefCell::new(vec![]); + let show = |spec: &str| { + shown.borrow_mut().push(spec.to_owned()); + Some(String::new()) + }; + assert_eq!(read_blob("r", "big.rs", 8, |_| Some(9), show), None); + assert_eq!(read_blob("r", "fits.rs", 8, |_| Some(8), show).as_deref(), Some("")); + assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 8, |_| sizes.get("crates/x/src/padded.rs").copied(), show), None); + assert_eq!(read_blob(&base, "crates/x/src/padded.rs", 41, |_| sizes.get("crates/x/src/padded.rs").copied(), show).as_deref(), Some("")); + assert_eq!(*shown.borrow(), ["r:fits.rs".to_owned(), format!("{base}:crates/x/src/padded.rs")]); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn base_root_routes_come_from_the_base_tree() { let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); From fde52f43a262c201ce2c00ea199ac5581ebcc08d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 02:31:56 -0800 Subject: [PATCH 39/60] xtask: test-lint resolves shadowed helpers, literal selectors and aliases - A renamed import (`use super::other::near as comparison;`) no longer counts as a call with a path; an import that keeps the name still does. - A bare call to a helper's name checks for a local binding in scope (`let near = || {}; near();`), skipping type annotations, field labels and path segments in patterns. - Helpers passed in assertion failure messages no longer count as checks. - A match-arm binding covers the arm's guard, and the arm's pattern stops at the block of the arm before it. - `#[ ignore = "..."]` with whitespace is read as an ignore attribute, both for diagnostic tests and for ignore-without-reason. - Literal ranges read `0x`, `0o` and `0b` bounds. - A pin compares literal arguments (`r.items("active")` against `r.items("archived")`), and does not count when a clone or borrow of the source made before the snapshot is still alive. - A function parameter named like a constant table is not the table. --- xtask/src/test_lint.rs | 434 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 397 insertions(+), 37 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index ec88e985fd..aa75ca051f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1180,6 +1180,11 @@ const COMMON: &[&str] = &[ /// The names called in `m[from..to]`: functions (`name(`, also through a path), methods /// (`.name(`), including calls with turbofish arguments, and macros (`name!`). fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + calls_at(m, from, to).into_iter().map(|(name, method, _)| (name, method)).collect() +} + +/// [`calls`] with the offset of each called name. +fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(String, bool, usize)> { let m = &m[..to]; let mut out = vec![]; let mut i = from; @@ -1196,7 +1201,7 @@ fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { let name = String::from_utf8_lossy(&m[i..end]).into_owned(); let method = i > 0 && m[i - 1] == b'.'; if !KEYWORDS.contains(&name.as_str()) { - out.push((if bang { format!("{name}!") } else { name }, method)); + out.push((if bang { format!("{name}!") } else { name }, method, i)); } } i = end; @@ -1369,10 +1374,50 @@ pub fn asserting_helpers(files: &[(String, String)]) -> HashMap bool { let name = name.trim_end_matches('!'); - words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| m[..at].trim_ascii_end().ends_with(b"::")) + words(m, name.as_bytes(), 0, m.len()).into_iter().any(|at| { + let after = skip_ws(m, at + name.len()); + let renamed = m[after..].starts_with(b"as") && !m.get(after + 2).copied().is_some_and(is_ident) && { + let mut alias = skip_ws(m, after + 2); + if m[alias..].starts_with(b"r#") { + alias += 2; + } + let alias_end = alias + m[alias..].iter().take_while(|&&c| is_ident(c)).count(); + &m[alias..alias_end] != name.as_bytes() + }; + m[..at].trim_ascii_end().ends_with(b"::") && !(renamed && in_use(m, at)) + }) +} + +/// Whether the masked text at `at` is inside a `use` declaration, its groups (`use a::{b, c}`) +/// included. +fn in_use(m: &[u8], at: usize) -> bool { + let mut depth = 0usize; + let mut start = 0; + for i in (0..at).rev() { + match m[i] { + b'}' => depth += 1, + b'{' if depth > 0 => depth -= 1, + b'{' if m[..i].trim_ascii_end().ends_with(b"::") => {} + b'{' | b';' if depth == 0 => { + start = i + 1; + break; + } + _ => {} + } + } + let mut s = m[start..at].trim_ascii_start(); + if let Some(rest) = s.strip_prefix(b"pub").filter(|r| !r.first().copied().is_some_and(is_ident)) { + s = rest.trim_ascii_start(); + if s.first() == Some(&b'(') { + s = matching(s, 0).map_or(&[][..], |close| s[close + 1..].trim_ascii_start()); + } + } + s.starts_with(b"use") && !s.get(3).copied().is_some_and(is_ident) } /// The asserting helpers a test in the file at `path` can reach: for a top-level test, the file's @@ -1577,10 +1622,22 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); let none = HashSet::new(); let helpers = helpers_for(ctx, file.path, file.depths[t.attr] == 0).unwrap_or(&none); - let delegates = calls(m, t.open, t.close) - .iter() - .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) - || passes_helper(m, t, helpers); + // Failure messages run only after an assertion has failed, so a helper there does not check. + let messages: Vec<(usize, usize)> = asserts.iter().flat_map(|a| a.args.iter().skip(guard_arg_count(&a.name)).copied()).collect(); + let quiet = |at: usize| !messages.iter().any(|&(from, to)| from <= at && at < to); + // A bare call of a helper's name reaches a local binding of that name where one is in scope; a + // name that says it checks (`check_…`) counts either way. + let delegates = calls_at(m, t.open, t.close).iter().any(|(n, method, at)| { + n != &t.name + && quiet(*at) + && !(n.ends_with('!') && is_assert_macro(n)) + && is_helper_call(n, *method, helpers) + && (*method + || n.ends_with('!') + || is_helper_call(n, false, &HashSet::new()) + || m[..*at].trim_ascii_end().ends_with(b"::") + || !shadows_helper(m, t.fn_at, t.open, t.close, n.as_bytes(), *at)) + }) || passes_helper(m, t, helpers, &quiet); let checks = checks_itself(m, t.open, t.close); let should_panic = should_panic_attr(m, t.attr, t.fn_at); let diagnostic = ignored_with_reason(file, t.attr, t.fn_at) && prints(m, t.open, t.close); @@ -1598,10 +1655,11 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { /// Whether a test's body passes an asserting helper by name as a value, an argument or a tuple /// element (`keeping_settings(the_test_body)`, `[("case", case_body), …]`), excluding local bindings -/// and parameters that shadow helper names. -fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet) -> bool { +/// and parameters that shadow helper names. Only names at offsets `counts` accepts count. +fn passes_helper(m: &[u8], t: &TestFn, helpers: &HashSet, counts: &dyn Fn(usize) -> bool) -> bool { passed_names(m, t.open, t.close).into_iter().any(|(name, pos)| { - name != t.name + counts(pos) + && name != t.name && !COMMON.contains(&name.as_str()) && helpers.contains(&name) && !shadows_helper(m, t.fn_at, t.open, t.close, name.as_bytes(), pos) @@ -1629,7 +1687,7 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { } end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; } - if words(body, name, start, end).is_empty() { + if !pattern_binds(body, name, start, end) { return false; } let head = body[..at].trim_ascii_end(); @@ -1649,6 +1707,34 @@ fn bound_at(body: &[u8], name: &[u8], pos: usize) -> bool { lets || loops || arm_binding(body, &name, pos).is_some() || closure_binding(body, &name, pos).is_some() } +/// Whether the `let` pattern in `body[start..end]` binds `name`: not in its type annotation +/// (`let cb: body = …`) or as a field label (`let Row { near: _ } = …`). +fn pattern_binds(body: &[u8], name: &[u8], start: usize, end: usize) -> bool { + let annotation = annotation_start(body, start, end); + words(body, name, start, annotation).into_iter().any(|at| { + let after = skip_ws(body, at + name.len()); + let label = after != annotation && body.get(after) == Some(&b':') && body.get(after + 1) != Some(&b':'); + // A path segment (`let model::near = …`) names a constant or unit struct. + let path = body[..at].trim_ascii_end().ends_with(b"::") || body[after..].starts_with(b"::"); + !label && !path + }) +} + +/// The offset of a `let` pattern's type annotation in `body[start..end]`: its `:` outside the +/// pattern's brackets (not a `::` path), or `end` when there is none. +fn annotation_start(body: &[u8], start: usize, end: usize) -> usize { + let mut i = start; + while i < end { + match body[i] { + b'(' | b'[' | b'{' => i = matching(body, i).map_or(end, |close| close + 1), + b':' if body.get(i + 1) == Some(&b':') => i += 2, + b':' => return i, + _ => i += 1, + } + } + end +} + /// The innermost unclosed `(`, `[` or `{` before `at`. fn enclosing_open(m: &[u8], at: usize) -> Option { let mut depth = 0usize; @@ -1762,7 +1848,7 @@ fn ignored_with_reason(file: &File, from: usize, to: usize) -> bool { let m = &file.m; words(m, b"ignore", from, to).into_iter().any(|at| { let j = skip_ws(m, at + "ignore".len()); - m[..at].ends_with(b"#[") + m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) && m.get(j) == Some(&b'=') && ignore_reason(&file.src[skip_ws(m, j + 1)..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) }) @@ -1843,13 +1929,19 @@ fn all_unguarded(v: &View) -> Vec { SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to) }) }); - let sizes = Sizes { file: &v.file.m, consts: OnceCell::new() }; + let sizes = Sizes { file: &v.file.m, consts: OnceCell::new(), src: v.file.src, open: v.t.open, cond: RefCell::default() }; if checked || first_item_guard(&body, &sizes) { return vec![]; } v.asserts .iter() - .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at], &sizes)) + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) + .filter(|a| { + let cond = v.first_arg(a); + let lits = a.args.first().map(|&(from, to)| literals_in(v.file.src, &v.file.m, from, to)).unwrap_or_default(); + *sizes.cond.borrow_mut() = (cond.as_ptr() as usize, cond.clone(), lits); + unguarded_all(&cond, &v.file.m[v.t.open..a.at], &sizes) + }) .map(|a| { let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); h.first = v.file.lines.of(v.t.attr); @@ -2308,7 +2400,8 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { return None; } let at = let_init(body, &s, bound).map_or(0, |(_, at)| statement_end(body, at)); - Some((norm(text.as_bytes()), s, at)) + let end = statement_end(body, bound); + Some((norm(text.as_bytes()), s, at, sizes.literals(let_value(body, bound, end), end))) }) } else { None @@ -2318,7 +2411,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { return false; } let (left, right) = (norm(&body[a.args[0].0..a.args[0].1]), norm(&body[a.args[1].0..a.args[1].1])); - [(&left, &right), (&right, &left)].into_iter().any(|(pinned, literal)| { + [(&left, &right, a.args[0]), (&right, &left, a.args[1])].into_iter().any(|(pinned, literal, (from, to))| { if literal_len(literal, sizes) == 0 { return false; } @@ -2329,13 +2422,20 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { && plain_local(pinned) && init(pinned, a.at).is_some_and(|(text, at)| { let bound = statement_end(body, at); + let root = root_local(r); + let root_from = let_init(body, root, at).map_or(0, |(_, pos)| statement_end(body, pos)); keeping_base(&text, true) == r + && sizes.receiver_literals(r).is_some_and(|want| sizes.literals(let_value(body, at, bound), bound).starts_with(&want)) && !touched_after(&body[..a.at], pinned, bound, pinned) - && !touched_after(body, root_local(r), bound, r) + && !touched_after(body, root, bound, r) + && !gives_alias(&body[..at], root, root_from) }); // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its // literal is what the receiver holds. - read || source.as_ref().is_some_and(|(call, s, at)| pinned == call && !touched_after(body, s, *at, r)) + // Literal arguments (`r.items("active")`) are masked, so they are compared from the source. + read || source + .as_ref() + .is_some_and(|(call, s, at, lits)| pinned == call && *lits == sizes.literals(from, to) && !touched_after(body, s, *at, r)) }) }) } @@ -2369,6 +2469,66 @@ fn body_level_statement(body: &[u8], mut at: usize) -> bool { statement } +/// Where the value of the `let` at `at` starts: after its `=`, past the pattern and any type +/// annotation; `end` when it has none. +fn let_value(body: &[u8], at: usize, end: usize) -> usize { + let mut i = at + 3; + while i < end { + match body[i] { + b'(' | b'[' | b'{' => i = matching(body, i).map_or(end, |close| close + 1), + b'=' if !matches!(body.get(i + 1), Some(b'=' | b'>')) => return i + 1, + _ => i += 1, + } + } + end +} + +/// Whether `body[from..]` may keep a second handle to the local `name` that can change what it +/// holds later: a `let` that binds it or a borrow of it (`let b = &r;`), or a clone of it +/// (`r.clone()`, `Rc::clone(&r)`) anywhere. A borrow that ends with its call (`populate(&mut r)`) +/// and a method call on it (`r.push(1)`, `let n = r.len();`) do not. +fn gives_alias(body: &[u8], name: &str, from: usize) -> bool { + if !plain_local(name) { + return true; + } + words(body, name.as_bytes(), from.min(body.len()), body.len()).into_iter().any(|at| { + let statement = body[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let raw = body[statement..at].trim_ascii_start(); + let head = norm(&body[statement..at]); + // `let b = &r;`, `let b = &mut r;` or `let b = r;` keeps the local itself; `let n = r.len();` reads it. + let whole = matches!(body.get(skip_ws(body, at + name.len())), Some(b';' | b',' | b')') | None); + let bound = raw.strip_prefix(b"let").is_some_and(|r| !r.first().copied().is_some_and(is_ident)) + && whole + && ["=&", "=&mut", "="].iter().any(|end| head.ends_with(end)); + let cloned = body[skip_ws(body, at + name.len())..].starts_with(b".clone()") + || ["Rc::clone(&", "Arc::clone(&"].iter().any(|call| head.ends_with(call)); + // A clone passed straight to `drop`, or bound to `_`, is gone before the snapshot. + let dropped = ["drop(", "drop(Rc::clone(&", "drop(Arc::clone(&"].iter().any(|call| head.ends_with(call)) + || head.starts_with("let_=") + || head.starts_with("let_:"); + if !(bound || (cloned && !dropped)) { + return false; + } + // A handle made in a block that closes before the snapshot, or a bound one dropped before + // it, is gone too. + let mut block = enclosing_open(body, at); + while let Some(open) = block.filter(|&o| body[o] != b'{') { + block = enclosing_open(body, open); + } + if block.is_some_and(|open| matching(body, open).is_some()) { + return false; + } + let pattern = raw.strip_prefix(b"let").map(<[u8]>::trim_ascii_start).unwrap_or_default(); + let pattern = pattern.strip_prefix(b"mut ").map_or(pattern, <[u8]>::trim_ascii_start); + let alias = &pattern[..pattern.iter().take_while(|&&c| is_ident(c)).count()]; + let dropped_later = !alias.is_empty() + && words(body, alias, statement_end(body, at), body.len()) + .into_iter() + .any(|use_at| body[..use_at].trim_ascii_end().strip_suffix(b"(").is_some_and(|h| h.trim_ascii_end().ends_with(b"drop"))); + !dropped_later + }) +} + /// The local a receiver path starts from: `r` of `r.items()`. fn root_local(expr: &str) -> &str { let end = expr.bytes().take_while(|&c| is_ident(c)).count(); @@ -2468,7 +2628,14 @@ fn fixed_table_call(receiver: &str, test_body: &[u8], sizes: &Sizes) -> bool { let table_end = body.bytes().take_while(|&c| is_ident(c) || c == b':').count(); let table = &body[..table_end]; let screaming = !table.is_empty() && table.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); - if !screaming || item_len(table, sizes) == 0 || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) { + // A parameter of the same name (`fn rows(TABLE: &[u8])`) is what the body reads. + let binds_table = + split_args(file, params_open + 1, params_close).into_iter().any(|(from, to)| pattern_binds(file, table.as_bytes(), from, to)); + if !screaming + || binds_table + || item_len(table, sizes) == 0 + || !(body[table_end..].starts_with(".iter()") || body[table_end..].starts_with(".into_iter()")) + { return false; } // The body is the chain alone, of steps that keep every row. @@ -2513,7 +2680,7 @@ fn let_binds(body: &[u8], name: &[u8]) -> bool { } end = if matches!(body[end], b'(' | b'[' | b'{') { matching(body, end).map_or(body.len(), |close| close + 1) } else { end + 1 }; } - !words(body, name, start, end).is_empty() + pattern_binds(body, name, start, end) }) } @@ -3210,9 +3377,31 @@ fn field_len(receiver: &str, sizes: &Sizes) -> usize { struct Sizes<'a> { file: &'a [u8], consts: OnceCell>, + /// The file's source, and the offset in it of the test body that offsets are relative to. + src: &'a [u8], + open: usize, + /// The condition being checked: where its masked, whitespace-free text starts in memory, that + /// text, and its string literals' contents in order. + cond: RefCell<(usize, String, Vec>)>, } impl Sizes<'_> { + /// The contents of the string literals in `from..to` of the test body, in order. + fn literals(&self, from: usize, to: usize) -> Vec> { + literals_in(self.src, self.file, self.open + from, self.open + to) + } + + /// The contents of the string literals of `r`, a slice of the condition being checked; `None` + /// when `r` is not one. + fn receiver_literals(&self, r: &str) -> Option>> { + // A character literal's masked text (`''`) does not say which character it holds. + (!r.contains("''")).then_some(())?; + let cond = self.cond.borrow(); + let (base, masked, lits) = &*cond; + let at = (r.as_ptr() as usize).checked_sub(*base).filter(|&at| at + r.len() <= masked.len())?; + let first = masked.get(..at)?.matches('"').count() / 2; + lits.get(first..first + r.matches('"').count() / 2).map(<[Vec]>::to_vec) + } /// An unsigned integer literal (with `_` and an integer suffix allowed) or a `const` of the /// file whose value is one. fn count(&self, text: &str) -> Option { @@ -3220,14 +3409,27 @@ impl Sizes<'_> { } } +/// The contents of the string literals in `from..to`, in order: the source between each pair of +/// quotes that the masked text `m` keeps. +fn literals_in(src: &[u8], m: &[u8], from: usize, to: usize) -> Vec> { + let quotes: Vec = (from..to.min(m.len())).filter(|&i| m[i] == b'"').collect(); + quotes.as_chunks::<2>().0.iter().map(|&[open, close]| src[open + 1..close].to_vec()).collect() +} + fn int_literal(text: &str) -> Option { - let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count(); - let suffix = &text[digits..]; + // A decimal literal, or a `0x`, `0o` or `0b` one, takes the same suffixes. + let (radix, body) = [("0x", 16), ("0o", 8), ("0b", 2)] + .into_iter() + .find_map(|(prefix, radix)| text.strip_prefix(prefix).map(|rest| (radix, rest))) + .unwrap_or((10, text)); + let digits = body.bytes().take_while(|c| char::from(*c).is_digit(radix) || *c == b'_').count(); + let suffix = &body[digits..]; let suffixes = ["", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"]; - if digits == 0 || !text.as_bytes()[0].is_ascii_digit() || !suffixes.contains(&suffix) { + let number = body[..digits].replace('_', ""); + if number.is_empty() || (radix == 10 && !text.as_bytes()[0].is_ascii_digit()) || !suffixes.contains(&suffix) { return None; } - text[..digits].replace('_', "").parse().ok() + usize::from_str_radix(&number, radix).ok() } /// `const NAME: T = ;` in a masked file. A name declared more than once with @@ -3605,9 +3807,9 @@ fn ignore_hits(file: &File) -> Vec { let m = &file.m; let mut out = vec![]; for at in words(m, b"ignore", 0, m.len()) { - if !m[..at].ends_with(b"#[") { - continue; - } + // `#[ignore`, with whitespace allowed between the tokens. + let Some(bracket) = m[..at].trim_ascii_end().len().checked_sub(1).filter(|&b| m[b] == b'[') else { continue }; + let Some(hash) = m[..bracket].trim_ascii_end().len().checked_sub(1).filter(|&h| m[h] == b'#') else { continue }; let j = skip_ws(m, at + "ignore".len()); let reason = match m.get(j) { Some(b'=') => { @@ -3619,8 +3821,8 @@ fn ignore_hits(file: &File) -> Vec { if !reason { let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str()); // The hit sits on `#[ignore`; its span reaches the attribute's `]`, past a reason on a later line. - let mut hit = file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()); - hit.last = matching(m, at - 1).map_or(hit.line, |close| file.lines.of(close)); + let mut hit = file.hit(hash, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()); + hit.last = matching(m, bracket).map_or(hit.line, |close| file.lines.of(close)); out.push(hit); } } @@ -4123,7 +4325,6 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { i = if opens { close + 1 } else { i + 1 }; continue; } - let params = &body[i + 1..close]; let from = skip_ws(body, close + 1); let end = match body.get(from) { Some(b'{') => matching(body, from), @@ -4155,7 +4356,9 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { end } }; - if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) { + // A parameter's type (`|_: helper|`) binds nothing. + let binds = split_args(body, i + 1, close).into_iter().any(|(f, t)| pattern_binds(body, name.as_bytes(), f, t)); + if binds && from <= before && end.is_some_and(|end| before < end) { found = Some(i); } i = close + 1; @@ -4163,16 +4366,24 @@ fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { found } -/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body -/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not. +/// The offset of the guard, or of the `=>` when there is none, of the innermost match arm whose +/// pattern binds `name` and whose guard or body holds `before`: `Some(n) => assert_eq!(n, 1)` binds +/// `n`, `None => …` does not. fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { let mut found = None; - for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") { - // The pattern runs back to the `{` or `,` that opens the arm. + for arrow in (0..body.len().saturating_sub(1)).filter(|&i| &body[i..i + 2] == b"=>") { + // The pattern runs back to the `{` or `,` that opens the arm, or to the `}` that ends the + // block body of the arm before it, which needs no comma. let mut depth = 0usize; let mut start = arrow; while start > 0 { match body[start - 1] { + b'}' if depth == 0 + && enclosing_open(body, start - 1) + .is_some_and(|open| matching(body, open) == Some(start - 1) && body[..open].trim_ascii_end().ends_with(b"=>")) => + { + break; + } b')' | b']' | b'}' => depth += 1, b'(' | b'[' | b'{' if depth == 0 => break, b'(' | b'[' | b'{' => depth -= 1, @@ -4183,8 +4394,17 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { } // A guard (`Some(x) if x == n`) reads names; it does not bind them. let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); + if guard >= before { + continue; + } let pattern = norm_words(&body[start..guard]); - if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + let p = pattern.as_bytes(); + // A field label (`Row { body: _ }`) names a field; it binds nothing. + let label = |at: usize| { + let after = skip_ws(p, at + name.len()); + p.get(after) == Some(&b':') && p.get(after + 1) != Some(&b':') + }; + if !words(p, name.as_bytes(), 0, p.len()).into_iter().any(|at| !label(at)) { continue; } // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. @@ -4209,7 +4429,8 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { } }; if end.is_some_and(|end| before < end) { - found = Some(arrow); + // The binding starts at the guard, so a `let` inside the guard or the body is later. + found = Some(guard); } } found @@ -8066,5 +8287,144 @@ mod tests { assert_eq!(hits(diagnostic), []); assert_eq!(hits(&diagnostic.replace(" eprintln!(\"{n:?}\");\n", "")), [(3, "no-assertion")], "an ignored test that prints nothing"); assert_eq!(hits(&diagnostic.replace("#[ignore = \"manual timing\"]\n", "")), [(2, "no-assertion")], "a test that runs and only prints"); + assert_eq!(hits(&diagnostic.replace("#[ignore", "#[ ignore")), [], "whitespace after the attribute's bracket"); + assert_eq!( + hits(&diagnostic.replace("#[ignore = \"manual timing\"]", "#[ ignore = \" \"]")), + [(2, "ignore-without-reason"), (3, "no-assertion")], + "a blank reason after whitespace" + ); + assert_eq!(hits("#[test]\n# [ ignore ]\nfn t() {\n assert!(f());\n}\n"), [(2, "ignore-without-reason")], "no reason, with whitespace"); + } + + /// Two files that each define `near`: `own` asserts in it, the other does not. + fn near_files(own: &str) -> Ctx { + let other = "fn near(a: f64) -> bool { a < 1.0 }\n#[test]\nfn u() {\n assert!(near(f()));\n}\n"; + let files = [("crates/x/tests/it/own.rs".to_owned(), own.to_owned()), ("crates/x/tests/it/other.rs".to_owned(), other.to_owned())]; + Ctx { helpers: asserting_helpers(&files), ..Ctx::default() } + } + + #[test] + fn an_import_of_another_files_helper_is_not_a_call_with_a_path() { + let own = "use super::other::near as comparison;\nfn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n near(f());\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), []); + let called = own.replace(" near(f());", " other::near(f());"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &called, &near_files(&called)), [(4, "no-assertion")], "a call with a path"); + let raw = own.replace(" as comparison", " as r#near"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &raw, &near_files(&raw)), [(4, "no-assertion")], "a raw alias that keeps the name"); + let imported = own.replace(" as comparison", ""); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &imported, &near_files(&imported)), [(4, "no-assertion")], "an import that keeps the name"); + } + + #[test] + fn a_local_binding_shadows_a_called_helper() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n let near = |_: f64| {};\n near(f());\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), [(3, "no-assertion")]); + let after = own.replace(" let near = |_: f64| {};\n near(f());", " near(f());\n let near = |_: f64| {};\n near(f());"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &after, &near_files(&after)), [], "a call before the binding"); + let named = "fn check_result() { assert!(f()); }\n#[test]\nfn t() {\n let check = check_result;\n check();\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", named, &near_files(named)), [], "a name that says it checks"); + } + + /// A test that passes the asserting `body` to `keeping`, and its helpers. + fn body_src() -> (&'static str, Ctx) { + let src = "fn keeping(test: fn()) {\n test();\n}\nfn body() {\n assert_eq!(f(), 1);\n}\n#[test]\nfn t() {\n keeping(body);\n}\n"; + (src, Ctx { helpers: asserting_helpers(&[("crates/x/src/tests.rs".to_owned(), src.to_owned())]), ..Ctx::default() }) + } + + #[test] + fn a_helper_in_an_assertion_message_does_not_delegate() { + let (src, ctx) = body_src(); + let message = src.replace(" keeping(body);", " assert!(parse(input).is_ok(), \"{}\", keeping(body));"); + assert_eq!(hits_in("crates/x/src/tests.rs", &message, &ctx), [(8, "only-weak")], "the message runs only when the check fails"); + let condition = src.replace(" keeping(body);", " assert!(parse(input).is_ok(), \"{}\", 1);\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &condition, &ctx), [], "a call of its own"); + } + + #[test] + fn a_match_arm_binding_shadows_a_helper_in_its_guard() { + let (src, ctx) = body_src(); + let guard = src.replace(" keeping(body);", " match Some(noop as fn()) { Some(body) if run_body(body) => (), _ => () }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &guard, &ctx), [(8, "no-assertion")]); + let after = guard.replace("_ => () }", "_ => () }\n keeping(body);"); + assert_eq!(hits_in("crates/x/src/tests.rs", &after, &ctx), [], "the helper after the match"); + let label = src.replace(" keeping(body);", " match row() { Row { body: _ } if run_body(body) => (), _ => () }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &label, &ctx), [], "a field label binds nothing"); + let next_arm = src.replace(" keeping(body);", " match row() { Some(body) if ready() => {} _ if run_body(body) => (), _ => () }"); + assert_eq!(hits_in("crates/x/src/tests.rs", &next_arm, &ctx), [], "a guard after a block arm without a comma"); + } + + #[test] + fn a_type_annotation_does_not_shadow_a_helper() { + let (src, ctx) = body_src(); + let typed = format!("type body = fn();\n{}", src.replace(" keeping(body);", " let cb: body = || {};\n keeping(body);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &typed, &ctx), []); + let bound = format!("type body = fn();\n{}", src.replace(" keeping(body);", " let body: body = || {};\n keeping(body);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &bound, &ctx), [(9, "no-assertion")], "a binding with the same name as its type"); + let closure = format!("type body = u8;\n{}", src.replace(" keeping(body);", " let visit = |_: body| keeping(body);\n visit(0);")); + assert_eq!(hits_in("crates/x/src/tests.rs", &closure, &ctx), [], "a closure parameter's type binds nothing"); + } + + #[test] + fn all_over_a_hexadecimal_literal_range_is_guarded() { + let hex = "#[test]\nfn t() {\n assert!((0x1u8..0x3u8).all(|x| x > 0));\n}\n"; + assert_eq!(hits(hex), []); + assert_eq!(hits(&hex.replace("0x1u8..0x3u8", "0b11..0o3")), [(3, "all-unguarded")], "an empty range"); + assert_eq!(hits(&hex.replace("0x1u8..0x3u8", "0b1..0o3")), [], "binary and octal bounds"); + } + + #[test] + fn a_pin_reads_the_same_literal_selector() { + let pinned = "#[test]\nfn t() {\n let got: Vec = r.items(\"active\").iter().map(|j| j.n).collect();\n assert_eq!(got, vec![1]);\n assert!(r.items(\"active\").iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(pinned), []); + let other = pinned.replace("items(\"active\").iter().all", "items(\"archived\").iter().all"); + assert_eq!(hits(&other), [(5, "all-unguarded")], "another selector"); + let chars = + pinned.replace("items(\"active\").iter().map", "items('a').iter().map").replace("items(\"active\").iter().all", "items('b').iter().all"); + assert_eq!(hits(&chars), [(5, "all-unguarded")], "a character selector"); + } + + #[test] + fn a_parameter_named_like_a_table_is_not_the_table() { + let src = "mod other {\n const TABLE: [u8; 2] = [1, 2];\n}\nfn rows(TABLE: &[u8]) -> Vec {\n TABLE.iter().copied().collect()\n}\n#[test]\nfn t() {\n assert!(rows(&[]).iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(9, "all-unguarded")]); + } + + #[test] + fn a_pin_does_not_count_when_an_earlier_alias_shares_the_source() { + let rc = "#[test]\nfn t() {\n let r = Rc::new(RefCell::new(vec![1u8]));\n let got: Vec<_> = r.borrow().iter().copied().collect();\n assert_eq!(got, [1]);\n assert!(r.borrow().iter().all(|n| *n > 0));\n}\n"; + assert_eq!(hits(rc), [], "an unchanged source"); + let aliased = rc + .replace(" let got", " let alias = Rc::clone(&r);\n let got") + .replace(" assert!(r.borrow()", " alias.borrow_mut().clear();\n assert!(r.borrow()"); + assert_eq!(hits(&aliased), [(8, "all-unguarded")], "an alias made before the snapshot"); + let populated = rc.replace(" let got", " populate(&mut r);\n let got"); + assert_eq!(hits(&populated), [], "a borrow that ends with its call"); + let counted = rc.replace(" let got", " let _n = r.borrow().len();\n let got"); + assert_eq!(hits(&counted), [], "a getter read before the snapshot"); + let borrowed = rc + .replace(" let got", " let alias = &r;\n let got") + .replace(" assert!(r.borrow()", " alias.borrow_mut().clear();\n assert!(r.borrow()"); + assert_eq!(hits(&borrowed), [(8, "all-unguarded")], "a borrow bound before the snapshot"); + let dropped = rc.replace(" let got", " drop(Rc::clone(&r));\n let got"); + assert_eq!(hits(&dropped), [], "a clone dropped before the snapshot"); + let scoped = rc.replace(" let got", " {\n let alias = Rc::clone(&r);\n use_it(&alias);\n }\n let got"); + assert_eq!(hits(&scoped), [], "an alias whose block ends before the snapshot"); + let released = rc.replace(" let got", " let alias = Rc::clone(&r);\n drop(alias);\n let got"); + assert_eq!(hits(&released), [], "an alias dropped before the snapshot"); + let discarded = rc.replace(" let got", " let _ = Rc::clone(&r);\n let got"); + assert_eq!(hits(&discarded), [], "a clone bound to `_`"); + let typed = "#[test]\nfn t() {\n let got: Vec<[u8; \"x\".len()]> = r.items(\"active\").to_vec();\n assert_eq!(got, vec![[1]]);\n assert!(r.items(\"active\").iter().all(|j| j.ok));\n}\n"; + assert_eq!(hits(typed), [], "a literal in the snapshot's type"); + } + + #[test] + fn a_field_label_in_a_pattern_does_not_shadow_a_helper() { + let own = "fn near(a: f64) { assert!(a < 1.0); }\n#[test]\nfn t() {\n let Row { near: _ } = row();\n near(f());\n}\n"; + assert_eq!(hits_in("crates/x/tests/it/own.rs", own, &near_files(own)), []); + let path = own.replace("Row { near: _ }", "model::near"); + let alone = Ctx { helpers: asserting_helpers(&[("crates/x/tests/it/own.rs".to_owned(), path.clone())]), ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it/own.rs", &path, &alone), [], "a path segment binds nothing"); + let bound = own.replace("Row { near: _ }", "Row { near }"); + assert_eq!(hits_in("crates/x/tests/it/own.rs", &bound, &near_files(&bound)), [(3, "no-assertion")], "a field shorthand binds"); } } From 1eb22f6134f32fc217d0dcfb6dae9f6683838612 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 03:01:11 -0800 Subject: [PATCH 40/60] xtask: test-lint census entry reads skip path segments, comment gaps and block statements - An entry name after `::` (`defaults::c`) is a path segment, not a read of the loop binding. - A `let` initializer scans to the end of its statement, so a block initializer binds its tail (`{ prepare(); c }`) and not the earlier statements in the block; `if let` and `while let` end at their block. - A call keeps its name when masked comment whitespace sits before `(`, except after a keyword (`if (a)`). - The argument-guard and alias tests now depend on the logic they cover. --- xtask/src/test_lint.rs | 66 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 8 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 4c39f6ad13..f25a31ecf1 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1764,9 +1764,10 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); } - // A field access (`options.c`) or a field label (`Row { c: x }`) names a field, not the binding. + // A field access (`options.c`), a path segment (`defaults::c`) or a field label (`Row { c: x }`) + // names a field or an item, not the binding. let is_field = |at: usize, len: usize| { - b[..at].trim_ascii_end().last() == Some(&b'.') || { + b[..at].trim_ascii_end().last() == Some(&b'.') || b[..at].trim_ascii_end().ends_with(b"::") || { let next = skip_ws(b, at + len); b.get(next) == Some(&b':') && b.get(next + 1) != Some(&b':') } @@ -1785,9 +1786,27 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { else { continue; }; - let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); + // `if let` and `while let` end their initializer at the conditional's block. + let conditional = [b"if".as_slice(), b"while"].iter().any(|kw| b[from..at].trim_ascii_end().ends_with(kw)); + let end = if conditional { (eq..to).find(|&i| b[i] == b'{').unwrap_or(to) } else { statement_end(&b[..to], eq) }; + // A block initializer binds the value of its tail (`{ prepare(); c }`). + let mut value = eq + 1; + let init = skip_ws(b, value); + if !conditional && b.get(init) == Some(&b'{') && matching(b, init).is_some_and(|close| b[close + 1..end].trim_ascii().is_empty()) { + let close = matching(b, init).unwrap_or(end); + let mut i = init + 1; + value = i; + while i < close { + match b[i] { + b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close), + b';' => value = i + 1, + _ => {} + } + i += 1; + } + } let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); - if live(eq + 1, end, &derived, &shadows) { + if live(value, end, &derived, &shadows) { // Rebinding from the entry suspends earlier shadows until this block ends. let until = block_close(b, at).min(to); let mut resumed = vec![]; @@ -1937,9 +1956,18 @@ fn numeric_literal(s: &str) -> bool { /// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the /// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { - let before = open; + // Masked comments leave spaces between the name and the `(` (`app.run /* note */ (c)`). + let before = from + b[from..open].trim_ascii_end().len(); if before > from && is_ident(b[before - 1]) { - return Some(before); + // A keyword before a parenthesized expression (`if (a)`, `return (x)`) is not a call. + let mut start = before; + while start > from && is_ident(b[start - 1]) { + start -= 1; + } + const KEYWORDS: [&[u8]; 15] = + [b"if", b"else", b"match", b"while", b"for", b"in", b"return", b"break", b"let", b"mut", b"move", b"async", b"await", b"as", b"loop"]; + let keyword = KEYWORDS.contains(&&b[start..before]); + return (before == open || !keyword).then_some(before); } if before == from || b[before - 1] != b'>' { return None; @@ -8592,7 +8620,11 @@ mod tests { [(2, "census")], "a nested sibling keeps the enclosing guard" ); - assert_eq!(census("assert!(ready && accept(0, app.run(c)));"), [], "an asserted enclosing conjunction requires the argument"); + assert_eq!( + census("assert!(menu(c).is_some() && accept(0, app.run(c)).is_some());"), + [], + "an asserted enclosing conjunction requires the argument" + ); assert_eq!(census("let _ = accept(0, { app.run(c) }); assert!(menu(c).is_some());"), [], "an argument block runs"); assert_eq!( census("let _run = |_: ()| app.run(c); assert!(menu(c).is_some());"), @@ -8616,6 +8648,24 @@ mod tests { [(2, "census")], "a typed closure parameter shadows the entry" ); + assert_eq!( + census("app.run(defaults::c); assert!(menu(c).is_some());"), + [(2, "census")], + "a path segment named like the entry does not read it" + ); + assert_eq!(census("app.run(c); assert!(menu(c).is_some());"), [], "a plain argument reads the entry"); + assert_eq!(census("let input = { prepare(); c }; assert!(render(input, offset).is_ok());"), [], "a block initializer's tail binds the entry"); + assert_eq!(census("assert!(app.run /* note */ (c).is_ok());"), [], "a comment before the arguments keeps the call"); + assert_eq!( + census("let input = { prepare(); let _ = c; fixed }; assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"), + [(2, "census")], + "a block initializer binds its tail, not earlier statements" + ); + assert_eq!( + census("if let Some(input) = fallback() { prepare(); } menu(c); assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"), + [(2, "census")], + "an if let initializer ends at its block" + ); } #[test] @@ -8627,7 +8677,7 @@ mod tests { assert_eq!(census(split), [], "a chain split over lines keeps its receiver"); let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n"; assert_eq!(census(rendered), [], "a file written for each entry"); - let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(check_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; + let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(validate_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema"); let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n"; assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census"); From d359bb7e1a9b581b5ad7a76a061e3af1076bce24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 02:28:11 -0800 Subject: [PATCH 41/60] Print: Document.print throws for CUSTOMPROFILE without a profile name A script that set PrintColorManagementOptions.colorProfileMode to CUSTOMPROFILE and assigned no name printed with the base settings' profile, as though no custom profile had been asked for. The job now throws before anything is written, as it does for an empty name. Follows up on #9087. --- crates/engine/src/script/dom/print.rs | 8 +++++++- crates/engine/src/tests/script_print.rs | 1 + docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 2e1d374cb1..13e9222864 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -545,6 +545,8 @@ struct Job { paper_size: bool, /// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says. source: bool, + /// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` must name the profile. + custom: bool, /// `printArea` is assigned: the artboards print even when the base settings ignore them. print_area: bool, /// The groups of `settings`: the top level and each nested object by its key. @@ -693,6 +695,7 @@ fn map_color(h: &Host, slot: usize, job: &mut Job) { let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE"); job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v)); job.source = source; + job.custom = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "CUSTOMPROFILE"); let g = job.group("color"); for (k, v) in &set { if *k == "intent" { @@ -992,7 +995,7 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer { /// each assigned name against the list it must come from, and puts the checked names into the /// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its /// name (any case) and a paper by its id or label. An empty name, or one with a path separator or -/// a control character, throws. +/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`. fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { let (count, saved_ignore) = with_doc(h, doc, |_, st| { let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str); @@ -1022,6 +1025,9 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos } job.group("advanced").insert("flattenerPreset".into(), json!(n)); } + if job.custom && job.profile.is_none() { + return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into())); + } if let Some(name) = job.profile.take() { let what = "PrintColorManagementOptions.name"; let n = plain_name(what, "color profile", &name)?; diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 1c15b3e9f0..a69b306587 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -661,6 +661,7 @@ fn print_refuses_profile_paper_and_blank_preset_names() { ("c.name = 'No Such Profile';", profile), ("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile), ("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"), + ("c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE;", "PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE"), ("p.name = '../letter';", paper), ("p.name = 'let\\u0007ter';", paper), ("p.name = '\\tA4\\n';", paper), diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..b65bc040bc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3354,7 +3354,7 @@ through `$`: `print` starts from. `print` throws before anything is written when an assigned `artboardRange` names an artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset` is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any - case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom` + case) or `colorProfileMode` is assigned `CUSTOMPROFILE` without a `name`, when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom` and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or a control character (also at either end), throws too, and each checked name is sent without the spaces around it. `PPDName` takes only `""`. A listed option that is not mapped, or a value that is not mapped such as diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a2d5bcd1..cac5bfaeac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1121,7 +1121,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`. + - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). From cf51c8894cef9d5329e36f1be2f6ec948979fcd6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:55:33 -0800 Subject: [PATCH 42/60] xtask: test-lint decodes string continuations in cfg_attr paths and keeps census hits for fixed ranges A path string that continues on the next line with a backslash now decodes to the joined file name, so the conditional route is kept. A range argument with two fixed bounds (1..4, 1..=4) no longer counts as an input, so the round-trip census diagnostic stays; a range with a variable bound still suppresses it. Adds a test for a bracket in a cfg_attr path filename keeping its sibling cfg gate. --- xtask/src/test_lint.rs | 46 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 53f367f0e4..44d73697e2 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1851,7 +1851,8 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let mut operands = 0; let mut numeric = true; for (i, c) in s.char_indices().chain([(s.len(), '+')]) { - if !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { + let range = c == '.' && (s.as_bytes().get(i + 1) == Some(&b'.') || s[..i].ends_with('.')) || c == '=' && s[..i].ends_with(".."); + if !range && !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { continue; } let head = &s[start..i]; @@ -5067,6 +5068,9 @@ fn unescape(s: &str) -> String { continue; } match chars.next() { + Some(c @ ('\n' | '\r')) if c == '\n' || chars.peek() == Some(&'\n') => { + while chars.next_if(|c| matches!(c, ' ' | '\t' | '\n' | '\r')).is_some() {} + } Some('n') => out.push('\n'), Some('t') => out.push('\t'), Some('r') => out.push('\r'), @@ -5579,7 +5583,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, } let open = skip_ws(m, at + "cfg_attr".len()); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let text = pred_text(&src[open + 1..close]); + let text = norm_outside_literals(&mask_parts(&String::from_utf8_lossy(&src[open + 1..close]), true, false)); let cuts = attr_commas(&text); let Some(&first) = cuts.first() else { continue }; let mut start = first + 1; @@ -8618,6 +8622,30 @@ mod tests { assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]); } + #[test] + fn conditional_paths_decode_string_continuations() { + for newline in ["\n", "\r\n"] { + let src = format!("#[cfg_attr(unix, path = \"chi\\{newline} \t\r\n ld.rs\")]\nmod c;\n"); + assert_eq!(cfg_attr_paths(&mask(&src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child.rs".to_owned())]); + } + let src = "#[cfg_attr(unix, path = \"child file.rs\")]\nmod c;\n"; + assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child file.rs".to_owned())]); + let raw = "#[cfg_attr(unix, path = r\"chi\\\n ld.rs\")]\nmod c;\n"; + assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "chi\\\n ld.rs".to_owned())]); + } + + #[test] + fn conditional_paths_keep_sibling_cfg_gates_with_brackets_in_filenames() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"mac[.rs\", cfg(target_os = \"macos\"))]\nmod platform;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/mac[.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]); + } + #[test] fn path_attributes_accept_raw_strings() { for src in ["#[path = r\"shared.rs\"]\nmod s;\n", "#[path = r#\"shared.rs\"#]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n"] { @@ -8951,6 +8979,20 @@ mod tests { assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } + #[test] + fn census_keeps_diagnostics_for_fixed_range_arguments() { + for range in ["1..4", "1..=4", "-4..-1", "1..(2 + 2)"] { + let src = + format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n"); + assert_eq!(only("census", &src), [(2, "census")], "{range}"); + } + for range in ["1..limit", "1..=limit", "start..4", "1..(limit + 2)"] { + let src = + format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n"); + assert_eq!(only("census", &src), [], "{range}"); + } + } + #[test] fn numeric_literals_are_one_token() { for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] { From 5886c70c8da9856d14caa9cabc9a5de139581f99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:52:44 -0800 Subject: [PATCH 43/60] Print: maxPages turns a job away before raster effects are flattened file.print with maxPages flattened every raster effect in the document before it counted the pages, so a job it then turned away still paid for rendering each effect. The page count from the artboards now runs first, on the artboards alone, and raster effects are flattened only for a job that fits. Follows up on #9087. --- crates/engine/src/cmd/print.rs | 40 ++++++++++++++----------- crates/engine/src/cmd/rasterfx.rs | 8 +++++ crates/engine/src/tests/script_print.rs | 33 ++++++++++++++++++++ docs/mcp.md | 3 +- 4 files changed, 65 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 5d37ec4e9c..77e6d03395 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -240,15 +240,7 @@ fn print(s: &mut Session, p: &Value) -> Result { // The artboards' background colors print behind the art. let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(PRINT, e))?; let doc = &*filled; - // Raster effects print as images at the document's raster effects resolution. - let flat = super::rasterfx::flatten_raster_effects(doc); - let doc = flat.as_ref().unwrap_or(doc); let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; - // The flattener expands pattern fills whose tile images need flattening, in the layers that print. - let tile_images = postscript - && !bitmap - && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? - .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); let level = match p.get("level").filter(|v| postscript && !v.is_null()) { Some(v) => { let t = super::fileio::dxf::text(v); @@ -256,20 +248,32 @@ fn print(s: &mut Session, p: &Value) -> Result { } None => Level::default(), }; - // A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it, - // once the options are checked, when its pages follow from the artboards alone (composite, no - // `skipBlank`, artboards not ignored); the pages are counted again on the prepared art. - super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; + // A job past `maxPages` is turned away before its raster effects are flattened and before Print + // as Bitmap or a flattener preset prepares it, once the options are checked, when its pages + // follow from the artboards alone (composite, no `skipBlank`, artboards not ignored); the pages + // are counted again on the prepared art. + let flattener = super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; let by_artboards = !set.skip_blank && !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore) && set.output.mode == vectorcraft_pdf::OutputMode::Composite; - if max_pages.is_some() - && by_artboards - && let Ok(pv) = vectorcraft_pdf::preview(doc, &set) - && too_many(pv.pages) - { - return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } })); + // Those pages are counted on the artboards with no art, which is not prepared for the count. + if max_pages.is_some() && by_artboards { + let mut bare = Document::new(0.0, 0.0); + bare.artboards = doc.artboards.clone(); + bare.setup.bleed = doc.setup.bleed; + bare.color_mode = doc.color_mode; + bare.layers.clear(); + let pv = vectorcraft_pdf::preview(&bare, &set).map_err(|e| pdf_error(PRINT, e))?; + if too_many(pv.pages) { + return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } })); + } } + // Raster effects print as images at the document's raster effects resolution. + let flat = super::rasterfx::flatten_raster_effects(doc); + let doc = flat.as_ref().unwrap_or(doc); + // The flattener expands pattern fills whose tile images need flattening, in the layers that print. + let tile_images = + postscript && !bitmap && flattener.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index f035ff55f5..97dd890457 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -817,9 +817,17 @@ fn staged_all(out: &mut Document, nodes: &[Arc], report: &mut FlattenRepor /// type, images, symbol instances, live objects) and on single fills and strokes, in the layers, /// opacity masks, symbol definitions and pattern tiles. pub fn flatten_raster_effects(doc: &Document) -> Option { + #[cfg(test)] + FLATTENED.with(|n| n.set(n.get() + 1)); flatten(doc, &mut FlattenReport::new(Which::All, doc)) } +#[cfg(test)] +thread_local! { + /// How many times this thread called [`flatten_raster_effects`]. + pub(crate) static FLATTENED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// A copy of `doc` in which the objects with Photoshop-style raster effects (Radial Blur, Unsharp /// Mask…) or Rasterize are images as [`flatten_raster_effects`] makes them (SVG export: its /// filters draw the other raster effects live), or `None` when there are none. diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 1c15b3e9f0..06ca34fa45 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -389,6 +389,39 @@ fn file_print_max_pages_composes_only_what_fits() { let _ = std::fs::remove_dir_all(base); } +/// A job past `maxPages` is turned away before its raster effects are flattened. +#[test] +fn file_print_max_pages_turns_a_job_away_before_raster_effects_are_flattened() { + use crate::cmd::rasterfx::FLATTENED; + let base = folder("max-pages-raster"); + let mut s = session(&base); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow"})).unwrap(); + let before = FLATTENED.with(std::cell::Cell::get); + let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap(); + assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}"); + assert_eq!(FLATTENED.with(std::cell::Cell::get), before, "nothing was flattened"); + let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap(); + assert!(r["dataBase64"].is_string(), "{r}"); + assert!(FLATTENED.with(std::cell::Cell::get) > before, "a job that fits is flattened"); + let _ = std::fs::remove_dir_all(base); +} + +/// A job past the page limit throws before its raster effects are flattened. +#[test] +fn file_print_max_pages_returns_a_page_cap_error_before_raster_effects_are_flattened() { + use crate::cmd::rasterfx::FLATTENED; + let base = folder("max-pages-raster-cap"); + let mut s = session(&base); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow"})).unwrap(); + let before = FLATTENED.with(std::cell::Cell::get); + let e = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 700}})).unwrap_err().to_string(); + assert!(e.contains("more than 2000 pages"), "{e}"); + assert_eq!(FLATTENED.with(std::cell::Cell::get), before, "nothing was flattened"); + let _ = std::fs::remove_dir_all(base); +} + /// Bad values throw when they are assigned, and nothing prints. #[test] fn print_options_refuse_bad_values() { diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..25e0a5d587 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13221,7 +13221,8 @@ and, with copies per sheet, each copy's artboard on the page (`copies`), plus `t `inks` of a separation and `warnings`. `file.print {settings?, path?}` writes the job as a print-ready PDF (one page per sheet, tile, ink and copy); headless it answers `dataBase64`. With `maxPages`, the job is composed only when it prints at most that many pages, copies counted; with more, `file.print` composes and writes nothing and answers -`{pages, format}`. In the app, `file.print` with no params opens the Print +`{pages, format}`. A composite job without `skipBlank` that prints its artboards is counted on the artboards before +its raster effects are rendered. In the app, `file.print` with no params opens the Print dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. From 080f3c4a84d8be0c01ee8a86e16b55089601dbfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:01:07 -0800 Subject: [PATCH 44/60] JavaScript: legacy reflect find skips proxy traps; replacer lists charge kept names - `reflect.find` reads the reflection object and its lists with ordinary [[GetOwnProperty]], so a proxy receiver throws a TypeError without its getOwnPropertyDescriptor trap running. - `JSON.stringify` charges each distinct name a replacer array keeps for the length of the call, instead of reserving bytes for the whole length, so a long sparse replacer list no longer hits the heap limit. - A test checks that an outer proxy reads an inner proxy target's descriptors in its trap's combined order of names and Symbols. --- crates/js/src/builtins/json.rs | 15 +++++--- crates/js/src/proxy_tests.rs | 70 ++++++++++++++++++++++++++++++++-- crates/js/src/reflect.rs | 8 ++-- docs/mcp.md | 6 ++- 4 files changed, 85 insertions(+), 14 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index a6d8babc9e..e5027df1c6 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult { struct Settings { replacer: Option, properties: Option>, + _held_properties: Option, gap: Vec, } @@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { /// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8). fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult { - let mut s = Settings { replacer: None, properties: None, gap: Vec::new() }; + let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() }; if let Value::Object(r) = replacer { if interp.is_callable(replacer) { s.replacer = Some(replacer.clone()); } else if interp.is_array(replacer)? { - s.properties = Some(property_list(interp, *r)?); + let (keys, held) = property_list(interp, *r)?; + s.properties = Some(keys); + s._held_properties = Some(held); } } let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone()); @@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { +/// Each name kept is charged to the heap for as long as the returned holder lives. +fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { let len = super::collections::length_of(interp, r)?; if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { @@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult> { } // The list lives until the call returns, so its names are rooted. interp.temp_roots.push(Value::String(s)); + held.add(interp, ELEMENT_BYTES)?; list.push(k); } } - Ok(list) + Ok((list, held)) } /// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 20338eeca2..a3655d2b17 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1757,6 +1757,19 @@ fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); } +#[test] +fn legacy_reflect_find_reads_a_proxy_receiver_without_its_traps() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var r = ({{ a: 1 }}).reflect, find = r.find, calls = 0; + var p = new Proxy(r, {{ getOwnPropertyDescriptor: function (t, k) {{ calls++; return Object.getOwnPropertyDescriptor(t, k); }} }}); + find.call(r, 'a') !== null && type_error(function () {{ find.call(p, 'a'); }}) && calls === 0" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + #[test] fn transparent_proxy_and_reflect_membership_use_host_indexers() { let index: HostFunction = Rc::new(|args| { @@ -2036,6 +2049,14 @@ fn json_proxy_replacer_lengths_use_to_length() { ); } +#[test] +fn json_replacer_lists_charge_only_the_names_they_keep() { + // A long, sparse replacer array keeps one name, so only that name counts against the heap. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let src = "var r = ['a']; r.length = 50000; JSON.stringify({ a: 1, b: 2 }, r) === '{\"a\":1}'"; + assert_eq!(Realm::with_options(es_options(), limits).run(src), Ok(JsValue::Bool(true))); +} + #[test] fn json_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { @@ -2061,13 +2082,19 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { ), LimitKind::Fuel ); + // A replacer list's length alone is not charged to the heap; the names it keeps are. let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run( + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : undefined; } }); + JSON.stringify({ a: 1 }, p) === '{}'" + ), + Ok(JsValue::Bool(true)) + ); assert_eq!( limit( - "var p = new Proxy([], { get: function (t, k) { - if (k === 'length') return 1000000; - throw new Error('element read'); - } }); JSON.stringify({}, p)", + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : 'name' + k; } }); + JSON.stringify({}, p)", limits, ), LimitKind::Heap @@ -2116,6 +2143,41 @@ fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() { ); } +#[test] +fn own_keys_checks_target_descriptors_in_combined_key_order() { + truth( + "var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 }; + t[s] = 3; t[u] = 4; + var reads = [], extensible = 0; + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a', u, 'b']; }, + isExtensible: function () { extensible++; return true; }, + getOwnPropertyDescriptor: function (t, k) { + reads.push(String(k)); + if (k === s) Object.defineProperty(t, u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + // The descriptor of `s`, read first, makes `u` non-configurable before `u` is read, so the + // outer trap that leaves `u` out breaks the invariant. + var threw = type_error(function () { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a', s]; } })); }); + var ok = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', u, 'a']; } })); + threw && reads.slice(0, 4).join() === 'Symbol(s),a,Symbol(u),b' && extensible === 2 && ok.length === 3", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + #[test] fn own_keys_consumers_keep_interleaved_trap_keys() { truth( diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 62c63c6bb0..2949ccba0c 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -328,15 +328,17 @@ fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult flat_charged(interp, &s)?, Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?, _ => continue, diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..4e380d9057 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2902,7 +2902,8 @@ A conversion or syntax error throws before that prototype getter runs. membership checks use host collection indexers, including numeric indices and named items. `JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys -or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped. +or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped, +and each distinct name a replacer array keeps counts against it until the call returns. Its `toJSON` lookup skips host collection indexers through empty-handler proxies and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before @@ -2911,7 +2912,8 @@ the maximum safe integer. Reviver traversal keys count against the heap limit un In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating -its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations +its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without +calling proxy traps, so a proxy receiver throws `TypeError`. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`, `defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation From 3482b24069e2d9d8e5b80a77e3dc73084b4576d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:03:43 -0800 Subject: [PATCH 45/60] Release CI: RPM smoke check waits for its SVG fixture to open The installed-RPM smoke check passed as soon as `ui.inspect` answered, even when the GUI never opened the SVG fixture it was started with. The check now repeats `ui.inspect` until nothing is still opening and `original-smoke.svg` is listed among the open documents, and fails after 90 seconds otherwise. The check was added in #10128. --- .github/scripts/release-rpm-smoke.py | 20 ++++++++++--- .../scripts/tests/test_release_rpm_smoke.py | 28 +++++++++++++++++-- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/.github/scripts/release-rpm-smoke.py b/.github/scripts/release-rpm-smoke.py index 3d70cca7c1..27ba643b27 100644 --- a/.github/scripts/release-rpm-smoke.py +++ b/.github/scripts/release-rpm-smoke.py @@ -51,16 +51,28 @@ def run_smoke(results): time.sleep(1) channel.settimeout(30) with channel, channel.makefile("rwb") as stream: - for request_id, method, params in ( - (0, "auth", {"token": token}), - (1, "ui.inspect", {}), - ): + def request(request_id, method, params): stream.write((json.dumps(dict(id=request_id, method=method, params=params)) + "\n").encode()) stream.flush() response = json.loads(stream.readline()) (results / f"{method}.json").write_text(json.dumps(response, indent=2)) if response.get("id") != request_id or response.get("ok") is not True: raise RuntimeError(f"GUI request failed: {method}") + return response.get("result") or {} + + request(0, "auth", {"token": token}) + # The fixture opens off the UI thread: inspect until it is listed as an open document. + deadline = time.monotonic() + 90 + request_id = 1 + while True: + state = request(request_id, "ui.inspect", {}) + titles = [d.get("title", "") for d in state.get("documents", [])] + if not state.get("opening") and fixture.name in titles: + break + if time.monotonic() >= deadline: + raise RuntimeError(f"GUI did not open the fixture; open documents: {titles}") + request_id += 1 + time.sleep(1) finally: app.terminate() try: diff --git a/.github/scripts/tests/test_release_rpm_smoke.py b/.github/scripts/tests/test_release_rpm_smoke.py index 9d92237534..536702a69d 100644 --- a/.github/scripts/tests/test_release_rpm_smoke.py +++ b/.github/scripts/tests/test_release_rpm_smoke.py @@ -27,7 +27,7 @@ class SmokeLifecycleTests(unittest.TestCase): self.channel = MagicMock() self.stream = self.channel.makefile.return_value.__enter__.return_value self.stream.readline.side_effect = [ - b'{"id":0,"ok":true}\n', b'{"id":1,"ok":true,"result":{"window":"fixture"}}\n', + b'{"id":0,"ok":true}\n', self.inspection(1, ["original-smoke.svg"]), ] self.runtime = None @@ -41,6 +41,11 @@ class SmokeLifecycleTests(unittest.TestCase): self.connect = self.start_patch(smoke.socket, "create_connection", return_value=self.channel) self.start_patch(smoke.time, "sleep") + @staticmethod + def inspection(request_id, titles, opening=()): + result = {"documents": [{"title": title, "dirty": False} for title in titles], "opening": list(opening)} + return (json.dumps({"id": request_id, "ok": True, "result": result}) + "\n").encode() + def start_patch(self, owner, name, **kwargs): patcher = patch.object(owner, name, **kwargs) result = patcher.start() @@ -54,7 +59,7 @@ class SmokeLifecycleTests(unittest.TestCase): def test_success_records_inspection_and_removes_private_runtime(self): smoke.run_smoke(self.results) report = json.loads((self.results / "ui.inspect.json").read_text()) - self.assertEqual(report["result"], {"window": "fixture"}) + self.assertEqual(report["result"]["documents"][0]["title"], "original-smoke.svg") requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list] self.assertEqual(requests[0]["method"], "auth") self.assertEqual(requests[0]["params"]["token"], self.launch.call_args.kwargs["env"]["VECTORCRAFT_CONTROL_TOKEN"]) @@ -99,6 +104,25 @@ class SmokeLifecycleTests(unittest.TestCase): smoke.run_smoke(self.results) self.assert_cleaned_up() + def test_inspection_is_repeated_while_the_fixture_is_opening(self): + self.stream.readline.side_effect = [ + b'{"id":0,"ok":true}\n', + self.inspection(1, [], opening=["/results/original-smoke.svg"]), + self.inspection(2, ["original-smoke.svg"]), + ] + smoke.run_smoke(self.results) + requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list] + self.assertEqual([r["method"] for r in requests], ["auth", "ui.inspect", "ui.inspect"]) + self.assertEqual([r["id"] for r in requests], [0, 1, 2]) + self.assert_cleaned_up() + + def test_fixture_that_never_opens_is_a_failure(self): + self.stream.readline.side_effect = [b'{"id":0,"ok":true}\n', self.inspection(1, ["Untitled-1"])] + self.start_patch(smoke.time, "monotonic", side_effect=[0, 0, 91]) + with self.assertRaisesRegex(RuntimeError, "did not open the fixture"): + smoke.run_smoke(self.results) + self.assert_cleaned_up() + def test_malformed_response_still_stops_child(self): self.stream.readline.side_effect = [b'not json\n'] with self.assertRaises(json.JSONDecodeError): From b0bf3506dc4044a08549271fa9f0ba5a2183671a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:16:59 -0800 Subject: [PATCH 46/60] Print: a stalled paper-size lookup no longer piles up worker threads Each printer choice in the Print dialog started a new thread to read the driver's paper sizes, even while earlier reads were still running. A driver that stalls (printer enumeration has no time limit) left one thread behind per printer change. A new read now waits for the running worker. Only the newest choice is read once that worker ends. When the newest still-running worker has run 15 seconds, the waiting read starts beside it, up to 4 workers in all. A read that waits 15 seconds with 4 stalled workers gets no driver sizes, and the dialog keeps its own sizes. The lookup came from #10511. --- apps/vectorcraft/src/printing.rs | 205 +++++++++++++++++++++++++++---- 1 file changed, 182 insertions(+), 23 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index e7f5db9a69..6e73f0f52b 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -37,32 +37,88 @@ impl PrintService for SystemPrint { true } fn papers(&mut self, printer: &str, fresh: bool) -> Papers { - self.papers.poll(printer, fresh, |printer| installed_papers(&printer)) + self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer)) } } -/// The paper-size lookup in flight: the printer it reads and its worker's channel. +/// A paper-size read that waits for the worker before it. +type PaperRead = Box Vec + Send>; + +/// How long the newest still-running worker runs before a waiting read may start beside it, and how long a read waits +/// when no worker may start before its printer is given no paper sizes. +const PAPER_WAIT: std::time::Duration = std::time::Duration::from_secs(15); + +/// The most paper-size workers alive at once, stalled ones included. +const PAPER_WORKERS: usize = 4; + +/// The paper-size lookup: the printer it reads with its worker's channel, the read waiting to start with the time it +/// began waiting, and the start times and completion flags of its workers. A read starts when no worker runs, or when +/// the newest still-running worker has run [`PAPER_WAIT`] and fewer than [`PAPER_WORKERS`] are alive. #[derive(Default)] -struct PaperLookup(Option<(String, std::sync::mpsc::Receiver>)>); +struct PaperLookup { + current: Option<(String, std::sync::mpsc::Receiver>)>, + waiting: Option<(String, PaperRead, std::time::Instant)>, + started: Vec<(std::time::Instant, std::sync::Arc)>, + workers: std::sync::Arc, +} + +/// Marks a worker finished and counts it down when it ends, including when it panics. +struct WorkerDone(std::sync::Arc, std::sync::Arc); + +impl Drop for WorkerDone { + fn drop(&mut self) { + self.1.store(false, std::sync::atomic::Ordering::SeqCst); + self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } +} impl PaperLookup { - /// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight - /// reads another printer, or when none is in flight; the earlier one's answer is dropped. - fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { - if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) { - let (send, receive) = std::sync::mpsc::channel(); - let name = printer.to_string(); - let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { - let _ = send.send(read(name)); - }); - self.0 = Some((printer.to_string(), receive)); + /// Poll the lookup of `printer`. A new lookup of `read` is wanted when `fresh` is set, when the one in flight or + /// waiting reads another printer, or when none is in flight; the earlier one's answer is dropped. Only the newest + /// waiting read starts, when the workers allow it at `now`. Each new or replacement read begins waiting at `now`. + /// Finished workers do not delay a waiting read. A read that has waited [`PAPER_WAIT`] while + /// [`PAPER_WORKERS`] workers stall is dropped, and the printer gets no paper sizes. + fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { + let wanted = self.waiting.as_ref().map(|(p, ..)| p).or(self.current.as_ref().map(|(p, _)| p)); + if fresh || wanted.is_none_or(|p| p != printer) { + self.current = None; + self.waiting = Some((printer.to_string(), Box::new(read), now)); } - let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) { + self.started.retain(|(_, running)| running.load(std::sync::atomic::Ordering::SeqCst)); + let alive = self.workers.load(std::sync::atomic::Ordering::SeqCst); + let may_start = alive == 0 + || (alive < PAPER_WORKERS && self.started.last().is_none_or(|(started, _)| now.saturating_duration_since(*started) >= PAPER_WAIT)); + if may_start && let Some((name, read, _)) = self.waiting.take() { + let (send, receive) = std::sync::mpsc::channel(); + self.workers.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let done = WorkerDone(self.workers.clone(), running.clone()); + let printer = name.clone(); + let spawned = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { + let worker = done; + let papers = read(printer); + worker.1.store(false, std::sync::atomic::Ordering::SeqCst); + let _ = send.send(papers); + }); + if spawned.is_err() { + return Papers::Ready(Vec::new()); + } + self.started.push((now, running)); + self.current = Some((name, receive)); + } + if let Some((.., since)) = &self.waiting { + if now.saturating_duration_since(*since) < PAPER_WAIT { + return Papers::Pending; + } + self.waiting = None; + return Papers::Ready(Vec::new()); + } + let result = match self.current.as_ref().map(|(_, receive)| receive.try_recv()) { Some(Ok(papers)) => Papers::Ready(papers), Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending, Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()), }; - self.0 = None; + self.current = None; result } } @@ -254,15 +310,27 @@ mod paper_lookup_tests { vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }] } - /// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers. - fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec { - let mut polled = lookup.poll(printer, true, move |_| paper(key)); + /// The test clock: `secs` seconds after a fixed start. + fn at(secs: u64) -> std::time::Instant { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + *START.get_or_init(std::time::Instant::now) + std::time::Duration::from_secs(secs) + } + + /// Poll the lookup of `printer` at `now` until it answers. + fn settle(lookup: &mut PaperLookup, printer: &str, now: std::time::Instant) -> Vec { loop { - match polled { + match lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) { Papers::Ready(papers) => return papers, Papers::Pending => std::thread::yield_now(), } - polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup")); + } + } + + /// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers. + fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec { + match lookup.poll(printer, true, at(0), move |_| paper(key)) { + Papers::Ready(papers) => papers, + Papers::Pending => settle(lookup, printer, at(0)), } } @@ -279,19 +347,110 @@ mod paper_lookup_tests { fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() { let mut lookup = PaperLookup::default(); let (open, read) = gated("Old"); - assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); let (other, read) = gated("Office"); - assert!(matches!(lookup.poll("Office", true, read), Papers::Pending)); + assert!(matches!(lookup.poll("Office", true, at(0), read), Papers::Pending)); let _ = open.send(()); let _ = other.send(()); // Back on the card printer. assert_eq!(answer(&mut lookup, "Card", "New"), paper("New")); // The dialog opens again on the card printer while a lookup of it is still running. let (open, read) = gated("Stale"); - assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); let _ = open.send(()); assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer")); } + + #[test] + fn a_stalled_lookup_holds_the_only_worker_while_the_printer_changes() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut lookup = PaperLookup::default(); + let (open, read) = gated("Stalled"); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); + let started = std::sync::Arc::new(AtomicUsize::new(0)); + for (i, printer) in ["Office", "Card", "Office", "Plotter"].into_iter().cycle().take(40).enumerate() { + let count = started.clone(); + let polled = lookup.poll(printer, i % 3 == 0, at(1), move |_| { + count.fetch_add(1, Ordering::SeqCst); + paper("Changed") + }); + assert!(matches!(polled, Papers::Pending), "{printer}"); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "only the stalled worker runs"); + } + let _ = open.send(()); + // Only the newest choice is read, once the stalled worker ends. + assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed")); + assert_eq!(started.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_waiting_read_starts_beside_a_worker_stalled_for_the_wait() { + use std::sync::atomic::Ordering; + let mut lookup = PaperLookup::default(); + let (card, read) = gated("Stalled"); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); + let (office, read) = gated("Office"); + assert!(matches!(lookup.poll("Office", false, at(1), read), Papers::Pending)); + assert!(matches!(lookup.poll("Office", false, at(14), |_| panic!("polling starts no lookup")), Papers::Pending)); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "the read waits while the worker is new"); + // The worker has stalled for the whole wait: the waiting read starts beside it. + assert!(matches!(lookup.poll("Office", false, at(15), |_| panic!("polling starts no lookup")), Papers::Pending)); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the waiting read starts beside the stalled worker"); + let _ = office.send(()); + assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office")); + // The worker that answered counts itself down once its thread ends. + while lookup.workers.load(Ordering::SeqCst) > 1 { + std::thread::yield_now(); + } + // The older worker has stalled long enough for another read to start immediately. + let (next, began) = std::sync::mpsc::channel(); + let (open, read) = gated("Next"); + assert!(matches!( + lookup.poll("Next", false, at(16), move |printer| { + let _ = next.send(()); + read(printer) + }), + Papers::Pending + )); + assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the next read starts without another wait"); + began.recv().expect("the next read started"); + let _ = open.send(()); + assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next")); + drop(card); + } + + #[test] + fn a_printer_waiting_on_stalled_workers_gets_no_sizes_after_the_wait() { + use std::sync::atomic::Ordering; + let mut lookup = PaperLookup::default(); + let (card, read) = gated("Stalled"); + assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); + // More stalls fill the workers up to the limit, one wait apart. + let mut stalls = vec![card]; + for (i, printer) in ["Plotter", "Scanner", "Fax"].into_iter().enumerate() { + let (gate, read) = gated("Stalled"); + stalls.push(gate); + assert!(matches!(lookup.poll(printer, true, at(30 + 15 * i as u64), read), Papers::Pending), "{printer}"); + } + assert!(matches!(lookup.poll("Label", true, at(61), |_| panic!("no worker may start")), Papers::Pending)); + assert!(matches!(lookup.poll("Label", false, at(75), |_| panic!("polling starts no lookup")), Papers::Pending)); + // Reopening the same printer and choosing another printer each starts a new wait. + assert!(matches!(lookup.poll("Label", true, at(76), |_| panic!("no worker may start")), Papers::Pending)); + assert!(matches!(lookup.poll("Photo", false, at(91), |_| panic!("no worker may start")), Papers::Pending)); + assert!(matches!(lookup.poll("Photo", false, at(105), |_| panic!("polling starts no lookup")), Papers::Pending)); + match lookup.poll("Photo", false, at(106), |_| panic!("polling starts no lookup")) { + Papers::Ready(papers) => assert_eq!(papers, []), + Papers::Pending => panic!("the wait for the stalled workers did not end"), + } + assert!(lookup.workers.load(Ordering::SeqCst) <= super::PAPER_WORKERS); + // Once the stalled workers end, the next choice is read again. + drop(stalls); + let papers = match lookup.poll("Photo", true, at(107), |_| paper("Ready")) { + Papers::Ready(papers) => papers, + Papers::Pending => settle(&mut lookup, "Photo", at(107)), + }; + assert_eq!(papers, paper("Ready")); + } } #[cfg(test)] From fffcca5cd2c9f422b75b9f67458bbe58c917a948 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:20:29 -0800 Subject: [PATCH 47/60] CI: build paths without parent-step literals the read check counts as reads The shared gate's undeclared-read check (select legs) reports two reads on main: crates/text/build.rs reads the workspace root (`.`) and crates/engine/src/tests/fontfiles.rs reads `crates`. Neither path names another member's files. - crates/text/build.rs takes the workspace root as the second ancestor of the crate directory instead of joining "../..". A relative CRAFT_FONTS_DIR still resolves from the same directory. - the_fonts_folder_next_to_a_document_is_an_absolute_path builds its climb to the filesystem root from ParentDir components instead of formatting a repeated "../". The test still opens the document by a relative path to its temporary folder. The check reports 0 problems on the result, down from 2 on main. --- crates/engine/src/tests/fontfiles.rs | 4 ++-- crates/text/build.rs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index e90aec1df9..fc8d72ead2 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -143,8 +143,8 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { let (_dir, root) = folder("relative"); std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap(); let cwd = std::env::current_dir().unwrap(); - let up = "../".repeat(cwd.components().count().saturating_sub(1)); - let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display()); + let up: PathBuf = cwd.components().skip(1).map(|_| std::path::Component::ParentDir).collect(); + let relative = up.join(root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap()).display().to_string(); assert!(Path::new(&relative).is_relative()); let mut s = session_for(&root); let mut doc = vectorcraft_doc::Document::new(100.0, 100.0); diff --git a/crates/text/build.rs b/crates/text/build.rs index 7863efe464..99eb1587f3 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -103,7 +103,8 @@ fn from_workspace(dir: PathBuf) -> PathBuf { return dir; } let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); - crate_dir.join("../..").join(dir) + // The workspace root is two levels above `crates/text`. + crate_dir.ancestors().nth(2).unwrap_or(&crate_dir).join(dir) } /// The one craft-fonts face web builds embed (family, style). From 337b47a309ad1e405659ac56cf893cd7c668d123 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:23:12 -0800 Subject: [PATCH 48/60] JavaScript: with scopes honor Symbol.unscopables; concat reads isConcatSpreadable - A `with` scope reads `Symbol.unscopables` after it finds a name, through a proxy's `get` trap, and skips the binding when that object's property for the name is truthy. - `concat` reads `Symbol.isConcatSpreadable`, through proxy traps; a defined value decides whether the object is spread. - `Object.keys` and `Object.getOwnPropertyNames` keep the target's order through empty-handler proxies. - `%TypedArray%.from` and `of` construct through a proxy constructor and check that the result is a typed array long enough. --- crates/js/src/builtins/array.rs | 8 +- crates/js/src/builtins/binary.rs | 28 ++++- crates/js/src/builtins/symbol.rs | 4 +- crates/js/src/interp.rs | 35 ++++-- crates/js/src/proxy.rs | 6 +- crates/js/src/proxy_tests.rs | 191 ++++++++++++++++++++++++++++--- crates/js/src/symbol.rs | 16 ++- docs/mcp.md | 8 ++ 8 files changed, 257 insertions(+), 39 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index ac8dd4639c..48dfe1832a 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -389,8 +389,12 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult let mut n = 0u64; for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) { interp.use_fuel()?; - // A proxy whose target is an array is spread too (ECMA-262 2020 section 22.1.3.1.1). - let spread = if interp.is_array(&e)? { e.as_object() } else { None }; + let override_spread = match (e.as_object(), interp.well_known(|w| &w.is_concat_spreadable)) { + (Some(_), Some(sym)) => interp.get_value_sym(&e, &sym)?, + _ => Value::Undefined, + }; + let spread = if matches!(override_spread, Value::Undefined) { interp.is_array(&e)? } else { override_spread.truthy() }; + let spread = if spread { e.as_object() } else { None }; let Some(e) = spread else { if n >= 9_007_199_254_740_991 { return Err(interp.type_error("concat exceeds the maximum safe length")); diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 5a48799007..16c6a6a160 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -824,6 +824,23 @@ fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) } +fn typed_create(interp: &mut Interp, this: &Value, len: u64, name: &str) -> JsResult { + if !this.as_object().is_some_and(|o| interp.is_proxy(o)) { + let elem = ctor_elem(interp, this, name)?; + return new_typed(interp, elem, len); + } + #[allow(clippy::cast_precision_loss)] + let result = interp.construct_value(this, &[Value::Number(len as f64)], this)?; + interp.rooted(std::slice::from_ref(&result), |interp| { + let Some(o) = result.as_object() else { return Err(interp.type_error("the constructor did not return a typed array")) }; + let Some(view) = view_of(interp, o) else { return Err(interp.type_error("the constructor did not return a typed array")) }; + if (view.length as u64) < len { + return Err(interp.type_error(&format!("TypedArray.{name} constructor returned a typed array that is too short"))); + } + Ok(o) + }) +} + /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { if !interp.is_constructor(&this) { @@ -836,16 +853,15 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe } let this_arg = arg(args, 2); let map = mapping.then_some((&map_fn, &this_arg)); - typed_array_from(interp, &arg(args, 0), map, |interp, len| { - let elem = ctor_elem(interp, &this, "from")?; - new_typed(interp, elem, len) - }) + typed_array_from(interp, &arg(args, 0), map, |interp, len| typed_create(interp, &this, len, "from")) } /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let elem = ctor_elem(interp, &this, "of")?; - let ta = new_typed(interp, elem, args.len() as u64)?; + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); + } + let ta = typed_create(interp, &this, args.len() as u64, "of")?; let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index 0bbccebb1c..e020e6335b 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -18,6 +18,8 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { ("hasInstance", well_known.has_instance.clone()), ("toPrimitive", well_known.to_primitive.clone()), ("toStringTag", well_known.to_string_tag.clone()), + ("unscopables", well_known.unscopables.clone()), + ("isConcatSpreadable", well_known.is_concat_spreadable.clone()), ]; let (to_string_tag, to_primitive, has_instance) = (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); @@ -171,7 +173,7 @@ fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bo interp.rooted(&[Value::Object(o)], |interp| { // A proxy's list stays counted against the heap until the array holds its Symbols. let (syms, _held) = if interp.is_proxy(o) { - let keys = interp.proxy_own_keys(o)?; + let keys = interp.proxy_own_keys(o, false)?; (keys.syms, keys.held) } else { let syms = interp.own_symbols(o)?; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 5f1f170b8b..2aa5c933c9 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1619,7 +1619,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return Ok(Resolved::Obj { object, with_this }); } cur = outer; @@ -1630,6 +1630,20 @@ impl Interp { Ok(Resolved::Unresolved) } + fn scope_binding(&mut self, object: ObjId, name: &Key, with_this: bool) -> JsResult { + if !self.scope_has(object, name)? { + return Ok(false); + } + if with_this && let Some(sym) = self.well_known(|w| &w.unscopables) { + let blocked = self.get_value_sym(&Value::Object(object), &sym)?; + if let Value::Object(o) = blocked { + let value = self.rooted(&[Value::Object(o)], |i| i.get_from(o, name, &Value::Object(o)))?; + return Ok(!value.truthy()); + } + } + Ok(true) + } + pub(crate) fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult { match self.heap.env(env) { Some(Env::Decl { bindings, .. }) => Ok(bindings.get(name).map_or(Value::Undefined, |b| b.value.clone())), @@ -1673,7 +1687,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return self.get_resolved(Resolved::Obj { object, with_this }, name); } let this = Value::Object(object); @@ -2389,7 +2403,7 @@ impl Interp { /// list is checked first. A proxy's names come from its `ownKeys` trap. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, false); } let o = self.object(id)?; // A typed array's indices come first, as a String object's do (section 9.4.5.6). @@ -2422,14 +2436,15 @@ impl Interp { } pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult { - let mut keys = self.own_keys(id)?; - if !self.is_proxy(id) { - if matches!(self.object(id)?.class, Class::Array { .. }) { - let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; - keys.insert(0, length); - } - keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); + if self.is_proxy(id) { + return self.proxy_own_keys(id, true); } + let mut keys = self.own_keys(id)?; + if matches!(self.object(id)?.class, Class::Array { .. }) { + let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; + keys.insert(0, length); + } + keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); Ok(keys) } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index fcb103b50c..e709cfd808 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -421,11 +421,11 @@ impl Interp { /// non-configurable key of the target, and of a non-extensible target exactly its keys. Each /// key takes a unit of fuel and counts against the heap limit until the caller drops the list, /// which keeps the trap's order in [`HeldKeys::ordered`]. - pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { + pub(crate) fn proxy_own_keys(&mut self, p: ObjId, ecma_order: bool) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { // A target that is a proxy gives its Symbols with its names. - let mut keys = i.ecma_own_keys(target)?; + let mut keys = if ecma_order { i.ecma_own_keys(target)? } else { i.own_keys(target)? }; if !i.is_proxy(target) { keys.syms = i.own_symbols(target)?; keys.held.add(i, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; @@ -444,7 +444,7 @@ impl Interp { /// one `ownKeys` trap call for a proxy. pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, false); } let mut keys = self.own_keys(id)?; keys.syms = self.own_symbols(id)?; diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index a3655d2b17..efb6bb78e8 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -744,6 +744,152 @@ fn a_descriptor_a_trap_makes_stays_reachable_while_it_is_read() { // ---- proxies elsewhere in the language ---- +#[test] +fn proxy_with_bindings_honor_unscopables() { + truth_collecting( + "var x = 'outer', result, log = [], scope, blocked; + var p = new Proxy({ x: 'inner' }, { + has: function (t, k) { if (k === 'x') log.push('has'); return Reflect.has(t, k); }, + get: function (t, k, r) { + if (k === Symbol.unscopables) { + scope = r; + return new Proxy({ x: true }, { get: function (t, k, r) { + log.push(k); blocked = r; return t[k]; + } }); + } + throw 'unexpected binding read'; + } + }); + with (p) { result = x; } + result === 'outer' && scope === p && typeof blocked === 'object' && log.join() === 'has,x'", + ); + for blocked in ["undefined", "null", "false", "1", "{}", "{ x: false }"] { + truth(&format!( + "var x = 'outer', result, t = {{ x: 'inner' }}; + t[Symbol.unscopables] = {blocked}; + with (new Proxy(t, {{}})) {{ result = x; }} + result === 'inner'" + )); + } + truth( + "var x = 'outer', kind, result, t = { x: 'inner' }; + t[Symbol.unscopables] = { x: true }; + with (new Proxy(t, {})) { x = 'changed'; kind = typeof x; result = delete x; } + x === 'changed' && t.x === 'inner' && kind === 'string' && result === false", + ); + for trap in ["return new Proxy({}, { get: function () { throw marker; } });", "throw marker;"] { + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy({{ x: 1 }}, {{ get: function (t, k) {{ + if (k === Symbol.unscopables) {{ {trap} }} return t[k]; + }} }}); + try {{ with (p) {{ x; }} }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); + assert_eq!( + realm.run( + "function method() { return 'outer'; } + var t = { method: function () { return 'inner'; } }, result; + t[Symbol.unscopables] = { method: true }; + with (new Proxy(t, {})) { result = method(); } + result === 'outer'" + ), + Ok(JsValue::Bool(true)) + ); +} + +#[test] +fn transparent_proxies_preserve_object_key_order() { + truth_collecting( + "var o = { z: 0, 10: 10, 2: 2, a: 1 }, a = [1, 2]; a.label = 'a'; + [o, a].every(function (target) { + var p = new Proxy(new Proxy(target, {}), {}); + return Object.keys(p).join() === Object.keys(target).join() && + Object.getOwnPropertyNames(p).join() === Object.getOwnPropertyNames(target).join() && + Reflect.ownKeys(p).join() === Reflect.ownKeys(target).join(); + })", + ); + truth( + "var calls = 0, p = new Proxy({ a: 1, b: 2 }, { ownKeys: function () { calls++; return ['b', 'a']; } }); + var q = new Proxy(p, {}); + Object.keys(q).join() === 'b,a' && Object.getOwnPropertyNames(q).join() === 'b,a' && + Reflect.ownKeys(q).join() === 'b,a' && calls === 3", + ); +} + +#[test] +fn concat_honors_proxy_spreadability_overrides() { + truth_collecting( + "var reads = 0, receiver, p = new Proxy([1, 2], { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads++; receiver = r; return false; } + return Reflect.get(t, k, r); + } }); + var a = [].concat(p), b = p.concat(3); + a.length === 1 && a[0] === p && b.length === 2 && b[0] === p && b[1] === 3 && reads === 2 && receiver === p", + ); + truth_collecting( + "var reads = [], receiver; + var p = new Proxy({ 0: 'a', 2: 'c', length: 3 }, { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads.push('spread'); receiver = r; return true; } + reads.push(k); return Reflect.get(t, k, r); + } }); + var a = [].concat(p); + a.length === 3 && a[0] === 'a' && !(1 in a) && a[2] === 'c' && receiver === p && reads.join() === 'spread,length,0,2'", + ); + truth( + "var p = new Proxy([1, 2], {}), t = [3, 4]; t[Symbol.isConcatSpreadable] = null; + var q = new Proxy(t, {}), a = [].concat(p, q); + a.length === 3 && a[0] === 1 && a[1] === 2 && a[2] === q", + ); + truth( + "var marker = {}, caught = false; + var p = new Proxy([], { get: function (t, k) { if (k === Symbol.isConcatSpreadable) throw marker; return t[k]; } }); + try { [].concat(p); } catch (e) { caught = e === marker; } + caught", + ); + type_errors(&["var p = Proxy.revocable([], {}); p.revoke(); [].concat(p.proxy)"]); +} + +#[test] +fn typed_array_statics_construct_through_proxy_receivers() { + truth_collecting( + "var p = new Proxy(Uint8Array, {}), a = p.of(257, 2), b = p.from([3, 260]); + a instanceof Uint8Array && a.length === 2 && a[0] === 1 && a[1] === 2 && + b instanceof Uint8Array && b.length === 2 && b[0] === 3 && b[1] === 4", + ); + truth_collecting( + "var calls = [], receiver, context = { add: 1 }; + var p = new Proxy(Uint8Array, { construct: function (t, args, nt) { + calls.push(t === Uint8Array, args.length, args[0], nt === p); + return new Uint16Array(args[0]); + } }); + var a = p.of(257, 2), b = p.from({ 0: 300, length: 1 }, function (v, i) { receiver = this; return v + i + this.add; }, context); + a instanceof Uint16Array && a[0] === 257 && a[1] === 2 && b instanceof Uint16Array && b[0] === 301 && + receiver === context && calls.join() === 'true,1,2,true,true,1,1,true'", + ); + for method in ["of(1, 2)", "from([1, 2])"] { + for result in ["{}", "new Uint8Array(1)", "new Proxy(new Uint8Array(2), {})"] { + truth(&format!( + "var p = new Proxy(Uint8Array, {{ construct: function () {{ return {result}; }} }}); + type_error(function () {{ p.{method}; }})" + )); + } + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy(Uint8Array, {{ construct: function () {{ throw marker; }} }}); + try {{ p.{method}; }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + truth( + "var pair = Proxy.revocable(Uint8Array, {}), p = pair.proxy; + pair.revoke(); + type_error(function () { Uint8Array.of.call(p, 1); }) && type_error(function () { Uint8Array.from.call(p, [1]); })", + ); +} + #[test] fn a_proxy_works_as_a_prototype_and_a_with_scope() { truth( @@ -769,21 +915,27 @@ fn a_proxy_works_as_a_prototype_and_a_with_scope() { fn typeof_reads_the_binding_a_with_scope_reported_once() { // GetBindingValue asks `has` again, and a binding gone by then reads as undefined without `get`. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return k === 'x' ? function () {} : undefined; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return k === 'x' ? function () {} : undefined; + } }); var r; with (p) { r = typeof x; } - r === 'undefined' && asked === 2 && got === 0", + r === 'undefined' && asked === 2 && got === 0 && unscopables === 1", ); // A plain read of the same binding takes the same path. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return 1; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return 1; + } }); var r; with (p) { r = x; } - r === undefined && asked === 2 && got === 0", + r === undefined && asked === 2 && got === 0 && unscopables === 1", ); } @@ -792,15 +944,19 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { for present in ["asked++ < 2", "asked++ === 0", "false"] { let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); let src = format!( - "var asked = 0, got = 0, outer = 0, receiver; + "var asked = 0, got = 0, outer = 0, unscopables = 0, receiver; function method() {{ outer++; return 'outer'; }} var p = new Proxy({{}}, {{ has: function (t, k) {{ return k === 'method' && ({present}); }}, - get: function () {{ got++; return function () {{ receiver = this; return 'proxy'; }}; }} + get: function (t, k) {{ + if (k === Symbol.unscopables) {{ unscopables++; return undefined; }} + got++; return function () {{ receiver = this; return 'proxy'; }}; + }} }}); var result, caught = false; try {{ with (p) {{ result = method(); }} }} catch (e) {{ caught = e instanceof TypeError; }} - {expected}", + ({expected}) && unscopables === {unscopables}", + unscopables = usize::from(present != "false"), expected = match present { "asked++ < 2" => "result === 'proxy' && receiver === p && asked === 2 && got === 1 && outer === 0 && !caught", "asked++ === 0" => "caught && asked === 2 && got === 0 && outer === 0", @@ -816,16 +972,21 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { #[test] fn concat_proxy_array_lengths_use_to_length() { truth( - "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0; + "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0, spreadReads = 0; var empty = lengths.every(function (length) { var p = new Proxy([7], { - get: function (t, k) { if (k === 'length') return length; reads++; return t[k]; }, + get: function (t, k) { + if (k === Symbol.isConcatSpreadable) { spreadReads++; return undefined; } + if (k === 'length') return length; + reads++; return t[k]; + }, has: function () { reads++; return true; } }); return [3].concat(new Proxy(p, {}), 9).join() === '3,9'; }); var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } }); - empty && reads === 0 && [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", + empty && reads === 0 && spreadReads === lengths.length && + [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", ); } @@ -855,7 +1016,11 @@ fn concat_and_reviver_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { let setup = format!( "var p = new Proxy([], {{ - get: function (t, k) {{ if (k === 'length') return {length}; throw new Error('element read'); }}, + get: function (t, k) {{ + if (k === Symbol.isConcatSpreadable) return undefined; + if (k === 'length') return {length}; + throw new Error('element read'); + }}, has: function () {{ throw new Error('element checked'); }} }});" ); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7ebcacbbc2..5c083d7acd 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -157,7 +157,9 @@ pub(crate) struct WellKnown { pub(crate) has_instance: Sym, pub(crate) to_primitive: Sym, pub(crate) to_string_tag: Sym, - /// The five as values, for the collector. + pub(crate) unscopables: Sym, + pub(crate) is_concat_spreadable: Sym, + /// The Symbols as values, for the collector. values: Vec, } @@ -171,8 +173,14 @@ impl WellKnown { make("Symbol.toPrimitive"), make("Symbol.toStringTag"), ); - let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect(); - WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values } + let unscopables = make("Symbol.unscopables"); + let is_concat_spreadable = make("Symbol.isConcatSpreadable"); + let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag, &unscopables, &is_concat_spreadable] + .into_iter() + .cloned() + .map(Value::Symbol) + .collect(); + WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, unscopables, is_concat_spreadable, values } } } @@ -543,7 +551,7 @@ impl Interp { /// the heap for the list is checked first. A proxy's Symbols come from its `ownKeys` trap. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { if self.is_proxy(id) { - return Ok(self.proxy_own_keys(id)?.syms); + return Ok(self.proxy_own_keys(id, false)?.syms); } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; diff --git a/docs/mcp.md b/docs/mcp.md index 4e380d9057..2f3cddb74c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2882,6 +2882,8 @@ Existing globals with either name are preserved. If a missing global cannot be a is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)` and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object. +Typed-array `from` and `of` accept proxy constructors and run their `construct` traps. +A proxy constructor must return a typed array with at least the requested length; otherwise the method throws `TypeError`. `Reflect.construct` also accepts a distinct constructor as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object. `Map`, `Set`, `WeakMap` and `WeakSet` initialize iterable arguments through the requested prototype's @@ -2909,6 +2911,8 @@ and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before walking indices or allocating traversal keys. `concat` throws `TypeError` if the combined length exceeds the maximum safe integer. Reviver traversal keys count against the heap limit until their traversal frame is dropped. +`concat` reads `Symbol.isConcatSpreadable` through proxy `get` traps. A defined value controls whether the object +is spread; an undefined value uses the array check. In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating @@ -2918,6 +2922,7 @@ and symbol enumeration on a revoked proxy also throw `TypeError`. A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`, `defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation reaches the target. `Reflect`'s functions take Symbol keys too. +`Object.keys` and `Object.getOwnPropertyNames` keep the target's key order through empty-handler proxies. For an ordinary object, `Reflect.ownKeys` returns the string keys, then the Symbols in insertion order. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines its key order, with strings and Symbols mixed as the @@ -2932,6 +2937,9 @@ names are rejected; a later getter's exception takes precedence over the duplica Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay reachable during proxy callbacks, including callbacks that revoke a nested target proxy. +A `with` scope checks `Symbol.unscopables` after finding a property. If that lookup returns an object whose +property for the binding name is truthy, resolution continues in the outer scope. Each read calls a proxy's `get` trap +when its receiver is a proxy. `Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype without creating a property on the receiver; when that typed array is the receiver, the value is converted to a number first. `Object.freeze`, `Object.seal`, `Object.isFrozen` and `Object.isSealed` include a proxy's Symbol From 096b3b0e24f74ce3c551e9204d0e9158a0b57f6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:52:46 -0800 Subject: [PATCH 49/60] Scripts: a script chosen after the startup scripts may print to a printer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Run Startup Scripts on, File › Scripts runs the chosen script through script.startup.run, and only script.run listed the print service's printers, so app.printerList and Document.print to a printer threw "not available here" in the chosen script. script.startup.run now lists the printers, each queued run takes them as it starts, and a startup script's print jobs are asked about before the next run starts. Follows up on #9087. --- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/dialogs/script_run.rs | 16 +++-- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/print.rs | 14 +++-- crates/ui-egui/src/script_runs.rs | 17 ++++++ crates/ui-egui/src/tests/script_print.rs | 74 ++++++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 8 files changed, 121 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b87001e4b5..b8fb0fe84a 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -194,6 +194,7 @@ impl VectorcraftApp { titlebar_inset: 0.0, last_effect: None, last_pathfinder: None, + queued_script_printers: None, last_filters: Default::default(), character_focus: None, run_count: 0, @@ -524,6 +525,7 @@ impl VectorcraftApp { crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); if self.session.script_running() + && !crate::script_runs::waiting_for_print(self) && !self.session.script_waiting() && self.session.script_dialog().is_none() && self.session.script_picker().is_none() diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 22d999782c..ebd7fcb6de 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -41,8 +41,8 @@ //! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder. //! //! The jobs a script prepared for a printer (`Document.print` without a file) wait for the dialog of -//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no other -//! dialog is open and no text field or text being typed on the canvas has the keyboard. Its fields +//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no question +//! or popup is open and no text field or text being typed on the canvas has the keyboard. Its fields //! are `jobs` (each job's `document`, `printer` and `pages`, read from the jobs when it opens; no //! field sets them) and `answer`. Only the person at the keyboard prints them, with a click on its //! Print button or Space once Tab gave it the focus: the button takes no click for @@ -508,6 +508,11 @@ pub(crate) fn asking_to_close(app: &VectorcraftApp) -> bool { with_host(app, |host, _| host.is_open::()).unwrap_or(false) } +/// Whether the question before a script's print jobs are sent is open. +pub(crate) fn asking_to_print(app: &VectorcraftApp) -> bool { + with_host(app, |host, _| host.is_open::()).unwrap_or(false) +} + /// Whether a dialog is open or waits to open: a script's dialog opens only over nothing. pub(crate) fn busy(app: &VectorcraftApp) -> bool { app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false) @@ -991,10 +996,13 @@ fn choose(app: &mut VectorcraftApp) { pub(crate) const PRINT_ENABLE_DELAY_SECS: f64 = 1.0; /// Opens the question before the jobs a script prepared for a printer are sent, once the run has -/// ended, no other dialog is open and nothing is being typed: while a text field or text on the +/// ended, no question or popup is open and nothing is being typed: while a text field or text on the /// canvas has the keyboard it waits, and a later poll opens it. pub(crate) fn ask_print(app: &mut VectorcraftApp) { - if app.session.script_running() || !app.session.script_prints_waiting() || busy(app) { + // Between two queued runs, the jobs the ended run prepared are asked about before the next starts. + let between_runs = app.session.script_name().is_none(); + let blocked = app.asking_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false); + if (app.session.script_running() && !between_runs) || !app.session.script_prints_waiting() || blocked { return; } let typing = app.ui_ctx.as_ref().is_some_and(egui::Context::text_edit_focused) || app.session.tool_wants_text(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8a931c60b3..60e133e9f3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -164,6 +164,9 @@ pub struct VectorcraftApp { pub last_effect: Option<(String, serde_json::Value)>, /// Last successful destructive Pathfinder operation, repeated on the current selection. pub last_pathfinder: Option, + /// The printers listed when `script.startup.run` queued its runs: each queued run lists them + /// as it starts, without asking the print service again. + pub(crate) queued_script_printers: Option, /// The parameters each object filter plug-in last ran with (Object › Plug-ins › Apply Last Filter). pub last_filters: dialogs::plugin::LastFilters, /// The Character panel field that takes the keyboard focus when the panel next draws it diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 0451cb5b5c..0e10b1fbb7 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -171,14 +171,18 @@ pub fn script_printers(app: &mut VectorcraftApp) -> Option { Some(Printers::new(service.printers().into_iter().map(|p| (p.name, p.default)), for_printer)) } -/// Runs the engine command `id`. A `script.run` started here lists the printers it may print to -/// ([`script_printers`]), and only that run lists them. +/// Runs the engine command `id`. A `script.run` or `script.startup.run` started here lists the +/// printers its first run may print to ([`script_printers`]), and only that run lists them; the +/// runs `script.startup.run` queues list the same printers as they start +/// ([`crate::script_runs::poll`]). pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result { - if id == "script.run" { - app.session.script_printers = script_printers(app); - } + let listed = if matches!(id, "script.run" | "script.startup.run") { script_printers(app) } else { None }; + app.session.script_printers = listed.clone(); let r = app.session.execute(id, params).map_err(|e| e.to_string()); app.session.script_printers = None; + if id == "script.startup.run" && r.is_ok() { + app.queued_script_printers = listed.filter(|_| app.session.script_running()); + } r } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 16fff70c80..04c018ee76 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -12,6 +12,11 @@ use crate::VectorcraftApp; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; use crate::dialogs::script_window; +/// Between two queued runs, the next one waits until the last run's print jobs are approved or canceled. +pub(crate) fn waiting_for_print(app: &VectorcraftApp) -> bool { + app.session.script_name().is_none() && (app.session.script_prints_waiting() || script_run::asking_to_print(app)) +} + /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { startup_failures(app); @@ -27,10 +32,22 @@ pub fn poll(app: &mut VectorcraftApp) { if app.session.script_name().is_none() && (script_run::asking_to_close(app) || script_run::answer_close_between_runs(app)) { return; } + if waiting_for_print(app) { + return; + } let name = app.session.script_name().unwrap_or_default(); let startup = app.session.startup_script_running(); let shared = share_views(app); + // Between two queued runs, this pump starts the next one: it lists the printers listed when the + // runs were queued. + if app.session.script_name().is_none() { + app.session.script_printers = app.queued_script_printers.clone(); + } let pumped = app.session.script_pump(); + app.session.script_printers = None; + if !app.session.script_running() { + app.queued_script_printers = None; + } take_views(app, &shared); let Some(result) = pumped else { // A pump that started the next queued run shows the runs before it that could not start diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 46c6ccc867..865e0a0094 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -327,6 +327,80 @@ fn a_script_cannot_print_to_a_printer_without_a_service_that_allows_it() { assert!(app.session.script_printers.is_none()); } +/// With startup scripts on, the chosen script starts after them, in a later frame, and still lists +/// the service's printers: its job asks the person as it does without startup scripts. +#[test] +fn a_script_chosen_after_startup_scripts_may_print() { + let (mut app, sent, _) = print_app(true); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO)); + let dir = std::env::temp_dir().join(format!("vc-script-print-startup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.jsx"), "vc.log(1);").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + run(&mut app, PRINT_TO_LAB); + assert!(!app.ui.status.contains("not available here"), "{}", app.ui.status); + assert_eq!(objects(&app), 1, "the chosen script ran"); + assert!(asking(&app), "its job waits for the person"); + assert!(app.session.script_printers.is_none()); + assert!(sent.borrow().is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A startup script's jobs are asked about before the chosen script starts, so that script may +/// print too. +#[test] +fn a_startup_scripts_jobs_are_asked_about_before_the_chosen_script_starts() { + let (mut app, sent, _) = print_app(true); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO)); + let dir = std::env::temp_dir().join(format!("vc-script-print-startup-jobs-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.jsx"), "var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": PRINT_TO_LAB, "name": "p.js" })).unwrap().unwrap(); + script_run::with_host(&app, |host, _| host.open(script_run::RunQuestion(craft::ui::dialog::StandardPrompt::custom("Blocked")))).unwrap(); + for _ in 0..10_000 { + script_runs::poll(&mut app); + if app.session.script_prints_waiting() { + break; + } + } + assert!(app.session.script_prints_waiting()); + assert!(!asking(&app), "the print question waits for the other dialog"); + script_runs::poll(&mut app); + assert!(script_runs::waiting_for_print(&app)); + assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits under another dialog"); + assert_eq!(objects(&app), 0); + script_run::forget::(&app); + let ctx = app.ui_ctx.clone().unwrap(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let _ = craft::ui::dialog::JobProgress::new("Placing", "Reading").show(ui); + }); + out.textures_delta.clear(); + assert!(app.any_dialog_open()); + assert!(!app.asking_dialog_open()); + script_runs::poll(&mut app); + assert!(asking(&app), "the startup script's job is asked about"); + assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits"); + click_after_delay(&mut app, 10.0, "Print"); + assert_eq!(sent.borrow().iter().map(|(p, ..)| p.clone()).collect::>(), [Some("Office".to_string())]); + for _ in 0..10_000 { + script_runs::poll(&mut app); + if !app.session.script_running() { + break; + } + } + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 1, "the chosen script ran: {}", app.ui.status); + script_runs::poll(&mut app); + assert!(asking(&app), "the chosen script's job is asked about"); + assert!(app.queued_script_printers.is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Space on Print, once Tab gave it the keyboard focus after [`PRINT_ENABLE_DELAY_SECS`], prints: /// a keyboard user can approve the jobs without a mouse. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..1eb6ed2715 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4523,7 +4523,9 @@ disabled, truncated, unreadable}`, with `then` holding `script.run`'s reply. In reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, unreadable}`, with `failed` naming the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the -status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from +status bar. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel. +Each queued run lists the printers listed when the runs were queued. +Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from the prompt shown on quitting, between two runs, drops the runs not yet started, and the status bar says so. While that prompt is open, the next run does not start. Under `--automation-read-root` it reads the folder only when the folder lies inside a read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply, or its error when the chosen script cannot start, and add `startup` holding the `script.startup.run` reply. While a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a2d5bcd1..a356f947b9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1155,7 +1155,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `new ExternalObject("lib:AdobeXMPScript")` gives `XMPMeta`, `XMPFile` and `XMPConst` ([the help page](https://extendscript.docsforadobe.dev/scripting-xmp/xmpscript-object-reference/)): properties, arrays, language alternatives and namespaces read from a packet, changed and serialized, and a `.xmp` sidecar read and written with `getXMP`, `putXMP` and `closeFile`. VectorCraft's own rules: `XMPFile` reads and writes only where `File` may; other files are scanned for their packet and read only; a packet over 8 MiB or not well-formed throws; members not built yet (iterators, structure fields, qualifiers, aliases) throw that they are not available yet. `crates/js/src/xmp_tests.rs`, `crates/engine/src/tests/script_xmp.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - - Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/tests/safe_mode.rs`. + - Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel, and each queued run lists the printers listed when the runs were queued. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/src/tests/script_print.rs`, `crates/ui-egui/tests/safe_mode.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. - Plug-in run notices: a filter or plug-in command's output may report a `notice`, which needs no permission; once the output is applied, `plugin.run` and the command return it and the status bar shows it as `Plug-in “name”: notice`, escaped, cut at 200 characters and never translated, and a run that fails or is refused shows none. VectorCraft's own API and limits. Tests: `objects::tests::notice_is_escaped_capped_and_checked` in `vectorcraft-plugins`, `a_filter_s_notice_is_returned_once_its_output_is_applied` and `a_plugin_command_returns_its_run_s_notice` in `vectorcraft-engine`, `plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated` in `vectorcraft-ui-egui`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. From 39c0f35f22fc319c60406c254c200a1bacb413b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:31:20 -0800 Subject: [PATCH 50/60] Save: a checked save refuses a folder moved outside the write root A checked save (`write_atomic_checked`, used by the engine's file writes while automation write roots are set) opens the destination folder once and puts the file in place through that open folder. A folder moved after it was opened still received the file, so moving it out of the write root while the file was written placed the file outside the root. After the file is written, before it takes the old file's permissions and again right before it is renamed into place, the folder's current path is checked again with the same check. The copy fallback checks it before the target is opened and again before the target is created or overwritten. A folder moved outside the root, or one whose current path the system does not report (FreeBSD), is refused: the temporary file and any copy of the old content are removed, and the error names the original destination. A move within the root keeps working as before. Follows the checked-write work in 4cb6f8f152a and 6cf91458905. --- crates/format/src/atomic.rs | 378 +++++++++++++++++++++++++++++++++--- 1 file changed, 350 insertions(+), 28 deletions(-) diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index d759ff6d9f..dd0cd4cc6c 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -89,13 +89,15 @@ fn create_new(path: &Path) -> io::Result { /// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is /// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at /// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it; -/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by +/// a link put there later is replaced, never followed. A folder that moved after it was opened is +/// checked with `allowed` again at its new path right before the file is put in place, and a folder +/// whose new path the system does not report fails. Elsewhere this is `allowed(path)` followed by /// [`write_atomic_with`]. #[cfg(unix)] pub fn write_atomic_checked( path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>, - allowed: impl FnOnce(&Path) -> io::Result<()>, + allowed: impl Fn(&Path) -> io::Result<()>, ) -> io::Result<()> { use rustix::fs::{AtFlags, Mode, OFlags}; // A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name` @@ -126,6 +128,24 @@ pub fn write_atomic_checked( }; // The folder may have moved since it was opened: messages name it where it is now. let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file); + // Right before the file is put in place: a folder that moved since it was opened is checked + // again where it is now, so a move out of the allowed folders does not receive the file. + let still_allowed = || -> io::Result<()> { + let here = folder_now(&dir, &real); + let open = rustix::fs::fstat(&dir)?; + // The path itself, not a link that leads to the folder from elsewhere. + let same = |p: &Path| { + std::fs::canonicalize(p).is_ok_and(|c| c == p) && rustix::fs::stat(p).is_ok_and(|s| (s.st_dev, s.st_ino) == (open.st_dev, open.st_ino)) + }; + if here == real && same(&real) { + return Ok(()); + } + if here == real || !same(&here) { + return Err(io::Error::other(format!("{}: the folder moved while the file was written", target.display()))); + } + allowed(&here.join(stored_name(&dir, &here, &name))) + .map_err(|_| io::Error::other(format!("{}: the folder moved while the file was written", target.display()))) + }; let synced = || { // Opened for reading here: the folder handle above may allow name lookups only. let flushed = @@ -133,13 +153,21 @@ pub fn write_atomic_checked( flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) }; let open_target = |write: bool| -> io::Result { + // A missing target is created by `create_target`, after the last check. An existing one is + // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. + if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) { + return Err(io::ErrorKind::NotFound.into()); + } let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) }; + let create_target = || -> io::Result { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) }; match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { Ok(mut f) => { let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); - if let Err(e) = filled { + // Checked before the temporary file takes the old file's wider permissions, and again + // right before the rename. + if let Err(e) = filled.and_then(|()| still_allowed()) { drop(f); remove_tmp(); return Err(e); @@ -151,6 +179,10 @@ pub fn write_atomic_checked( let _ = keep_permissions_at(&dir, &name, &old, &f); } drop(f); + if let Err(e) = still_allowed() { + remove_tmp(); + return Err(e); + } #[cfg(test)] let refuse = RENAME_REFUSED.with(std::cell::Cell::get); #[cfg(not(test))] @@ -189,7 +221,9 @@ pub fn write_atomic_checked( }, remove_tmp: &remove_tmp, open_target: &open_target, + create_target: &create_target, synced: &synced, + still_allowed: &still_allowed, }; write_over_in(&over, refused.into()) } @@ -207,7 +241,7 @@ pub fn write_atomic_checked( // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&elsewhere); }; - if let Err(e) = filled { + if let Err(e) = filled.and_then(|()| still_allowed()) { remove(); return Err(e); } @@ -222,7 +256,9 @@ pub fn write_atomic_checked( open_tmp: &|| File::open(&elsewhere), remove_tmp: &remove, open_target: &open_target, + create_target: &create_target, synced: &synced, + still_allowed: &still_allowed, }; write_over_in(&over, refused.into()) } @@ -422,7 +458,10 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { let _ = std::fs::remove_file(tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, + #[cfg(unix)] + create_target: &|| create_new(target), synced: &|| sync_written_parent(target), + still_allowed: &|| Ok(()), }; write_over_in(&over, refused) } @@ -441,38 +480,92 @@ struct Over<'a> { open_tmp: &'a dyn Fn() -> io::Result, /// Best effort. remove_tmp: &'a dyn Fn(), - /// The target for writing (created when missing, not truncated) when `true`, for reading when - /// `false`. + /// Opens the target without truncating it for writing when `true`, or for reading when `false`. + /// Checked Unix writes defer creation of a missing target to `create_target`. open_target: &'a dyn Fn(bool) -> io::Result, + /// Creates a missing target after the final check and fails if its name is taken. + #[cfg(unix)] + create_target: &'a dyn Fn() -> io::Result, /// The target's folder flushed, after the target is written. synced: &'a dyn Fn() -> io::Result<()>, + /// Asked right before the target is overwritten: an error leaves it as it was. + still_allowed: &'a dyn Fn() -> io::Result<()>, } /// [`write_over`] through `over`. fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { - let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?))); - let Ok((mut from, mut to)) = opened else { + // Checked Unix writes create a missing target only after the final check. + if let Err(e) = (over.still_allowed)() { + (over.remove_tmp)(); + return Err(e); + } + let opened = (over.open_tmp)().and_then(|from| { + let to = match (over.open_target)(true) { + Ok(to) => Some(to), + #[cfg(unix)] + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => return Err(e), + }; + Ok((from, to)) + }); + let Ok((mut from, to)) = opened else { // Best effort: the temporary file is all there is to clean up. (over.remove_tmp)(); return Err(refused); }; // Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes // into: one put at its name meanwhile is not copied in its place. - let kept = to.metadata().map_or(true, |m| m.len() > 0); + let kept = to.as_ref().is_some_and(|to| to.metadata().map_or(true, |m| m.len() > 0)); if kept && let Err(e) = (over.open_target)(false).and_then(|mut target| { - if !same_file(&target, &to) { + if !to.as_ref().is_some_and(|to| same_file(&target, to)) { return Err(io::Error::other("the file was replaced while it was opened")); } keep_old(&mut target, over) }) { + #[cfg(unix)] + if let Err(e) = (over.still_allowed)() { + drop((from, to)); + (over.remove_tmp)(); + return Err(e); + } let why = format!( "{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", (over.tmp)().display() ); return Err(io::Error::new(refused.kind(), RecoveryError(why))); } + if let Err(e) = (over.still_allowed)() { + // Nothing was overwritten: neither copy is needed. + drop((from, to)); + (over.remove_tmp)(); + if kept { + (over.remove_old)(); + } + return Err(e); + } + let mut to = match to { + Some(to) => to, + #[cfg(unix)] + None => match (over.create_target)() { + Ok(to) => to, + // A file put at the name meanwhile is left alone, and reported as there. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + (over.remove_tmp)(); + return Err(e); + } + Err(_) => { + (over.remove_tmp)(); + return Err(refused); + } + }, + #[cfg(not(unix))] + None => { + (over.remove_tmp)(); + return Err(refused); + } + }; let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); match (copied, kept) { @@ -826,8 +919,18 @@ mod tests { (d, root, outside) } + /// Whether this system says where an open folder is now: macOS always, Linux and Android through + /// `/proc/self/fd`, which a chroot may lack. Decided without `folder_now`. #[cfg(unix)] - fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ { + fn reports_open_folder_paths() -> bool { + if cfg!(target_vendor = "apple") { + return true; + } + cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/proc/self/fd").is_dir() + } + + #[cfg(unix)] + fn under(root: &Path) -> impl Fn(&Path) -> io::Result<()> + '_ { move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) } } @@ -851,22 +954,51 @@ mod tests { #[test] fn a_checked_write_stays_in_the_folder_it_opened() { let (d, root, outside) = checked_folders("checked-after"); - let check = under(&root); let r = write_atomic_checked( &root.join("inside/doc.txt"), - |f| f.write_all(b"new"), - |p| { - check(p)?; + |f| { std::fs::rename(root.join("inside"), root.join("moved"))?; - std::os::unix::fs::symlink(&outside, root.join("inside")) + std::os::unix::fs::symlink(&outside, root.join("inside"))?; + f.write_all(b"new") }, + under(&root), ); + if !reports_open_folder_paths() { + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the folder moved")), "{r:?}"); + assert!(!outside.join("doc.txt").exists() && !root.join("moved/doc.txt").exists()); + assert!(std::fs::read_dir(root.join("moved")).unwrap().next().is_none()); + let _ = std::fs::remove_dir_all(d); + return; + } r.unwrap(); assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder"); assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new"); let _ = std::fs::remove_dir_all(d); } + /// A folder moved out of the allowed root while the file is written receives nothing: the move is + /// caught before the file is put in place, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_folder_moved_outside_while_it_fills() { + let (d, root, outside) = checked_folders("checked-moved-out"); + let r = write_atomic_checked( + &root.join("inside/doc.txt"), + |f| { + f.write_all(b"new")?; + std::fs::rename(root.join("inside"), outside.join("inside")) + }, + under(&root), + ); + assert!(r.as_ref().is_err_and(|e| !read_only_location(e)), "{r:?}"); + let message = r.unwrap_err().to_string(); + assert!(message.contains(&root.join("inside/doc.txt").display().to_string()), "{message}"); + assert!(message.contains("the folder moved"), "{message}"); + assert!(!message.contains(&outside.display().to_string()), "{message}"); + assert!(std::fs::read_dir(outside.join("inside")).unwrap().next().is_none(), "nothing is left outside"); + let _ = std::fs::remove_dir_all(d); + } + /// A link put at the file's name after the check is replaced by the file, not followed. #[cfg(unix)] #[test] @@ -922,31 +1054,34 @@ mod tests { let _ = std::fs::remove_dir_all(d); } - /// A checked write whose folder moved after it was opened, refused the rename, and failed to - /// copy into the file: the temporary file and the copy of the old content stay in that folder, - /// and the error names them where they are now. (FreeBSD does not say where an open folder is - /// now: there the error names them where the folder was opened.) + /// A failed fallback names the recovery files in the folder's current location when available. + /// A move is refused when the system cannot resolve the open folder's current path. #[cfg(unix)] #[test] fn a_checked_write_names_the_kept_file_where_its_folder_moved() { let (d, root, _) = checked_folders("checked-moved"); std::fs::write(root.join("inside/doc.txt"), b"original").unwrap(); - let check = under(&root); let r = write_atomic_checked( &root.join("inside/doc.txt"), - |f| f.write_all(b"new"), - |p| { - check(p)?; + |f| { std::fs::rename(root.join("inside"), root.join("moved"))?; RENAME_REFUSED.with(|c| c.set(true)); // The temporary file's flush and the copy of the old content work, the next doesn't. FLUSHES_LEFT.with(|c| c.set(Some(2))); - Ok(()) + f.write_all(b"new") }, + under(&root), ); RENAME_REFUSED.with(|c| c.set(false)); FLUSHES_LEFT.with(|c| c.set(None)); let message = r.unwrap_err().to_string(); + if !reports_open_folder_paths() { + assert!(message.contains("the folder moved"), "{message}"); + assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(root.join("moved")).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + return; + } let kept = |ext: &str| -> PathBuf { let found: Vec<_> = std::fs::read_dir(root.join("moved")) .unwrap() @@ -958,15 +1093,200 @@ mod tests { }; let (tmp, old) = (kept("tmp"), kept("old")); assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec())); - let named_in = - if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") }; for file in [&tmp, &old] { - let named = named_in.join(file.file_name().unwrap()); + let named = root.join("moved").join(file.file_name().unwrap()); assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display()); } let _ = std::fs::remove_dir_all(d); } + /// A refused rename whose folder is no longer allowed by the time the file would be overwritten + /// leaves the file as it was, and neither copy stays behind. + #[test] + fn a_refused_rename_does_not_overwrite_once_no_longer_allowed() { + let d = dir("no-rename-disallowed"); + let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old")); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + #[cfg(unix)] + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + Ok(()) + } else { + assert_eq!(std::fs::read(&old).unwrap(), b"original"); + Err(io::Error::other("moved outside")) + } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + assert!(!tmp.exists() && !old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A backup failure after a folder moves outside removes the new content and reports the refusal. + #[cfg(unix)] + #[test] + fn a_refused_rename_rechecks_authorization_after_a_backup_error() { + let (d, root, outside) = checked_folders("no-rename-backup-moved"); + let inside = root.join("inside"); + let moved = outside.join("inside"); + let path = inside.join("doc.txt"); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(inside.join("doc.tmp"), b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| moved.join("doc.tmp"), + create_old: &|| { + std::fs::rename(&inside, &moved)?; + Err(io::Error::other("backup failed")) + }, + old: &|| moved.join("doc.old"), + remove_old: &|| {}, + open_tmp: &|| File::open(inside.join("doc.tmp")), + remove_tmp: &|| { + let _ = std::fs::remove_file(moved.join("doc.tmp")); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if inside.exists() { Ok(()) } else { Err(io::Error::other("moved outside")) } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!e.to_string().contains(&outside.display().to_string()), "{e}"); + assert!(!e.get_ref().is_some_and(|e| e.is::())); + assert_eq!(std::fs::read(moved.join("doc.txt")).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(&moved).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + } + + /// A refused fallback leaves a missing target absent when the final check fails. + #[cfg(unix)] + #[test] + fn a_refused_rename_leaves_a_missing_target_absent_once_no_longer_allowed() { + let d = dir("no-rename-disallowed-new"); + let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let created = std::cell::Cell::new(false); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| { + if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) } + }, + create_target: &|| { + created.set(true); + create_new(&path) + }, + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + assert!(!path.exists()); + Ok(()) + } else { + assert!(!created.get() && !path.exists()); + Err(io::Error::other("moved outside")) + } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!created.get()); + assert!(!path.exists()); + assert!(!tmp.exists() && !old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked fallback creates a missing target after authorization succeeds. + #[cfg(unix)] + #[test] + fn a_checked_write_creates_a_missing_target_when_the_rename_is_refused() { + let (d, root, _) = checked_folders("checked-new-no-rename"); + let path = root.join("inside/doc.txt"); + RENAME_REFUSED.with(|c| c.set(true)); + let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + r.unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert_eq!(std::fs::read_dir(root.join("inside")).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(d); + } + + /// A file created by another writer at the final check is preserved whether that check succeeds or fails. + #[cfg(unix)] + #[test] + fn a_refused_rename_preserves_a_target_created_at_the_final_check() { + for allowed in [false, true] { + let d = dir("no-rename-new-target-taken"); + let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| Err(io::Error::other("no backup expected")), + old: &|| d.join("doc.old"), + remove_old: &|| {}, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, + create_target: &|| create_new(&path), + synced: &|| Ok(()), + still_allowed: &|| { + checks.set(checks.get() + 1); + if checks.get() == 1 { + return Ok(()); + } + std::fs::write(&path, b"someone else's")?; + if allowed { Ok(()) } else { Err(io::Error::other("moved outside")) } + }, + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert_eq!(checks.get(), 2); + if !allowed { + assert!(e.to_string().contains("moved outside"), "{e}"); + } + assert_eq!(std::fs::read(&path).unwrap(), b"someone else's"); + assert!(!tmp.exists() && !d.join("doc.old").exists()); + let _ = std::fs::remove_dir_all(d); + } + } + /// A refused rename copies the old content through the file handle it then overwrites: when a /// different file is at the name by the time it is opened for reading, nothing is overwritten and /// the new content stays in the temporary file. @@ -991,7 +1311,9 @@ mod tests { let _ = std::fs::remove_file(&tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) }, + create_target: &|| create_new(&path), synced: &|| Ok(()), + still_allowed: &|| Ok(()), }; let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}"); From 806aec918a9425353fa3cb0689bf9d138cf945c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:11:24 -0800 Subject: [PATCH 51/60] xtask: test-lint census rule counts a computation only where it runs on the entry The census rule leaves out a loop that feeds each entry into a computation. It now checks that the computation runs, and that it runs on the entry: - An alias assigned another value no longer holds the entry, and one assigned the entry holds it. Assignments in an empty loop, an async block, a move closure or a closure the loop never calls do not change the alias, and one that may be skipped does not make one. - A nested for body counts only when its source is a literal range or array that is not empty. - A block in an earlier argument keeps the enclosing || or && that can skip the call. - Calling an async closure counts only when the future is awaited or passed to block_on. - A closure that is not bound with let counts only when it is called where it is written; a parenthesized initializer binds the closure. - A closure call resolves to the binding in scope at the call, so a later let of the same name takes it. - A conjunction inside a parenthesized operand of an asserted && is required, unless an || at its level can bypass it. --- xtask/src/test_lint.rs | 557 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 495 insertions(+), 62 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 44d73697e2..19c8bf3c8d 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1739,10 +1739,14 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let mut derived: Vec<(String, usize, usize)> = pattern_names(pattern).map(|n| (n, from, to)).collect(); // Where a binding does not read the entry, the name holds another value until its scope ends. let mut shadows: Vec<(String, usize, usize)> = vec![]; + let mut empty_bodies = vec![]; for at in words(b, b"for", from, to) { let Some(&kw) = words(b, b"in", at + 3, to).first() else { continue }; let Some(open) = loop_open(b, kw + 2, to) else { continue }; let Some(close) = matching(b, open).filter(|&c| c < to) else { continue }; + if literal_source_yields(&b[at..open]) == Some(false) { + empty_bodies.push((open, close)); + } shadows.extend(pattern_names(&String::from_utf8_lossy(&b[at + 3..kw])).map(|n| (n, open + 1, close))); } // Simple closure parameters shadow captures in both block and expression bodies. @@ -1776,6 +1780,9 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); } + // The scopes of nested loop patterns and closure parameters, where an assignment to the name + // changes that binding and not the entry. + let nested_bindings = shadows.clone(); // A field access (`options.c`), a path segment (`defaults::c`) or a field label (`Row { c: x }`) // names a field or an item, not the binding. let is_field = |at: usize, len: usize| { @@ -1791,32 +1798,91 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { .any(|at| !is_field(at, n.len()) && !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z)) }) }; - // Names bound inside the loop from the entry count as the entry. - for at in words(b, b"let", from, to) { - let Some(eq) = - (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) - else { + let let_eq = |at: usize| { + (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + }; + // An assignment that starts a statement (`input = fallback();`) changes what the name holds + // until the end of the block that declares it. + let assignments: Vec<(usize, usize)> = (from + 1..to) + .filter(|&i| { + b[i] == b'=' + && !matches!(b.get(i + 1), Some(b'=' | b'>')) + && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>' | b'+' | b'-' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^') + }) + .filter_map(|eq| { + let name_end = from + b[from..eq].trim_ascii_end().len(); + let mut at = name_end; + while at > from && is_ident(b[at - 1]) { + at -= 1; + } + let before = b[from..at].trim_ascii_end(); + (at < name_end && !b[at].is_ascii_digit() && (before.is_empty() || matches!(before.last(), Some(b';' | b'{' | b'}')))).then_some((at, eq)) + }) + .collect(); + // Where the value of the initializer or assigned value after the `=` at `eq` starts. A block + // gives the value of its tail (`{ prepare(); c }`). + let value_start = |eq: usize, end: usize| { + let init = skip_ws(b, eq + 1); + let Some(close) = matching(b, init).filter(|&close| b[init] == b'{' && b[close + 1..end].trim_ascii().is_empty()) else { return eq + 1 }; + let mut i = init + 1; + let mut value = i; + while i < close { + match b[i] { + b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close), + b';' => value = i + 1, + _ => {} + } + i += 1; + } + value + }; + let mut steps: Vec<(usize, Option)> = words(b, b"let", from, to).into_iter().map(|at| (at, None)).collect(); + steps.extend(assignments.into_iter().map(|(at, eq)| (at, Some(eq)))); + steps.sort_unstable(); + // Names bound or assigned inside the loop from the entry count as the entry. + for (at, assigned) in steps { + if let Some(eq) = assigned { + let name = String::from_utf8_lossy(b[at..eq].trim_ascii_end()).into_owned(); + let end = statement_end(&b[..to], eq); + let until = words(b, b"let", from, at) + .into_iter() + .filter(|&l| block_close(b, l) > at) + .filter(|&l| let_eq(l).is_some_and(|e| pattern_names(&String::from_utf8_lossy(&b[l + 3..e])).any(|n| n == name))) + .map(|l| (l, block_close(b, l).min(to))) + .chain( + nested_bindings + .iter() + .filter(|(n, since, until)| *n == name && *since <= at && at < *until) + .map(|(_, since, until)| (*since, *until)), + ) + .max_by_key(|&(since, _)| since) + .map_or(to, |(_, until)| until); + // Assignments in move closures leave outer bindings unchanged. Assignments in async + // blocks or uncalled closures do not run; conditional assignments do not make aliases. + if in_move_closure(b, from, to, at) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { + continue; + } + if live(value_start(eq, end), end, &derived, &shadows) { + if !runs_with_assertion(b, from, to, at) { + continue; + } + // Assigning the entry again ends what earlier assignments in the same scope stored. + for s in shadows.iter_mut().filter(|s| s.0 == name && s.1 <= at && at < s.2 && s.2 == until) { + s.2 = end; + } + derived.push((name, end, until)); + } else if derived.iter().any(|(d, _, _)| *d == name) && !empty_bodies.iter().any(|&(open, close)| open < at && at < close) { + shadows.push((name, end, until)); + } + continue; + } + let Some(eq) = let_eq(at) else { continue; }; // `if let` and `while let` end their initializer at the conditional's block. let conditional = [b"if".as_slice(), b"while"].iter().any(|kw| b[from..at].trim_ascii_end().ends_with(kw)); let end = if conditional { (eq..to).find(|&i| b[i] == b'{').unwrap_or(to) } else { statement_end(&b[..to], eq) }; - // A block initializer binds the value of its tail (`{ prepare(); c }`). - let mut value = eq + 1; - let init = skip_ws(b, value); - if !conditional && b.get(init) == Some(&b'{') && matching(b, init).is_some_and(|close| b[close + 1..end].trim_ascii().is_empty()) { - let close = matching(b, init).unwrap_or(end); - let mut i = init + 1; - value = i; - while i < close { - match b[i] { - b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close), - b';' => value = i + 1, - _ => {} - } - i += 1; - } - } + let value = if conditional { eq + 1 } else { value_start(eq, end) }; let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); if live(value, end, &derived, &shadows) { // Rebinding from the entry suspends earlier shadows until this block ends. @@ -1966,6 +2032,42 @@ fn numeric_literal(s: &str) -> bool { matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") } +/// The value of a decimal integer literal such as `3`, `-4`, `1_000` or `2u8`. +fn integer_literal(s: &str) -> Option { + let (sign, digits) = s.strip_prefix('-').map_or((1, s), |rest| (-1, rest)); + let body = ["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"] + .iter() + .find_map(|suffix| digits.strip_suffix(suffix)) + .unwrap_or(digits); + if !numeric_literal(digits) || !body.bytes().all(|c| c.is_ascii_digit() || c == b'_') { + return None; + } + body.replace('_', "").parse::().ok().map(|n| sign * n) +} + +/// Whether the source of the `for … in ` head `head` yields at least one item, for an +/// integer range with literal bounds (`0..3` and `0..=0` do, `0..0` and `5..=4` do not) or an array +/// literal (`[a, b]` and `[x; 2]` do, `[]` and `[x; 0]` do not). `None` for any other source. +fn literal_source_yields(head: &[u8]) -> Option { + let &kw = words(head, b"in", 3, head.len()).first()?; + let mut source: String = String::from_utf8_lossy(&head[kw + 2..]).chars().filter(|c| !c.is_whitespace()).collect(); + while source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { + source = source[1..source.len() - 1].to_owned(); + } + if source.starts_with('[') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { + let items = &source[1..source.len() - 1]; + return match top_level_at(items, ";").first() { + Some(&semi) => integer_literal(&items[semi + 1..]).map(|n| n > 0), + None => Some(!items.is_empty()), + }; + } + if let Some((low, high)) = source.split_once("..=") { + return integer_literal(low).zip(integer_literal(high)).map(|(low, high)| low <= high); + } + let (low, high) = source.split_once("..")?; + integer_literal(low).zip(integer_literal(high)).map(|(low, high)| low < high) +} + /// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the /// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { @@ -2008,7 +2110,8 @@ fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { /// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`, /// also with a block as the right operand); the right side of `&&` has to run only in an asserted /// condition. A call inside a closure bound with `let` runs only when the loop calls -/// that closure. +/// that closure ([`closure_calls`]), and a call in a closure that is not bound does not count. A call +/// in a nested `for` body counts only when the loop's source yields an item ([`literal_source_yields`]). fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { runs_with_assertion_within(b, from, to, start, &[]) } @@ -2043,12 +2146,16 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } } let prefix = b[head..open].trim_ascii(); + let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active) { return false; } + } else if nested_for && literal_source_yields(prefix) != Some(true) { + // A nested `for` body runs only when its source yields an item. + return false; } else if !prefix.ends_with(b"|") - && !(prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace)) + && !nested_for && (prefix.ends_with(b"=>") || [b"async".as_slice(), b"async move"] .iter() @@ -2057,8 +2164,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac || (!words(prefix, b"loop", 0, prefix.len()).is_empty() && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) { - // A nested `for` body is taken to run, like the loop body itself; [`feeds_entry`] keeps - // its own bindings apart. + // A nested `for` body whose source yields an item runs, like the loop body itself; + // [`feeds_entry`] keeps its own bindings apart. return false; } } @@ -2066,8 +2173,13 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac // the operand of `||` or `&&`. let mut stmt = from; let mut braces = 0usize; + // The parenthesis or bracket that most closely encloses the call: a block after it is an + // earlier argument or element (`accept({ 0 }, app.run(c))`), not an earlier statement. + let group = (from..start).rev().find(|&i| matches!(b[i], b'(' | b'[' | b'{') && matching(b, i).is_none_or(|close| start < close)); + let group = group.filter(|&i| b[i] != b'{'); for i in (from..start).rev() { match b[i] { + b'}' if braces == 0 && group.is_some_and(|g| g < i) => braces += 1, // A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`) // unless an operator joins the call's expression to it. b'}' if braces == 0 && { @@ -2103,8 +2215,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b[pipe] != b'|' { return None; } - let head = b[stmt..pipe].trim_ascii(); - let head = head.strip_suffix(b"move").or_else(|| head.strip_suffix(b"async")).unwrap_or(head).trim_ascii_end(); + let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); + let head = strip_closure_keywords(&head).0.as_bytes(); if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { return None; } @@ -2155,42 +2267,162 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac closure = Some(stmt + prefix.len()); } } - // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. + // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. A closure + // that is not bound with `let` (`Some(|| app.run(c))`) shows no call of it. let Some(end) = closure else { return true }; let head = String::from_utf8_lossy(&b[stmt..end]); - let head = head.trim(); - let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); - let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true }; - let Some(name) = pattern_names(binding).last() else { return true }; - words(b, name.as_bytes(), end, to).into_iter().any(|at| { - // `other.run()` calls a method, not the closure. - b[..at].trim_ascii_end().last() != Some(&b'.') - && b.get(skip_ws(b, at + name.len())) == Some(&b'(') - && runs_with_assertion_within(b, from, to, at, &active) - }) + let (bare, asynchronous) = strip_closure_keywords(head.trim_end()); + // Unwrap parentheses whose outer closing parenthesis ends the initializer. + let unwrapped = (|| { + let mut head = bare; + let mut inner_close = None; + while let Some(prefix) = head.strip_suffix('(') { + let close = matching(b, stmt + prefix.len())?; + if close < start || inner_close.is_some_and(|inner| !b[inner + 1..close].trim_ascii().is_empty()) { + return None; + } + inner_close = Some(close); + head = prefix.trim_end(); + } + inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) + })(); + let binding_head = unwrapped.unwrap_or(bare); + let Some(binding) = + binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) + else { + // `(|| app.run(c))()` calls the closure where it is written. + let open = stmt + bare.len(); + let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return false }; + let call = skip_ws(b, close + 1); + if b.get(call) != Some(&b'(') { + return false; + } + if !asynchronous { + return true; + } + let next = matching(b, call).map_or(b.len(), |c| skip_ws(b, c + 1)); + return b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); + }; + let Some(name) = pattern_names(binding).last() else { return false }; + closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, &active)) +} + +/// The head before a closure's parameters with a trailing `move` and `async` removed, and whether +/// the closure is async. +fn strip_closure_keywords(head: &str) -> (&str, bool) { + fn keyword<'a>(h: &'a str, kw: &str) -> Option<&'a str> { + h.strip_suffix(kw).filter(|rest| !rest.ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_')).map(str::trim_end) + } + let head = head.trim_end(); + let head = keyword(head, "move").unwrap_or(head); + match keyword(head, "async") { + Some(head) => (head, true), + None => (head, false), + } +} + +/// Where `b[after..to]` calls the closure that the `let` at `bound` binds to `name`: `name(…)`, not +/// a method (`other.run()`), and not after a later `let` of the same name that is still in scope. +/// Calling an async closure only makes a future, so its call counts only when the future is +/// awaited (`run().await`) or passed to `block_on`. +fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, asynchronous: bool) -> Vec { + let rebinds = |l: usize, at: usize| { + let eq = (l + 3..at).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')); + // The new name is in scope from the end of its statement (`let run = run();` still calls the + // earlier closure) to the end of its block. + block_close(b, l) > at + && eq.is_some_and(|eq| statement_end(&b[..to], eq) < at && pattern_names(&String::from_utf8_lossy(&b[l + 3..eq])).any(|n| n == name)) + }; + words(b, name.as_bytes(), after, to) + .into_iter() + .filter(|&at| { + let open = skip_ws(b, at + name.len()); + if b[..at].trim_ascii_end().last() == Some(&b'.') || b.get(open) != Some(&b'(') { + return false; + } + if words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { + return false; + } + if !asynchronous { + return true; + } + let Some(close) = matching(b, open) else { return false }; + let next = skip_ws(b, close + 1); + let awaited = b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); + awaited || b[..at].trim_ascii_end().ends_with(b"block_on(") + }) + .collect() } /// Whether an `&&` is at the top level of an assertion's first argument. fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool { macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| { - let Some(&(mut f, mut t)) = a.args.first() else { return false }; - loop { - f += b[f..t].len() - b[f..t].trim_ascii_start().len(); - t = f + b[f..t].trim_ascii_end().len(); - if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) { - break; - } - f += 1; - t -= 1; - } - // A top-level `||` lets the assertion pass without the conjunction. - let cond = String::from_utf8_lossy(&b[f..t]); - f <= at && at < t && top_level_at(&cond, "||").is_empty() && top_level_at(&cond, "&&").contains(&(at - f)) + let Some(&(f, t)) = a.args.first() else { return false }; + required_conjunction(b, f, t, at, 0) }) } -/// Whether `start` lies in the block body of a closure bound with `let` in -/// `b[from..to]` (`let run = || { … };`, also `move` or `async`) that the loop never calls. +/// Whether the `&&` at `at` has to hold for the condition `b[f..t]` to hold: it joins the +/// condition's top-level operands, or those of a parenthesized operand of a top-level `&&` +/// (`(a && b) && c`). An `||` at the same level lets the condition hold without it. +fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: usize) -> bool { + loop { + f += b[f..t].len() - b[f..t].trim_ascii_start().len(); + t = f + b[f..t].trim_ascii_end().len(); + if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) { + break; + } + f += 1; + t -= 1; + } + let cond = String::from_utf8_lossy(&b[f..t]); + if depth > 64 || at < f || t <= at || !top_level_at(&cond, "||").is_empty() { + return false; + } + let ands = top_level_at(&cond, "&&"); + if ands.contains(&(at - f)) { + return true; + } + // The operand that holds `at`, when it is a parenthesized group. + let start = ands.iter().rev().map(|&a| f + a + 2).find(|&s| s <= at).unwrap_or(f); + let end = ands.iter().map(|&a| f + a).find(|&e| e > at).unwrap_or(t); + let open = skip_ws(b, start); + let close = start + b[start..end].trim_ascii_end().len(); + b.get(open) == Some(&b'(') && matching(b, open) == close.checked_sub(1) && required_conjunction(b, open, close, at, depth + 1) +} + +/// Whether `start` lies in the body of an `async` or `async move` block. +fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { + (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { + let head = b[from..open].trim_ascii_end(); + let head = head.strip_suffix(b"move").filter(|h| h.last().is_some_and(u8::is_ascii_whitespace)).unwrap_or(head).trim_ascii_end(); + head.strip_suffix(b"async").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + }) +} + +/// Whether `start` lies in the block or expression body of a move closure. +fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { + words(b, b"move", from, start).into_iter().any(|at| { + let pipe = skip_ws(b, at + 4); + if b.get(pipe) != Some(&b'|') { + return false; + } + let Some(end) = (pipe + 1..to).find(|&i| b[i] == b'|') else { return false }; + let body = skip_ws(b, end + 1); + let mut until = body; + if b.get(body) == Some(&b'{') { + until = matching(b, body).unwrap_or(to).min(to); + } else { + while until < to && !matches!(b[until], b',' | b';' | b')' | b']' | b'}') { + until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 }; + } + } + body <= start && start < until + }) +} + +/// Whether `start` lies in the block body of a closure bound with `let` in `b[from..to]` +/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds. fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { let mut depth = 0usize; for i in (from..start).rev() { @@ -2201,18 +2433,14 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & b'{' => { let Some(params) = b[from..i].trim_ascii_end().strip_suffix(b"|") else { continue }; let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; - let head = params[..pipe].trim_ascii_end(); - let head = String::from_utf8_lossy(head); - let head = head.trim_end(); - let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); + let (head, asynchronous) = strip_closure_keywords(&text); let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue }; let Some(name) = pattern_names(binding).last() else { continue }; + let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); let close = matching(b, i).unwrap_or(to); - if !words(b, name.as_bytes(), close, to).into_iter().any(|at| { - b[..at].trim_ascii_end().last() != Some(&b'.') - && b.get(skip_ws(b, at + name.len())) == Some(&b'(') - && runs_with_assertion_within(b, from, to, at, active) - }) { + if !closure_calls(b, &name, bound, close, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, active)) + { return true; } } @@ -8937,6 +9165,211 @@ mod tests { ); } + #[test] + fn census_follows_assignments_to_entry_aliases() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let mut input = c; input = fallback(); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an alias assigned another value no longer holds the entry" + ); + assert_eq!( + census("let mut input = c; { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a block outlasts the block" + ); + assert_eq!( + census("for mut c in [fallback()] { c = fallback(); } app.run(c); assert!(menu(c).is_some());"), + [], + "an assignment to a nested loop binding ends with its scope" + ); + assert_eq!( + census("let run = |mut c: Command| { c = fallback(); app.run(c) }; run(default()); app.run(c); assert!(menu(c).is_some());"), + [], + "an assignment to a closure parameter ends with its scope" + ); + assert_eq!( + census("let mut input = c; for _ in 0..0 { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an empty range does not end an alias" + ); + assert_eq!( + census("let mut input = c; for _ in 5..=4 { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an empty inclusive range does not end an alias" + ); + assert_eq!( + census("let mut input = c; for _ in [x; 0] { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an array repeated zero times does not end an alias" + ); + assert_eq!( + census("let mut input = c; for x in xs { input = fallback(); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a loop over an unknown source may end an alias" + ); + assert_eq!( + census("let mut input = c; input = fallback(); input = c; app.run(input); assert!(menu(c).is_some());"), + [], + "an alias assigned the entry again holds it" + ); + assert_eq!( + census("let mut input = fallback(); input = c; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment from the entry makes an alias" + ); + assert_eq!( + census("let mut input = fallback(); input = { menu(c); fallback() }; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assigned block gives the value of its tail" + ); + assert_eq!( + census("let mut input = fallback(); let _saved = || { input = c; }; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in an uncalled closure does not make an alias" + ); + assert_eq!( + census("let mut input = c; let _saved = || { input = fallback(); }; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an uncalled closure does not end an alias" + ); + assert_eq!( + census("let mut input = c; { let _future = async { input = fallback(); }; } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an unpolled async block does not end an alias" + ); + assert_eq!( + census("let mut input = c; let _future = async move { input = fallback(); }; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in an unpolled async move block does not end an alias" + ); + assert_eq!( + census("let mut input = fallback(); if ready { input = c; } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment that may be skipped does not make an alias" + ); + assert_eq!( + census("let mut input = c; let mut run = move || { input = fallback(); }; run(); app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment to a move capture leaves the outer alias unchanged" + ); + } + + #[test] + fn census_needs_evidence_that_the_call_runs_on_the_entry() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an empty range never runs its body"); + assert_eq!(census("for x in xs { app.run(c, x); } assert!(menu(c).is_some());"), [(2, "census")], "a source that may be empty"); + assert_eq!(census("for x in 0..=0 { app.run(c, x); } assert!(menu(c).is_some());"), [], "an inclusive range with one value runs"); + assert_eq!(census("for x in [1, 2] { app.run(c, x); } assert!(menu(c).is_some());"), [], "a nonempty array literal runs"); + assert_eq!( + census("let _ = ready || accept({ 0 }, app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a block in an earlier argument keeps the enclosing ||" + ); + assert_eq!( + census("let _ = accept({ 0 }, app.run(c)); assert!(menu(c).is_some());"), + [], + "a block in an earlier argument does not skip the call" + ); + } + + #[test] + fn census_needs_evidence_that_a_closure_or_conjunction_runs_the_call() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let run = async || app.run(c); let _future = run(); assert!(menu(c).is_some());"), + [(2, "census")], + "calling an async closure only makes a future" + ); + assert_eq!( + census("let run = async move || app.run(c); let _future = run(); assert!(menu(c).is_some());"), + [(2, "census")], + "calling an async move closure only makes a future" + ); + assert_eq!( + census("let run = async || { app.run(c) }; let _future = run(); assert!(menu(c).is_some());"), + [(2, "census")], + "calling a block-bodied async closure only makes a future" + ); + assert_eq!(census("let run = async || app.run(c); assert!(run().await.is_ok());"), [], "an awaited async closure runs"); + assert_eq!(census("let run = async || { app.run(c) }; assert!(run().await.is_ok());"), [], "an awaited block-bodied async closure runs"); + assert_eq!(census("let _saved = Some(|| app.run(c)); assert!(menu(c).is_some());"), [(2, "census")], "a stored closure is not called"); + assert_eq!(census("let run = (|| app.run(c)); run(); assert!(menu(c).is_some());"), [], "a called parenthesized closure runs"); + assert_eq!( + census("let _run = (|| app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled parenthesized closure does not run" + ); + assert_eq!(census("let _ = (|| app.run(c))(); assert!(menu(c).is_some());"), [], "a closure called where it is written runs"); + assert_eq!( + census("let _ = (|| { prepare(); app.run(c) })(); assert!(menu(c).is_some());"), + [], + "a block closure called where it is written runs" + ); + assert_eq!( + census("let _future = (async || app.run(c))(); assert!(menu(c).is_some());"), + [(2, "census")], + "an async closure called where it is written only makes a future" + ); + assert_eq!(census("assert!((async || app.run(c))().await.is_ok());"), [], "an awaited async closure called where it is written runs"); + assert_eq!( + census("let _saved = Some(|| { app.run(c) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a stored block closure is not called" + ); + assert_eq!( + census("let _saved = Some(|| { prepare(); app.run(c) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a later statement of a stored block closure is not run" + ); + assert_eq!(census("let _ = || { prepare(); app.run(c) }; assert!(menu(c).is_some());"), [(2, "census")], "a dropped closure is not called"); + assert_eq!( + census("let _ = ready || { prepare(); app.run(c) }; assert!(menu(c).is_some());"), + [(2, "census")], + "an || before a block can skip it" + ); + assert_eq!( + census("let _ = ready && { prepare(); app.run(c) }; assert!(menu(c).is_some());"), + [(2, "census")], + "an && before a block can skip it" + ); + assert_eq!( + census("let run = || app.run(c); let run = || (); run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a shadowing closure takes the call" + ); + assert_eq!( + census("let run = || { app.run(c) }; let run = || (); run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a shadowing closure takes the call of a block closure" + ); + assert_eq!(census("let run = || app.run(c); run(); assert!(menu(c).is_some());"), [], "a closure called without shadowing runs"); + assert_eq!( + census("let run = || app.run(c); let run = run(); assert!(menu(c).is_some());"), + [], + "a shadowing initializer still calls the earlier closure" + ); + assert_eq!( + census("let run = || app.run(c); { let run = || (); } run(); assert!(menu(c).is_some());"), + [], + "a shadowing closure ends with its block" + ); + assert_eq!( + census("assert!((menu(c).is_some() && app.run(c).is_ok()) && other(c).is_some());"), + [], + "a conjunction inside a required conjunction runs" + ); + assert_eq!( + census("assert!((menu(c).is_some() && app.run(c).is_ok()) || other(c).is_some());"), + [(2, "census")], + "a conjunction on one side of || can be bypassed" + ); + } + #[test] fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); From 444c46c5158b9caa339010aea066e944d4059959 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:12:47 -0800 Subject: [PATCH 52/60] Scripts: for-in visits a name when a getPrototypeOf trap returns a new proxy each time A for-in loop asks only the proxies whose ownKeys trap listed a name for its descriptor. When a getPrototypeOf trap returned a new proxy of the same target on each call, the proxy met before each name was not the one that listed it, so the name was skipped. The loop now records, for each proxy, the proxy its prototype lookup returned, and a new proxy of that same target in its place answers for it. Proxies that list nothing are recorded too, so another proxy of their target does not answer for them, and the listing proxies stay rooted until the iterator holds them. Follows #10185. --- crates/js/src/heap.rs | 11 ++-- crates/js/src/interp.rs | 74 +++++++++++++++--------- crates/js/src/proxy_tests.rs | 108 +++++++++++++++++++++++++++++++++++ docs/mcp.md | 4 +- 4 files changed, 162 insertions(+), 35 deletions(-) diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index d69e34fae4..c758610862 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,9 +215,8 @@ pub(crate) struct ArgMap { #[derive(Clone, Debug)] pub(crate) struct ForIn { pub(crate) keys: Vec, - /// The proxies whose `ownKeys` trap returned a listed name, each with the positions in `keys` - /// of the names it returned. - pub(crate) listed: Vec, + /// Each proxy on the chain maps to the positions in `keys` of the names its `ownKeys` trap returned. + pub(crate) listed: HashMap, pub(crate) pos: usize, pub(crate) object: Option, } @@ -227,7 +226,8 @@ pub(crate) struct ForIn { /// name's position is here. #[derive(Clone, Debug)] pub(crate) struct Listed { - pub(crate) proxy: ObjId, + /// The proxy returned by this proxy's prototype lookup, if any. + pub(crate) prototype: Option, pub(crate) positions: Vec, } @@ -1191,7 +1191,8 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } Class::ForIn(state) => { work.extend(state.object.iter().map(|o| o.0)); - work.extend(state.listed.iter().map(|l| l.proxy.0)); + work.extend(state.listed.keys().map(|o| o.0)); + work.extend(state.listed.values().filter_map(|l| l.prototype.map(|o| o.0))); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); strings.bytes += crate::interp::listed_bytes(&state.listed); } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 5f1f170b8b..69988da046 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -18,6 +18,7 @@ //! keeps its operands on the operand stack until it is done, so everything it holds is reachable //! from the roots when a nested run collects. +use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -575,11 +576,11 @@ pub(crate) const KEY_ENTRY_BYTES: usize = 32; pub(crate) const SOURCE_ENTRY_BYTES: usize = std::mem::size_of::(); /// The bytes of a `for-in` loop's record of one proxy that listed names, without its positions. -const LISTED_ENTRY_BYTES: usize = std::mem::size_of::(); +const LISTED_ENTRY_BYTES: usize = std::mem::size_of::<(ObjId, Listed)>() + KEY_ENTRY_BYTES; /// The bytes of a `for-in` loop's records of the proxies that listed its names. -pub(crate) fn listed_bytes(listed: &[Listed]) -> usize { - listed.iter().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum() +pub(crate) fn listed_bytes(listed: &HashMap) -> usize { + listed.values().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum() } /// The most units of a computed property name an error about a property of `null` or `undefined` @@ -3332,29 +3333,27 @@ impl Interp { /// For a String object, the heap budget for all its index names is checked before any is /// built. Each index name and each property visited takes a unit of fuel. /// - /// The second list holds each proxy whose `ownKeys` trap returned a listed name, with the - /// positions of the names it returned. - fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, Vec)> { + /// The map records each proxy's listed positions and the proxy returned by its prototype lookup. + /// Listing roots remain until `op_for_in_start` installs the iterator. + fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, HashMap)> { if self.options.e4x && self.is_xml(&Value::Object(id)) { - return Ok((self.xml_enumerate(id)?, Vec::new())); + return Ok((self.xml_enumerate(id)?, HashMap::new())); } let slot = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); - let r = self.enumerable_keys_from(id, slot); - self.temp_roots.truncate(slot); - r + self.enumerable_keys_from(id, slot) } /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its /// `ownKeys` trap and the next object with its `getPrototypeOf` trap. /// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype. /// Descriptors are checked when iteration reaches each name. - fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, Vec)> { + fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, HashMap)> { // Each name met on the chain, with its position in `out` when it is listed. let mut seen: std::collections::HashMap> = std::collections::HashMap::new(); let mut held = HeldBytes::new(self); let mut out: Vec = Vec::new(); - let mut listed: Vec = Vec::new(); + let mut listed = HashMap::new(); let next_pos = |out: &Vec| u32::try_from(out.len()).unwrap_or(u32::MAX); let mut cur = Some(id); while let Some(o) = cur { @@ -3362,6 +3361,7 @@ impl Interp { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(o); } + self.temp_roots.push(Value::Object(o)); let keys = self.own_keys(o)?; let mut positions = Vec::new(); for k in keys { @@ -3382,13 +3382,12 @@ impl Interp { positions.push(pos); } } - if !positions.is_empty() { - held.add(self, LISTED_ENTRY_BYTES)?; - positions.sort_unstable(); - positions.dedup(); - listed.push(Listed { proxy: o, positions }); - } + held.add(self, LISTED_ENTRY_BYTES)?; + positions.sort_unstable(); + positions.dedup(); cur = self.get_prototype_of(o)?; + let prototype = cur.filter(|&p| self.is_proxy(p)); + listed.insert(o, Listed { prototype, positions }); if let Some(root) = self.temp_roots.get_mut(slot) { *root = cur.map_or(Value::Undefined, Value::Object); } @@ -3443,14 +3442,20 @@ impl Interp { } fn op_for_in_start(&mut self) -> JsResult<()> { + let saved = self.temp_roots.len(); + let r = self.op_for_in_start_rooted(); + self.temp_roots.truncate(saved); + r + } + + fn op_for_in_start_rooted(&mut self) -> JsResult<()> { let v = self.peek(0)?; let ((keys, listed), object) = if v.is_nullish() { - ((Vec::new(), Vec::new()), None) + ((Vec::new(), HashMap::new()), None) } else { let o = self.to_object(&v)?; // A wrapper made by ToObject is not on the stack; a collection while the names are // listed or their bytes reserved must not free it. - let saved = self.temp_roots.len(); self.temp_roots.push(Value::Object(o)); // Listing a namespace object's exports does not read them (ECMA-262 2015 section // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. @@ -3460,7 +3465,6 @@ impl Interp { self.heap.bytes = self.heap.bytes.saturating_add(bytes); Ok((keys, listed)) }); - self.temp_roots.truncate(saved); (keys?, Some(o)) }; let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, listed, pos: 0, object })), None)); @@ -3493,8 +3497,9 @@ impl Interp { /// /// `pos` is the position of `k` in the names of the loop `iter`. A proxy is asked through its /// `getOwnPropertyDescriptor` trap only when its `ownKeys` trap returned `k` while the names - /// were listed, wherever it sits on the chain now; any other proxy cannot hide an inherited - /// name. A typed array without the element `k` names does not hide its prototypes' `k`. + /// were listed, or when the same prototype lookup returns a fresh proxy of that target. + /// Recorded proxies can move on the chain; any other proxy cannot hide an inherited name. + /// A typed array without the element `k` names does not hide its prototypes' `k`. fn for_in_still_has(&mut self, iter: ObjId, o: ObjId, k: &Key, pos: u32) -> JsResult { // One root slot holds the proxy the walk has reached, then the prototype it gave. let mark = self.temp_roots.len(); @@ -3506,13 +3511,18 @@ impl Interp { fn for_in_still_has_rooted(&mut self, iter: ObjId, mut cur: ObjId, k: &Key, pos: u32, slot: usize) -> JsResult { let mut steps = 0usize; + let mut candidate = None; loop { if self.is_proxy(cur) { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(cur); } self.use_fuel()?; - if self.for_in_listed_by(iter, cur, pos)? + let source = self.for_in_listing_proxy(iter, cur, candidate)?; + let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") }; + let listed = source.and_then(|p| state.listed.get(&p)); + candidate = listed.and_then(|l| l.prototype); + if listed.is_some_and(|l| l.positions.binary_search(&pos).is_ok()) && let Some(prop) = self.get_own_property(cur, k)? { return Ok(prop.enumerable()); @@ -3524,6 +3534,7 @@ impl Interp { cur = next; continue; } + candidate = None; if let Some(prop) = self.ordinary_own_property(cur, k)? { return Ok(prop.enumerable()); } @@ -3536,11 +3547,18 @@ impl Interp { } } - /// Whether the `ownKeys` trap of `proxy` returned the name at `pos` when the loop `iter` - /// listed its names. - fn for_in_listed_by(&self, iter: ObjId, proxy: ObjId, pos: u32) -> JsResult { + /// Finds a recorded proxy by identity or by the preceding proxy's recorded prototype lookup. + fn for_in_listing_proxy(&self, iter: ObjId, proxy: ObjId, candidate: Option) -> JsResult> { let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") }; - Ok(state.listed.iter().any(|l| l.proxy == proxy && l.positions.binary_search(&pos).is_ok())) + if state.listed.contains_key(&proxy) { + return Ok(Some(proxy)); + } + let target = |p: ObjId| match self.heap.object(p).map(|o| &o.class) { + Some(Class::Proxy(d)) => d.target, + _ => None, + }; + let Some(own) = target(proxy) else { return Ok(None) }; + Ok(candidate.filter(|&p| target(p) == Some(own))) } // ---- calls ---- diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 0bbe6e0b02..8a0b1fec1f 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1854,6 +1854,114 @@ fn for_in_asks_only_the_proxies_that_listed_a_name() { ); } +#[test] +fn for_in_visits_a_name_from_a_prototype_trap_that_returns_a_new_proxy_each_time() { + // Each [[GetPrototypeOf]] gives a new proxy of `t`: the one asked before each name is not the + // one whose ownKeys listed it. + truth_collecting( + "var t = { a: 1, b: 2 }; + var o = new Proxy({}, { ownKeys: function () { return []; }, getPrototypeOf: function () { return new Proxy(t, {}); } }); + var seen = []; + for (var name in o) seen.push(name); + seen.join() === 'a,b'", + ); + // A non-enumerable descriptor from such a proxy still does not hide a name further on. + truth( + "var c = { x: 1 }; + var o = new Proxy({}, { + ownKeys: function () { return []; }, + getPrototypeOf: function () { + return new Proxy({}, { + ownKeys: function () { return []; }, + getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; }, + getPrototypeOf: function () { return c; } + }); + } + }); + var seen = []; + for (var name in o) seen.push(name); + seen.join() === 'x'", + ); + // Two proxies of one target on the chain: the one that listed nothing does not decide for the + // one that listed `x`. + truth( + "var t = {}; + var b = new Proxy(t, { + ownKeys: function () { return ['x']; }, + getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; } + }); + var a = new Proxy(t, { + ownKeys: function () { return []; }, + getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; }, + getPrototypeOf: function () { return b; } + }); + var seen = []; + for (var name in a) seen.push(name); + seen.join() === 'x'", + ); +} + +#[test] +fn for_in_matches_nested_fresh_wrappers_to_their_prototype_lookups() { + truth_collecting( + "var t = { a: 1, b: 2 }, middle = {}; + var handler = { + ownKeys: function () { return []; }, + getPrototypeOf: function () { return new Proxy(t, {}); } + }; + var o = new Proxy({}, { + ownKeys: function () { return []; }, + getPrototypeOf: function () { return new Proxy(middle, handler); } + }); + var seen = []; + for (var name in o) seen.push(name); + seen.join() === 'a,b'", + ); +} + +#[test] +fn for_in_does_not_ask_an_inserted_proxy_of_a_listing_proxys_target() { + truth_collecting( + "var t = { a: 1, b: 2 }, reads = 0; + var listed = new Proxy(t, {}); + var o = Object.create(listed), seen = []; + for (var name in o) { + seen.push(name); + if (name === 'a') { + Object.setPrototypeOf(o, new Proxy(t, { + getOwnPropertyDescriptor: function () { + reads++; + return { value: 0, enumerable: false, configurable: true }; + }, + getPrototypeOf: function () { return listed; } + })); + } + } + seen.join() === 'a,b' && reads === 0", + ); +} + +#[test] +fn for_in_walks_many_empty_proxies_before_inherited_names() { + truth( + "var base = {}, depth = 256, count = 32, walks = 0, reads = 0; + for (var i = 0; i < count; i++) base['key' + i] = i; + function wrap(next) { + return new Proxy({}, { + ownKeys: function () { return []; }, + getOwnPropertyDescriptor: function () { reads++; return undefined; }, + getPrototypeOf: function () { walks++; return next; } + }); + } + var o = base; + for (var j = 0; j < depth; j++) o = wrap(o); + var seen = []; + for (var name in o) seen.push(name); + seen.length === count && seen.every(function (name, index) { return name === 'key' + index; }) && + reads === 0 && walks === depth * (count + 1)", + ); +} + #[test] fn for_in_reaches_a_name_past_a_typed_array_without_that_element() { truth( diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..8553f1dde7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2924,8 +2924,8 @@ the same key twice (two Symbols are the same key only when they are the same Sym result is checked against the target's non-configurable keys of both kinds. A `for-in` prototype walk keeps the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain. A `for-in` loop checks each proxy candidate's descriptor -when iteration reaches that name, and asks only the proxies whose `ownKeys` trap returned the name, wherever they sit -on the chain then; a typed array without the element a name gives does not hide that name on its prototypes. An `ownKeys` result is read and its elements are validated before duplicate +when iteration reaches that name, and asks only the proxies whose `ownKeys` trap returned the name, or a new proxy of +the same target that the same `getPrototypeOf` trap returns in its place (such a trap may return a new proxy on each call), wherever they sit on the chain then; a typed array without the element a name gives does not hide that name on its prototypes. An `ownKeys` result is read and its elements are validated before duplicate names are rejected; a later getter's exception takes precedence over the duplicate-name error. Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay From a875e6e6be221cc31bc15c9f4e274a23508032cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:12:48 -0800 Subject: [PATCH 53/60] Print: Windows paper sizes that share a name are all listed The Size list keyed a Windows printer's paper sizes by name, so a second size with the same name (several Custom forms, for example) was dropped. Each size is now kept, and sizes that share a name show their size in inches after it, with a number when that name is still another form's. Two driver sizes that both match one built-in size stay the printer's own papers, so either can be picked. Follows #10511. --- crates/ui-egui/src/dialogs/print.rs | 11 ++- crates/ui-egui/src/dialogs/tests_print.rs | 104 ++++++++++++++++++++++ crates/ui-egui/src/print.rs | 34 ++++++- 3 files changed, 145 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6546b2ff5b..5bebc27656 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -181,7 +181,7 @@ fn media_choices(papers: &[Paper], current: &str) -> Vec<(String, String)> { } else { let mut out: Vec<(String, String)> = Vec::new(); for p in papers { - let id = own_media_of(p).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string()); + let id = own_media_choice(p, papers).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string()); if out.iter().all(|(i, _)| *i != id) { out.push((id, p.label.clone())); } @@ -203,6 +203,13 @@ fn own_media_of(p: &Paper) -> Option { Media::ALL.iter().copied().find(|m| m.size().is_some_and(|(mw, mh)| (mw.min(mh) - w).abs() <= 0.5 && (mw.max(mh) - h).abs() <= 0.5)) } +/// [`own_media_of`] `p`, unless another of `papers` with a different size matches the same size: both then stay +/// the printer's own papers. +fn own_media_choice(p: &Paper, papers: &[Paper]) -> Option { + let own = own_media_of(p)?; + (!papers.iter().any(|q| own_media_of(q) == Some(own) && (q.width, q.height) != (p.width, p.height))).then_some(own) +} + /// The printer's paper the Size row names (`printer:CR80`), when it is one of `papers`. fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a Paper> { let key = fields.text("media")?.strip_prefix(PRINTER_PAPER)?; @@ -521,7 +528,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, if let Some(new) = printer_paper(fields, &open.papers.1) && chosen.as_ref().is_none_or(|old| same_size(old, new)) { - let own = own_media_of(new)?; + let own = own_media_choice(new, &open.papers.1)?; fields.set("media", own.id()); return Some((own.id().to_string(), settings(fields))); } diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index d2ebf74122..131de851bd 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -650,6 +650,110 @@ fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() { assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number"); } +#[test] +fn windows_paper_sizes_that_share_a_name_are_all_listed() { + // A driver form whose name looks like a size suffix is a size of its own. + let out = "256\tCustom\t400\t600\r\n256\tCustom\t500\t1181\r\n256\tCustom\t400\t600\r\n256\tCustom 500x1181\t520\t720\r\n\ + 256\tCustom (4 x 6 in)\t300\t300\r\n"; + let papers = crate::print::windows_papers(out); + let labels: Vec<&str> = papers.iter().map(|p| p.label.as_str()).collect(); + // Both sizes named Custom are listed, with their sizes; the repeat of the first size is left out, + // and a shown name another form already has gets a number. + assert_eq!(labels, ["Custom (4 x 6 in) 2", "Custom (5 x 11.81 in)", "Custom 500x1181", "Custom (4 x 6 in)"]); + let mut keys: Vec<&str> = papers.iter().map(|p| p.key.as_str()).collect(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), 4, "{keys:?}"); + assert!((papers[1].width - 360.0).abs() < 1e-9 && (papers[1].height - 850.32).abs() < 1e-9); +} + +struct WindowsForms(&'static str); + +impl PrintService for WindowsForms { + fn printers(&mut self) -> Vec { + vec![Printer::new("Forward").is_default(true), Printer::new("Reverse")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let out = if printer == "Reverse" { self.0.lines().rev().collect::>().join("\n") } else { self.0.to_string() }; + Papers::Ready(crate::print::windows_papers(&out)) + } +} + +#[test] +fn distinct_windows_sizes_matching_one_built_in_size_are_selectable() { + let out = "11\tA5\t582\t827\n11\tA5\t583\t827\n"; + let papers = crate::print::windows_papers(out); + assert_eq!(papers.len(), 2); + assert!(papers[0].width < papers[1].width); + assert_eq!(papers[0].height, papers[1].height); + let services = Services { print: Some(Box::new(WindowsForms(out))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + for paper in &papers { + let media = format!("printer:{}", paper.key); + set(&mut app, "media", json!(media)); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], media); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(paper.width), Some(paper.height)), "{f}"); + } +} + +#[test] +fn windows_forms_stay_selected_when_queue_enumeration_order_changes() { + for out in ["256\tCustom\t400\t600\n256\tCustom\t500\t700\n", "11\tA5\t582\t827\n11\tA5\t583\t827\n"] { + let papers = crate::print::windows_papers(out); + let reverse = crate::print::windows_papers(&out.lines().rev().collect::>().join("\n")); + for paper in &papers { + let other = reverse.iter().find(|p| (p.width, p.height) == (paper.width, paper.height)).unwrap(); + assert_eq!(paper.key, other.key); + } + let services = Services { print: Some(Box::new(WindowsForms(out))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + for paper in &papers { + set(&mut app, "printer", json!("Forward")); + pump(&mut app); + let media = format!("printer:{}", paper.key); + set(&mut app, "media", json!(media)); + pump(&mut app); + set(&mut app, "printer", json!("Reverse")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], media); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(paper.width), Some(paper.height)), "{f}"); + } + } +} + +#[test] +fn long_windows_paper_labels_keep_dimensions_and_collision_numbers() { + let name = "é".repeat(128); + let suffix = " (4 x 6 in)"; + let prefix: String = name.chars().take(128 - suffix.chars().count()).collect(); + let collision = format!("{prefix}{suffix}"); + let out = format!("256\t{name}\t400\t600\n256\t{name}\t500\t700\n256\t{collision}\t300\t300\n"); + let papers = crate::print::windows_papers(&out); + assert_eq!(papers.len(), 3); + assert!(papers.iter().all(|p| p.label.chars().count() <= 128)); + assert!(papers[0].label.ends_with(" (4 x 6 in) 2"), "{:?}", papers[0]); + assert!(papers[1].label.ends_with(" (5 x 7 in)"), "{:?}", papers[1]); + assert_eq!(papers[2].label, collision); + for (i, paper) in papers.iter().enumerate() { + assert!(papers[i + 1..].iter().all(|p| p.label != paper.label)); + } +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 0451cb5b5c..c1ab63a121 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -141,7 +141,9 @@ pub fn ppd_papers(ppd: &str) -> Vec { } /// The paper sizes in tab-separated lines of number, name, width and height (hundredths of an inch), as Windows' -/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply. +/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply. A name +/// listed again with another size stays in the list, keyed by its name and size, and every size of that name +/// shows its size in inches after the name; one listed again with the same size is left out. pub fn windows_papers(out: &str) -> Vec { let mut papers: Vec = Vec::new(); for line in out.lines() { @@ -150,9 +152,37 @@ pub fn windows_papers(out: &str) -> Vec { let (Ok(w), Ok(h)) = (w.parse::(), h.parse::()) else { continue }; if !key.is_empty() { let label = if label.is_empty() { key } else { label }; - push_paper(&mut papers, Paper { key: label.into(), label: label.into(), width: w * 0.72, height: h * 0.72 }); + let (width, height) = (w * 0.72, h * 0.72); + let key = format!("{label}\t{w}x{h}"); + push_paper(&mut papers, Paper { key, label: label.into(), width, height }); } } + // Sizes that share a name show their size in inches after it. + // A shown name that is still another paper's gets a number after it. + let names: Vec = papers.iter().map(|p| p.key.split('\t').next().unwrap_or_default().to_string()).collect(); + let inches = |pt: f64| (pt / 0.72).round() / 100.0; + for i in 0..papers.len() { + if names.iter().filter(|n| **n == names[i]).count() < 2 { + papers[i].key = names[i].clone(); + continue; + } + let p = &papers[i]; + let suffix = format!(" ({} x {} {})", inches(p.width), inches(p.height), tl!("in")); + let with_suffix = |suffix: &str| { + let name: String = names[i].chars().take(MAX_PAPER_LABEL.saturating_sub(suffix.chars().count())).collect(); + format!("{name}{suffix}") + }; + let shown = |label: &str| { + papers.iter().enumerate().any(|(j, q)| j != i && q.label.chars().take(MAX_PAPER_LABEL).eq(label.chars().take(MAX_PAPER_LABEL))) + }; + let mut label = with_suffix(&suffix); + let mut n = 2; + while shown(&label) && n < MAX_PAPERS + 2 { + label = with_suffix(&format!("{suffix} {n}")); + n += 1; + } + papers[i].label = label.chars().take(MAX_PAPER_LABEL).collect(); + } papers } From f8eb542e04ad590aec59e7c0b94c9953ac0a5af8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:06:02 -0800 Subject: [PATCH 54/60] Scripts: geometry read from a document in the back matches what the setters measure The bounds getters (position, left, top, width, height and the bounds arrays) read an item in a document in the back without measuring its type, while the setters measure it after the switch to that document since #10538. A script that read t.width and assigned it back could resize the item, and every geometry assignment switched to the document and back even when nothing changed. The getters now measure type not measured yet in a document in the back for an item that holds type, a symbol instance or a placed document, the way the switch measures it, and the check is skipped while the document is unchanged. An assignment equal to the current value of an object without such content in a document in the back returns without switching documents, and no undo step is made. --- crates/engine/src/script/dom.rs | 59 ++++++++++++++++++++------ crates/engine/src/session/documents.rs | 22 ++++++++++ crates/engine/src/tests/script_dom.rs | 52 +++++++++++++++++++++++ docs/mcp.md | 5 ++- 4 files changed, 124 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b29b037908..3c2bbe8d29 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2477,8 +2477,12 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer { /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the /// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path /// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does -/// nothing. +/// nothing. Type in a document in the back that is not measured yet is measured first, as the +/// switch to that document would measure it. fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option, Frame), HostError> { + if h.session.borrow().active_index() != Some(item.doc.index) && rests_on_type(h, item) { + h.session.borrow_mut().measure_back_type(item.doc.uid); + } with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?))) } @@ -2550,20 +2554,41 @@ fn item_height(h: &Host, a: &[Data]) -> Answer { Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height()))) } +/// Whether the item's bounds can rest on laid-out type: it holds type, a symbol instance or a +/// placed document. Such bounds in a document in the back may be laid out in another document's +/// composite fonts, so the setters measure them only after the switch to the document. +fn rests_on_type(h: &Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).is_none_or(|n| { + let mut found = false; + n.walk(&mut |c| found |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_))); + found + }) + }) +} + /// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - // Measured once the document is active. - edit_item_with(h, item, |h| { - let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) }; + // The distance to move, or `None` when the item is already there or has no bounds. + let delta = |h: &Host| -> std::result::Result, HostError> { + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(None) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); let (dx, dy) = (to.x - r.x0, to.y - r.y0); - if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + Ok((dx.abs() > 1e-9 || dy.abs() > 1e-9).then_some((dx, dy))) + }; + // An item already in place stays, and its document stays in the back. + if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && delta(h)?.is_none() { + return Ok(Data::Undefined); + } + // Measured again once the document is active. + edit_item_with(h, item, |h| { + if let Some((dx, dy)) = delta(h)? { command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; } Ok(()) @@ -2601,19 +2626,27 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - // Measured once the document is active, so the ratio applies to the bounds the scale works on. - edit_item_with(h, item, |h| { - let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) }; + // The bounds to scale and the percentage, or `None` when the item already has that size or has + // no bounds. + let scale = |h: &Host| -> std::result::Result, HostError> { + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(None) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { return Err(HostError::Error(format!("the object has no {what} to scale"))); } - if (now - size).abs() < 1e-9 { - return Ok(()); + Ok(((now - size).abs() >= 1e-9).then_some((r, size / now * 100.0))) + }; + // An item already that size stays, and its document stays in the back. + if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && scale(h)?.is_none() { + return Ok(Data::Undefined); + } + // Measured again once the document is active, so the ratio applies to the bounds the scale + // works on. + edit_item_with(h, item, |h| { + if let Some((r, pct)) = scale(h)? { + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; } - let pct = size / now * 100.0; - let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; - command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; Ok(()) })?; Ok(Data::Undefined) diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 4669876304..f902c9a3b6 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -496,6 +496,28 @@ impl Session { true } + /// Measure the type not measured yet in the open document with [`DocState::uid`] `uid` when it is + /// in the back, as [`Session::measure_back_document`] does, so bounds read from it are the ones + /// it has once it comes to the front. A document in front, or one with all its type measured, + /// is left as it is. A document unchanged since it was last measured or checked here is not + /// walked again ([`DocState::measured_in_own`]; with no composite font names kept, its coming + /// to the front measures again what it would have measured without the check). + pub(crate) fn measure_back_type(&mut self, uid: u64) { + let Some(index) = self.docs.iter().position(|d| d.uid == uid) else { return }; + if self.active == Some(index) { + return; + } + let st = &mut self.docs[index]; + if st.measured_in_own.as_ref().is_some_and(|(doc, _)| std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))) { + return; + } + if text_trees(&st.doc).any(|n| has_text_where(n, &mut |t| t.cached_bounds.is_none())) { + self.measure_back_document(index); + } else { + st.measured_in_own = Some((Arc::downgrade(&st.doc), HashSet::new())); + } + } + /// Measure the type not measured yet in open document `index`, which is in the back, in its own /// composite fonts, lent for the measuring, so its type has the bounds it will have when the /// document comes to the front: type naming a composite font the document does not define is diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f731eef72d..975de6a42a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -186,6 +186,58 @@ fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); } +/// The getters measure type in a document in the back as the setters do, so assigning an item's +/// own width, height, left, top or position back to it changes nothing and makes no undo step, +/// and for an object without type the document is not switched to. +#[test] +fn page_item_geometry_read_from_a_back_document_assigns_back_without_a_change() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap()); + let uid = s.active().unwrap().uid; + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let front = s.active().unwrap().uid; + let back = |s: &Session| s.documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.history.undo.len()); + let steps = back(&s); + let sets = ["t.width = t.width;", "t.height = t.height;", "t.left = t.left;", "t.top = t.top;", "t.position = t.position;"]; + for (kind, set) in sets.iter().flat_map(|set| [("TextFrame", set), ("PathItem", set)]) { + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + // A switch to the back document and back again would stamp the front document anew. + let stamp = s.active().unwrap().activated; + let out = log( + &mut s, + &format!( + "var p = app.documents[1].pageItems, t = p[0].typename == '{kind}' ? p[0] : p[1];\ + var w = t.width, x = t.left; {set} vc.log(t.width - w); vc.log(t.left - x);" + ), + ); + assert_eq!(out.len(), 2, "{kind} {set}"); + for d in &out { + assert!(d.as_f64().unwrap().abs() < 1e-6, "{kind} {set} moved or resized the item by {d}"); + } + assert_eq!(back(&s), steps, "{kind} {set} made an undo step"); + if kind == "PathItem" { + assert_eq!(s.active().unwrap().activated, stamp, "{set} switched documents"); + } + } + assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + let in_back = log(&mut s, "vc.log(app.documents[1].pageItems[0].width);"); + let index = s.documents().iter().position(|d| d.uid == uid).unwrap(); + s.execute("document.activate", &json!({"index": index})).unwrap(); + let in_front = log(&mut s, "vc.log(app.activeDocument.pageItems[0].width);"); + assert_eq!(in_back, in_front, "the width read in the back is the width read in front"); +} + /// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the /// visible bounds. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..ce156071ea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3106,7 +3106,10 @@ through `$`: 100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"` (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds, widened to take in the direction points of every path in the object), `editable` (false for an + visible bounds, widened to take in the direction points of every path in the object; in a document in the back, type + not measured yet is measured first, as the switch to that document would measure it; a valid + `position`, `left`, `top`, `width` or `height` equal to the value an object that holds no type, symbol instance + or placed document already has is not applied, and its document stays in the back), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` From 31d02e482196819837e229be4e8e093787c59063 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:39:44 -0800 Subject: [PATCH 55/60] Scripts: startup scripts at launch list no printers, and spool failures stay shown The startup scripts run at launch no longer list the print service's printers, so the first window does not wait on it; a script.startup.run with any other reason still lists them. A script's print jobs that the desktop's worker fails to send are shown in the status bar even when a later line, a later batch that was sent or a startup script's failure took it, and the startup script's notes stay in the hover. script.startup.run's params text describes the print wait and the launch rule. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/ui-egui/src/print.rs | 35 ++++-- crates/ui-egui/src/tests/script_print.rs | 145 ++++++++++++++++++++++- docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 5 files changed, 177 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 37a661dfcb..d273dabad5 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Run Startup Scripts", [], None, - "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry", + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry; in the app, a run lists the printers once when the runs are queued and each queued run may print to them, except with reason launch, whose runs list no printers and cannot print to a printer, and a queued run waits while the jobs the run before it prepared for a printer wait for Print or Cancel", always, startup_run ), diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 0e10b1fbb7..c56c7fbfa2 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -171,12 +171,14 @@ pub fn script_printers(app: &mut VectorcraftApp) -> Option { Some(Printers::new(service.printers().into_iter().map(|p| (p.name, p.default)), for_printer)) } -/// Runs the engine command `id`. A `script.run` or `script.startup.run` started here lists the -/// printers its first run may print to ([`script_printers`]), and only that run lists them; the -/// runs `script.startup.run` queues list the same printers as they start -/// ([`crate::script_runs::poll`]). +/// Runs the engine command `id`. A `script.run`, or a `script.startup.run` whose reason is not +/// `launch`, started here lists the printers its first run may print to ([`script_printers`]), and +/// only that run lists them; the runs `script.startup.run` queues list the same printers as they +/// start ([`crate::script_runs::poll`]). The startup scripts run at launch list no printers, so the +/// first window does not wait on the print service. pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result { - let listed = if matches!(id, "script.run" | "script.startup.run") { script_printers(app) } else { None }; + let lists = id == "script.run" || (id == "script.startup.run" && params.get("reason").and_then(Value::as_str) != Some("launch")); + let listed = if lists { script_printers(app) } else { None }; app.session.script_printers = listed.clone(); let r = app.session.execute(id, params).map_err(|e| e.to_string()); app.session.script_printers = None; @@ -189,6 +191,9 @@ pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, param /// The error for a script's jobs when the print service does not let scripts print. const NO_SCRIPT_PRINTING: &str = "Printing from scripts is not available here: the script's print jobs were not sent"; +/// The start of the status line for a script's print jobs that the desktop's worker failed to send. +const SCRIPT_PRINT_FAILED: &str = "Printing from a script failed"; + /// Sends the jobs a script prepared, which the person approved, each to its printer. Every printer /// must still be one the service lists, by its exact name, or no job is sent. → `{sent}`, or /// `{background: true}` while the desktop's worker sends them. @@ -207,8 +212,24 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec>>, scripts: bool, + /// When set, jobs go to the desktop's worker, which fails to spool them with this message, or + /// sends them when it is empty. + spool_error: Option<&'static str>, + /// How many times the printers were listed. + lists: Rc>, } impl PrintService for Spool { fn printers(&mut self) -> Vec { + self.lists.set(self.lists.get() + 1); self.names.borrow().iter().enumerate().map(|(i, name)| Printer::new(name.clone()).is_default(i == 0)).collect() } @@ -39,6 +45,11 @@ impl PrintService for Spool { fn scripts_may_print(&self) -> bool { self.scripts } + + fn shared_print(&self) -> Option { + let error = self.spool_error?; + Some(std::sync::Arc::new(move |_| if error.is_empty() { Ok("Sent".to_string()) } else { Err(error.to_string()) })) + } } /// An app in a window, with a document, a print service listing Office (the default) and Lab, and @@ -46,7 +57,7 @@ impl PrintService for Spool { fn print_app(scripts: bool) -> (VectorcraftApp, Sent, Rc>>) { let sent = Sent::default(); let names = Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()])); - let spool = Spool { sent: sent.clone(), names: names.clone(), scripts }; + let spool = Spool { sent: sent.clone(), names: names.clone(), scripts, spool_error: None, lists: Default::default() }; let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() })); app.run("file.new", json!({})).unwrap(); app.session.prefs.show_external_script_warning = false; @@ -303,6 +314,111 @@ fn a_failed_run_or_a_printer_that_went_away_sends_nothing() { assert!(!asking(&app)); } +/// An app whose script print jobs go to the desktop's worker, which fails with `error` (or sends +/// them when it is empty). +fn worker_print_app(error: &'static str) -> VectorcraftApp { + let spool = Spool { + sent: Sent::default(), + names: Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()])), + scripts: true, + spool_error: Some(error), + lists: Default::default(), + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() })); + app.services.write_shared = Some(std::sync::Arc::new(|_, _| Ok(()))); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +/// A job the desktop's worker fails to spool is reported even when another line, such as the next +/// queued script's, took the status bar while the worker ran. +#[test] +fn a_spool_failure_shows_after_a_later_status_line() { + let mut app = worker_print_app("The printer Lab is offline"); + run(&mut app, PRINT_TO_LAB); + assert!(asking(&app)); + click_after_delay(&mut app, 10.0, "Print"); + app.status("The next script ran"); + crate::background::wait_all(&mut app); + assert!(app.ui.status.contains("The printer Lab is offline"), "{}", app.ui.status); +} + +/// A later batch the worker sent does not replace an earlier batch's failure in the status bar. +#[test] +fn a_sent_batch_does_not_hide_an_earlier_spool_failure() { + let mut app = worker_print_app(""); + run(&mut app, PRINT_TO_LAB); + assert!(asking(&app)); + click_after_delay(&mut app, 10.0, "Print"); + app.status("Printing from a script failed: The printer Office is offline"); + crate::background::wait_all(&mut app); + assert!(app.ui.status.contains("The printer Office is offline"), "{}", app.ui.status); +} + +/// A spool failure stays visible after the next batch is approved and sent. +#[test] +fn a_batch_submitted_after_a_spool_failure_does_not_hide_it() { + let mut app = worker_print_app("The printer Lab is offline"); + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 10.0, "Print"); + run(&mut app, PRINT_TO_LAB); + assert!(asking(&app)); + crate::background::wait_all(&mut app); + let failure = app.ui.status.clone(); + assert!(failure.contains("The printer Lab is offline"), "{failure}"); + assert!(asking(&app)); + app.services.print = worker_print_app("").services.print; + click_after_delay(&mut app, 20.0, "Print"); + assert!(!asking(&app)); + assert!(!app.background.jobs.is_empty(), "the next batch was submitted"); + assert_eq!(app.ui.status, "Printing from a script…"); + crate::background::wait_all(&mut app); + assert_eq!(app.ui.status, failure); + assert_eq!(app.ui.status_notes, Some((failure.clone(), vec![failure]))); +} + +/// A spool failure keeps the startup scripts' errors in the status bar's hover notes. +#[test] +fn a_spool_failure_does_not_hide_a_later_startup_script_failure() { + let mut app = worker_print_app("The printer Lab is offline"); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO)); + let dir = std::env::temp_dir().join(format!("vc-script-print-startup-failure-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.jsx"), PRINT_TO_LAB).unwrap(); + std::fs::write(dir.join("b.jsx"), "throw new Error('The later startup script failed');").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(1);", "name": "chosen" })).unwrap().unwrap(); + for _ in 0..10_000 { + script_runs::poll(&mut app); + if asking(&app) { + break; + } + } + assert!(asking(&app)); + click_after_delay(&mut app, 10.0, "Print"); + for _ in 0..10_000 { + script_runs::poll(&mut app); + if !app.session.script_running() { + break; + } + } + assert!(!app.session.script_running()); + assert!(app.ui.startup_notes.is_empty(), "the startup round ended"); + assert!(app.ui.status.contains("The later startup script failed"), "{}", app.ui.status); + let startup_notes = app.ui.status_notes.as_ref().unwrap().1.clone(); + crate::background::wait_all(&mut app); + assert!(app.ui.status.contains("The printer Lab is offline"), "{}", app.ui.status); + let (status, notes) = app.ui.status_notes.as_ref().unwrap(); + assert_eq!(status, &app.ui.status, "the hover notes match the displayed status"); + assert!(notes.len() > 1, "the hover lists both failures"); + assert!(notes.contains(status)); + assert!(startup_notes.iter().all(|note| notes.contains(note)), "{notes:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// Without a service that lets scripts print (the web's), or without any, printing to a printer /// from a script throws and nothing is asked or sent. #[test] @@ -348,6 +464,33 @@ fn a_script_chosen_after_startup_scripts_may_print() { let _ = std::fs::remove_dir_all(&dir); } +/// The startup scripts run at launch do not list the printers, so the first window does not wait +/// on the print service. +#[test] +fn the_startup_scripts_at_launch_list_no_printers() { + let lists: Rc> = Default::default(); + let spool = Spool { + sent: Sent::default(), + names: Rc::new(RefCell::new(vec!["Office".to_string()])), + scripts: true, + spool_error: None, + lists: lists.clone(), + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() })); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO)); + let dir = std::env::temp_dir().join(format!("vc-script-print-launch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.jsx"), "vc.log(1);").unwrap(); + app.session.attach_startup_scripts_dir(dir.clone()); + app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap(); + script_runs::run_at_launch(&mut app); + assert!(app.session.script_running(), "the startup script started: {}", app.ui.status); + assert_eq!(lists.get(), 0, "the printers were not listed"); + assert!(app.queued_script_printers.is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + /// A startup script's jobs are asked about before the chosen script starts, so that script may /// print too. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1eb6ed2715..c94a526505 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4524,7 +4524,9 @@ reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the status bar. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel. -Each queued run lists the printers listed when the runs were queued. +Each queued run lists the printers listed when the runs were queued; the runs with reason `launch` list no +printers, so they cannot print to a printer. A job that fails to spool is reported in the status bar even when a +later run or a later job's note took it. Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from the prompt shown on quitting, between two runs, drops the runs not yet started, and the status bar says so. While that prompt is open, the next run does not start. Under `--automation-read-root` it reads the folder only when the folder lies inside a read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a356f947b9..5248dc8802 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1155,7 +1155,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `new ExternalObject("lib:AdobeXMPScript")` gives `XMPMeta`, `XMPFile` and `XMPConst` ([the help page](https://extendscript.docsforadobe.dev/scripting-xmp/xmpscript-object-reference/)): properties, arrays, language alternatives and namespaces read from a packet, changed and serialized, and a `.xmp` sidecar read and written with `getXMP`, `putXMP` and `closeFile`. VectorCraft's own rules: `XMPFile` reads and writes only where `File` may; other files are scanned for their packet and read only; a packet over 8 MiB or not well-formed throws; members not built yet (iterators, structure fields, qualifiers, aliases) throw that they are not available yet. `crates/js/src/xmp_tests.rs`, `crates/engine/src/tests/script_xmp.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - - Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel, and each queued run lists the printers listed when the runs were queued. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/src/tests/script_print.rs`, `crates/ui-egui/tests/safe_mode.rs`. + - Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel, and each queued run lists the printers listed when the runs were queued; the startup scripts run at launch list no printers. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/src/tests/script_print.rs`, `crates/ui-egui/tests/safe_mode.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. - Plug-in run notices: a filter or plug-in command's output may report a `notice`, which needs no permission; once the output is applied, `plugin.run` and the command return it and the status bar shows it as `Plug-in “name”: notice`, escaped, cut at 200 characters and never translated, and a run that fails or is refused shows none. VectorCraft's own API and limits. Tests: `objects::tests::notice_is_escaped_capped_and_checked` in `vectorcraft-plugins`, `a_filter_s_notice_is_returned_once_its_output_is_applied` and `a_plugin_command_returns_its_run_s_notice` in `vectorcraft-engine`, `plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated` in `vectorcraft-ui-egui`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. From 757b667f3d7dcebba4906d1c97308f5dca162679 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:39:46 -0800 Subject: [PATCH 56/60] Scripts: for-in keeps the names a proxy listed before the chain returns to it A getPrototypeOf trap may return the same proxy again. Its second visit replaced the positions the first visit recorded, so a name only the first ownKeys call returned was never visited. Each visit now adds its new positions to the proxy's record, each pair counted once against the heap limit, and the records are sorted and compacted once after the walk. --- crates/js/src/interp.rs | 20 +++++++++++++++----- crates/js/src/proxy_tests.rs | 17 +++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 69988da046..20640cc00d 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3354,6 +3354,7 @@ impl Interp { let mut held = HeldBytes::new(self); let mut out: Vec = Vec::new(); let mut listed = HashMap::new(); + let mut proxy_positions: std::collections::HashSet<(ObjId, u32)> = std::collections::HashSet::new(); let next_pos = |out: &Vec| u32::try_from(out.len()).unwrap_or(u32::MAX); let mut cur = Some(id); while let Some(o) = cur { @@ -3377,17 +3378,20 @@ impl Interp { } }; // A name an earlier object has but does not list is not listed again. - if let Some(pos) = pos { - held.add(self, SOURCE_ENTRY_BYTES)?; + // A proxy met again on the chain records each position once. + if let Some(pos) = pos.filter(|&pos| !proxy_positions.contains(&(o, pos))) { + held.add(self, SOURCE_ENTRY_BYTES.saturating_add(KEY_ENTRY_BYTES))?; + proxy_positions.insert((o, pos)); positions.push(pos); } } held.add(self, LISTED_ENTRY_BYTES)?; - positions.sort_unstable(); - positions.dedup(); cur = self.get_prototype_of(o)?; let prototype = cur.filter(|&p| self.is_proxy(p)); - listed.insert(o, Listed { prototype, positions }); + // A proxy met again on the chain keeps the names its earlier visits listed. + let entry = listed.entry(o).or_insert_with(|| Listed { prototype, positions: Vec::new() }); + entry.prototype = prototype; + entry.positions.append(&mut positions); if let Some(root) = self.temp_roots.get_mut(slot) { *root = cur.map_or(Value::Undefined, Value::Object); } @@ -3438,6 +3442,12 @@ impl Interp { } cur = obj.proto; } + // Sorted once after the walk, for the iterator's binary search. + for entry in listed.values_mut() { + entry.positions.sort_unstable(); + entry.positions.dedup(); + entry.positions.shrink_to_fit(); + } Ok((out, listed)) } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 8a0b1fec1f..9f42ac53e5 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1901,6 +1901,23 @@ fn for_in_visits_a_name_from_a_prototype_trap_that_returns_a_new_proxy_each_time ); } +#[test] +fn for_in_keeps_the_names_a_proxy_listed_before_it_returns_itself_as_its_prototype() { + // The first visit lists `x`; the proxy is its own prototype once, and the second visit lists + // nothing. The name from the first visit is still visited. + truth( + "var keysCalls = 0, protoCalls = 0; + var p = new Proxy({}, { + ownKeys: function () { return keysCalls++ === 0 ? ['x'] : []; }, + getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; }, + getPrototypeOf: function () { return protoCalls++ === 0 ? p : null; } + }); + var seen = []; + for (var name in p) seen.push(name); + seen.join() === 'x'", + ); +} + #[test] fn for_in_matches_nested_fresh_wrappers_to_their_prototype_lookups() { truth_collecting( From 12355cb52994d0fdbfd236bd92772d2f324ff682 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:42:17 -0800 Subject: [PATCH 57/60] xtask: test-lint fails on a hit of any rule in the changed lines all-unguarded, only-weak, exit-status-only, no-assertion, early-return, env-gate-unset, census, mirror, constant-echo, fixture-only and exact-pixel only listed their hits before. Their hits on changed lines and tests now fail the check like the other rules. A `// test-lint: allow ` comment still exempts a hit, and hits on unchanged lines still do not fail. A never-run test that builds on macOS or Windows is still listed without failing, since it runs locally on that platform. Docs: docs/development.md. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 52 ++++++++++++++++++++++-------------------- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/docs/development.md b/docs/development.md index 77e4b736a5..0e528cdab4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a hit of any of its rules: an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`), a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status (`exit-status-only`), a test with no assertion and no asserting helper (`no-assertion`), a silent early `return` on a value from the code under test (`early-return`), an environment variable that no CI leg sets (`env-gate-unset`), and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 44d73697e2..7bf34a56be 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -82,9 +82,9 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason`, `sleep`, -//! `reads-source` and `never-run` (except a test that builds on macOS or Windows) in the lines and -//! tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on a hit of any rule in the lines and tests changed since a base, +//! except a `never-run` test that builds on macOS or Windows, which it lists without failing. The +//! base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -223,11 +223,6 @@ impl Rule { } } - /// Whether a hit on a changed line fails the command. The other rules only report. - pub fn fails(self) -> bool { - matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep | Rule::ReadsSource | Rule::NeverRun) - } - fn from_id(id: &str) -> Option { Rule::ALL.into_iter().find(|r| r.id() == id) } @@ -256,14 +251,15 @@ pub struct Hit { /// allow comment there does not exempt it. pub gates: Vec, /// A `never-run` hit on a test that builds on macOS or Windows, which CI does not test on: it is - /// listed with the report-only rules. + /// listed without failing the check. pub report_only: bool, } impl Hit { - /// Whether the hit fails the check when it is on a changed line. + /// Whether the hit fails the check when it is on a changed line: every hit does, except a + /// `never-run` test that builds on macOS or Windows. fn fails(&self) -> bool { - self.rule.fails() && !self.report_only + !self.report_only } fn show(&self) -> String { @@ -555,7 +551,7 @@ fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), let (failing, reported): (Vec<&Hit>, Vec<&Hit>) = counted.iter().partition(|h| h.fails()); if !reported.is_empty() { println!( - "test-lint: {} hit(s) of report-only rules in the lines changed since {base} (they do not fail the check):\n {}", + "test-lint: {} hit(s) on tests that build only on macOS or Windows in the lines changed since {base} (run them there; they do not fail the check):\n {}", reported.len(), listing(&reported).join("\n ") ); @@ -6159,8 +6155,11 @@ mod tests { } #[test] - fn census_is_report_only() { - assert!(!Rule::Census.fails()); + fn census_fails_the_check() { + let census = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.name.starts_with('a'));\n }\n}\n"; + let hits = lint_file("crates/x/src/tests.rs", census, &ctx()); + assert_eq!(hits.iter().map(|h| h.rule).collect::>(), [Rule::Census]); + assert!(finish(&hits, 0, 1, "base").is_err(), "census fails the check"); assert_eq!(Rule::from_id("census"), Some(Rule::Census)); } @@ -7284,23 +7283,26 @@ mod tests { } #[test] - fn only_failing_rules_fail_the_check() { - let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); - assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep", "reads-source", "never-run"]); + fn every_rule_fails_the_check() { let ios = "#[cfg(target_os = \"ios\")]\n#[test]\nfn ios() {\n assert_eq!(f(), 1);\n}\n"; assert!(finish(&lint_file("crates/x/src/tests.rs", ios, &ctx()), 0, 1, "base").is_err(), "never-run fails the check"); let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n"; + let silent = "#[test]\nfn silent() {\n f();\n}\n"; let hits_of = |src: &str| lint_file("crates/x/src/tests.rs", src, &ctx()); - assert_eq!(finish(&hits_of(unguarded), 0, 1, "base"), Ok(()), "all-unguarded only reports"); - assert_eq!(finish(&hits_of(weak), 0, 1, "base"), Ok(()), "only-weak only reports"); - let all = hits_of(&format!("{weak}{unguarded}{skipped}")); - assert_eq!(all.len(), 3); - let Err(message) = finish(&all, 0, 1, "base") else { panic!("ignore-without-reason fails the check") }; - assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); - assert!(message.contains("[ignore-without-reason] `skipped`"), "{message}"); - assert!(!message.contains("[only-weak]") && !message.contains("[all-unguarded]"), "{message}"); + assert!(finish(&hits_of(unguarded), 0, 1, "base").is_err(), "all-unguarded fails the check"); + assert!(finish(&hits_of(weak), 0, 1, "base").is_err(), "only-weak fails the check"); + assert!(finish(&hits_of(silent), 0, 1, "base").is_err(), "no-assertion fails the check"); + let all = hits_of(&format!("{weak}{unguarded}{skipped}{silent}")); + assert_eq!(all.len(), 4); + let Err(message) = finish(&all, 0, 1, "base") else { panic!("the hits fail the check") }; + assert!(message.starts_with("4 test-lint hit(s)"), "{message}"); + for listed in ["[only-weak] `weak`", "[all-unguarded] `all`", "[ignore-without-reason] `skipped`", "[no-assertion] `silent`"] { + assert!(message.contains(listed), "{listed} in {message}"); + } + let allowed = "#[test]\n// test-lint: allow only-weak the value is random\nfn weak() {\n assert!(f().is_ok());\n}\n"; + assert_eq!(finish(&hits_of(allowed), 0, 1, "base"), Ok(()), "an allow with a reason exempts the test"); assert_eq!(finish(&[], 3, 1, "base"), Ok(())); } From b727487d80ee71fc46c5f1a8eeeacc703ebe5523 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:00:53 -0800 Subject: [PATCH 58/60] Docs: pathItems.removeAll() reports hidden or locked paths first pathItems.removeAll() throws "cannot delete hidden or locked paths" when any path is hidden or locked or is inside a hidden or locked object, and only otherwise "cannot delete objects on a locked artboard". Both messages end with a colon and up to 20 path ids. docs/mcp.md now says so in both places that describe removeAll(). --- docs/mcp.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 17f142733a..32ed9d1a27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3367,8 +3367,9 @@ through `$`: - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `[name]` (read as `pageItems["name"]` is read), `index(key)`, - `getByName(name)`, `removeAll()` (when any path is on a locked artboard, it throws - `cannot delete objects on a locked artboard` and deletes nothing), `add()` (a path with no points, from `path.create`, painted as new art; when new + `getByName(name)`, `removeAll()` (it deletes nothing and throws `cannot delete hidden or locked paths` when any path is + hidden or locked or is inside a hidden or locked object, and otherwise `cannot delete objects on a locked artboard` + when any path is on a locked artboard; each message is followed by a colon and the ids of up to 20 of those paths), `add()` (a path with no points, from `path.create`, painted as new art; when new art has no fill and no stroke, the path has neither), and the shape creators `rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`, @@ -3444,8 +3445,10 @@ through `$`: `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard throws - `Cannot edit` with nothing changed, and `pathItems.removeAll()` when any path is on a locked artboard throws - `cannot delete objects on a locked artboard` and deletes nothing. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or + `Cannot edit` with nothing changed. `pathItems.removeAll()` deletes nothing and throws an error when any path is + hidden or locked or is inside a hidden or locked layer, group, compound path or other object (`cannot delete hidden or locked paths`), and otherwise + when any path is on a locked artboard (`cannot delete objects on a locked artboard`), each followed by a colon and + the ids of up to 20 of those paths. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops are not available yet. From ff165a7ec29d2342709cf0fcd2a68ba3718199b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:10:45 -0800 Subject: [PATCH 59/60] JavaScript: descriptor bags keep ECMAScript key order; Symbol hooks need ES2015 Object.defineProperties, Object.create, seal and freeze read an ordinary object's own names in ECMAScript order (array indices ascending first) in an ES2015 run, through proxies without an ownKeys trap too; without the option they keep the order for-in visits. concat reads Symbol.isConcatSpreadable and with scopes read Symbol.unscopables only in an ES2015 run, so a Symbol set by an earlier run does not change code run without the option. Tests: the host-function proxy refusal checks the throw and that neither the host function nor the trap ran; the bound-constructor test sets the custom prototype before constructing. --- crates/js/src/builtins/array.rs | 5 ++- crates/js/src/interp.rs | 5 ++- crates/js/src/proxy.rs | 9 +++-- crates/js/src/proxy_tests.rs | 59 +++++++++++++++++++++++++++++---- 4 files changed, 66 insertions(+), 12 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 48dfe1832a..0f45f1cb50 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -389,7 +389,10 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult let mut n = 0u64; for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) { interp.use_fuel()?; - let override_spread = match (e.as_object(), interp.well_known(|w| &w.is_concat_spreadable)) { + // Code run without the ECMAScript 2015 option reads no such Symbol, even in a realm + // that has it from an earlier run. + let spreadable = if interp.options.es2015 { interp.well_known(|w| &w.is_concat_spreadable) } else { None }; + let override_spread = match (e.as_object(), spreadable) { (Some(_), Some(sym)) => interp.get_value_sym(&e, &sym)?, _ => Value::Undefined, }; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 2aa5c933c9..206f7b93c7 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1634,7 +1634,10 @@ impl Interp { if !self.scope_has(object, name)? { return Ok(false); } - if with_this && let Some(sym) = self.well_known(|w| &w.unscopables) { + if with_this + && self.options.es2015 + && let Some(sym) = self.well_known(|w| &w.unscopables) + { let blocked = self.get_value_sym(&Value::Object(object), &sym)?; if let Value::Object(o) = blocked { let value = self.rooted(&[Value::Object(o)], |i| i.get_from(o, name, &Value::Object(o)))?; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index e709cfd808..b9bf04e87a 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -441,12 +441,15 @@ impl Interp { } /// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]: - /// one `ownKeys` trap call for a proxy. + /// one `ownKeys` trap call for a proxy. With [`crate::Options::es2015`] the names come in + /// ECMAScript order (array indices ascending first), through proxies without an `ownKeys` + /// trap too; without it they come in the order `for-in` visits them. pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + let ecma_order = self.options.es2015; if self.is_proxy(id) { - return self.proxy_own_keys(id, false); + return self.proxy_own_keys(id, ecma_order); } - let mut keys = self.own_keys(id)?; + let mut keys = if ecma_order { self.ecma_own_keys(id)? } else { self.own_keys(id)? }; keys.syms = self.own_symbols(id)?; keys.held.add(self, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; Ok(keys) diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index efb6bb78e8..09ffb4b7a3 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -852,6 +852,38 @@ fn concat_honors_proxy_spreadability_overrides() { type_errors(&["var p = Proxy.revocable([], {}); p.revoke(); [].concat(p.proxy)"]); } +#[test] +fn spreadability_and_unscopables_kept_from_an_earlier_run_apply_only_with_the_option() { + let mut realm = es(); + let setup = "var a = [1, 2]; a[Symbol.isConcatSpreadable] = false; + var o = { x: 'own' }; o[Symbol.unscopables] = { x: true }; var x = 'outer'; true"; + assert_eq!(realm.run(setup), Ok(JsValue::Bool(true))); + realm.set_es2015(false); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 2 && c[0] === 1 && w === 'own'"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 1 && c[0] === a && w === 'outer'"), Ok(JsValue::Bool(true))); +} + +#[test] +fn define_properties_defines_array_index_keys_in_ascending_order() { + truth( + "var log = [], bag = {}; bag.b = { value: 0 }; bag[2] = { value: 2 }; bag[1] = { value: 1 }; + var p = new Proxy({}, { defineProperty: function (t, k, d) { log.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(p, bag); + var wrapped = [], q = new Proxy({}, { defineProperty: function (t, k, d) { wrapped.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(q, new Proxy(bag, {})); + log.join() === '1,2,b' && wrapped.join() === '1,2,b'", + ); + // Without the option, descriptors are read in the order for-in visits the names. + let mut realm = Realm::new(); + let src = "var order = [], bag = {}; bag.b = 0; bag[2] = 0; bag[1] = 0; + var seen = [], descs = {}; + for (var k in bag) { order.push(k); (function (k) { Object.defineProperty(descs, k, { enumerable: true, get: function () { seen.push(k); return { value: 0 }; } }); })(k); } + Object.defineProperties({}, descs); + seen.join() === order.join()"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); +} + #[test] fn typed_array_statics_construct_through_proxy_receivers() { truth_collecting( @@ -1527,12 +1559,23 @@ fn a_host_function_refuses_a_proxy_and_names_the_argument() { } } assert!(seen.borrow().is_empty(), "the host function did not run"); - // The traps did not run either. + // The same argument with a trap is refused too, before the host function or the trap runs. let mut realm = es(); - let f: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + let calls = Rc::new(RefCell::new(0usize)); + let counter = calls.clone(); + let f: HostFunction = Rc::new(move |_| { + *counter.borrow_mut() += 1; + Ok(Data::Undefined) + }); realm.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); - let r = realm.run("var ran = false; try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } catch (e) {} ran"); - assert_eq!(r, Ok(JsValue::Bool(false))); + let r = realm.run( + "var ran = false, threw = false; + try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } + catch (e) { threw = e instanceof TypeError; } + threw && !ran", + ); + assert_eq!(r, Ok(JsValue::Bool(true))); + assert_eq!(*calls.borrow(), 0, "the host function did not run"); } #[test] @@ -2269,13 +2312,15 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { #[test] fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { truth( - "var B = Map.bind(null, [[1, 7]]), P = new Proxy(B, {}), Q = new Proxy(P, {}); + "var B = Map.bind(null, [[1, 7]]), proto = Object.create(Map.prototype); + Object.defineProperty(B, 'prototype', { value: proto }); + var P = new Proxy(B, {}), Q = new Proxy(P, {}); var a = new P(), b = new Q(), c = Reflect.construct(Q, []); var R = new Proxy(Q.bind(null), {}), d = new R(); var U = new Proxy(Uint8Array.bind(null, [7, 8]), {}), u = new U(); - Object.defineProperty(B, 'prototype', { value: Map.prototype }); a.get(1) === 7 && b.get(1) === 7 && c.get(1) === 7 && d.get(1) === 7 && - Object.getPrototypeOf(a) === Map.prototype && u.length === 2 && u[1] === 8 && + Object.getPrototypeOf(a) === proto && Object.getPrototypeOf(b) === proto && Object.getPrototypeOf(c) === proto && + Object.getPrototypeOf(d) === Map.prototype && u.length === 2 && u[1] === 8 && type_error(function () { class Child extends P {} new Child(); })", ); } From 5594da577bfcfbc3aaff8e23b30ccac151d56e59 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:09:47 -0800 Subject: [PATCH 60/60] xtask: test-lint census rule ends tail assignments at their block and tells closure locals from captures An assignment that ends a block without a semicolon (`{ input = c }`) now makes its alias at the block's close instead of after the next statement. A `let` inside a move closure, or one of its parameters, now counts as a local binding: an assignment to it ends the alias as it does outside a closure. Assignments to outer captures are still skipped. A closure stored with `let` in `Some`, `Ok`, `Err`, `Box::new`, `Rc::new` or `Arc::new` and never used again does not run, so its assignments no longer end an alias. A closure passed to any other call may run and still ends it. An async closure called where it is written now runs when the call is passed straight to `block_on` (a trailing comma included), unless the `block_on` sits inside another closure. --- xtask/src/test_lint.rs | 122 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 111 insertions(+), 11 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 19c8bf3c8d..418cc75b1f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1843,7 +1843,8 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { for (at, assigned) in steps { if let Some(eq) = assigned { let name = String::from_utf8_lossy(b[at..eq].trim_ascii_end()).into_owned(); - let end = statement_end(&b[..to], eq); + // A block's tail (`{ input = c }`) ends at the block's close. + let end = statement_end(&b[..to], eq).min(block_close(b, at)); let until = words(b, b"let", from, at) .into_iter() .filter(|&l| block_close(b, l) > at) @@ -1859,7 +1860,7 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { .map_or(to, |(_, until)| until); // Assignments in move closures leave outer bindings unchanged. Assignments in async // blocks or uncalled closures do not run; conditional assignments do not make aliases. - if in_move_closure(b, from, to, at) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { + if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { continue; } if live(value_start(eq, end), end, &derived, &shadows) { @@ -2297,7 +2298,19 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b.get(call) != Some(&b'(') { return false; } - if !asynchronous { + // An async closure's future runs when it is passed straight to `block_on` or awaited. A `|` + // before `block_on` may open a closure around it (`let _saved = || block_on(…);`) that + // never runs. + let outer = (stmt..open.saturating_sub(1)).rev().find(|&i| !b[i].is_ascii_whitespace()); + let blocked = matching(b, call).is_some_and(|call_close| { + outer.is_some_and(|o| { + b[o] == b'(' + && !b[stmt..o].contains(&b'|') + && b[..o].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && matching(b, o).is_some_and(|c| matches!(b[call_close + 1..c].trim_ascii(), b"" | b",")) + }) + }); + if !asynchronous || blocked { return true; } let next = matching(b, call).map_or(b.len(), |c| skip_ws(b, c + 1)); @@ -2400,8 +2413,9 @@ fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { }) } -/// Whether `start` lies in the block or expression body of a move closure. -fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { +/// Whether `start` lies in the block or expression body of a move closure that captures `name`: +/// neither the closure's parameters nor a `let` in its body before `start` binds `name`. +fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> bool { words(b, b"move", from, start).into_iter().any(|at| { let pipe = skip_ws(b, at + 4); if b.get(pipe) != Some(&b'|') { @@ -2417,12 +2431,22 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize) -> bool { until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 }; } } - body <= start && start < until + let inside = body <= start && start < until; + let binds = |text: &[u8]| pattern_names(&String::from_utf8_lossy(text)).any(|n| n == name); + let local = inside + && words(b, b"let", body, start).into_iter().any(|l| { + block_close(b, l) > start + && (l + 3..start) + .find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + .is_some_and(|eq| binds(&b[l + 3..eq])) + }); + inside && !binds(&b[pipe + 1..end]) && !local }) } /// Whether `start` lies in the block body of a closure bound with `let` in `b[from..to]` -/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds. +/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds, or of +/// a closure that a `let` stores without a call ([`stored_closure`]). fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { let mut depth = 0usize; for i in (from..start).rev() { @@ -2435,11 +2459,15 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); - let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue }; - let Some(name) = pattern_names(binding).last() else { continue }; - let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); let close = matching(b, i).unwrap_or(to); - if !closure_calls(b, &name, bound, close, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, active)) + let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); + let stored = binding.is_none() && stored_closure(b, head, close, to); + let Some(name) = binding.and_then(|binding| pattern_names(binding).last()).or_else(|| stored.then(String::new)) else { continue }; + let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); + if stored + || !closure_calls(b, &name, bound, close, to, asynchronous) + .into_iter() + .any(|at| runs_with_assertion_within(b, from, to, at, active)) { return true; } @@ -2450,6 +2478,28 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & false } +/// Whether the closure whose block body ends at `close`, with `head` the text before its +/// parameters, is the only argument of `Some`, `Ok`, `Err`, `Box::new`, `Rc::new` or `Arc::new` in +/// a `let` initializer (`let _saved = Some(|| { … });`) whose names `b[..to]` never uses again, so +/// nothing can call it. A closure passed to any other call, a drop guard's included, may run there. +fn stored_closure(b: &[u8], head: &str, close: usize, to: usize) -> bool { + let Some(callee_end) = head.strip_suffix('(').map(str::trim_end) else { return false }; + let path_len = callee_end.bytes().rev().take_while(|&c| is_ident(c) || c == b':').count(); + let (rest, path) = callee_end.split_at(callee_end.len() - path_len); + let mut segments = path.rsplit("::"); + let last = segments.next().unwrap_or_default(); + let owner = segments.next().unwrap_or_default(); + let constructor = matches!(last, "Some" | "Ok" | "Err") || (last == "new" && matches!(owner, "Box" | "Rc" | "Arc")); + let Some(binding) = rest.trim_end().strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { return false }; + let paren = skip_ws(b, close + 1); + let semi = skip_ws(b, paren + 1); + constructor + && binding.starts_with(char::is_whitespace) + && b.get(paren) == Some(&b')') + && b.get(semi) == Some(&b';') + && pattern_names(binding).all(|n| words(b, n.as_bytes(), semi, to).is_empty()) +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -9254,6 +9304,36 @@ mod tests { [], "an assignment to a move capture leaves the outer alias unchanged" ); + assert_eq!( + census("let mut input = fallback(); { input = c } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment that ends a block without a semicolon makes an alias there" + ); + assert_eq!( + census("let mut input = fallback(); { input = c; } app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment that ends with a semicolon in a block makes an alias" + ); + assert_eq!( + census("let run = move || { let mut input = c; input = fallback(); app.run(input); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment to a binding declared in a move closure ends its alias" + ); + assert_eq!( + census("let mut input = c; let _saved = Some(|| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in a closure stored in a call argument does not end an alias" + ); + assert_eq!( + census("let mut input = c; let _ = Some(input).map(|_| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure passed to a call that may run it ends an alias" + ); + assert_eq!( + census("let mut input = c; { let _guard = RunOnDrop(|| { input = fallback(); }); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure kept by another type, which may run it, ends an alias" + ); } #[test] @@ -9316,6 +9396,26 @@ mod tests { "an async closure called where it is written only makes a future" ); assert_eq!(census("assert!((async || app.run(c))().await.is_ok());"), [], "an awaited async closure called where it is written runs"); + assert_eq!( + census("let _ = block_on((async || app.run(c))()); assert!(menu(c).is_some());"), + [], + "an async closure called where it is written and passed to block_on runs" + ); + assert_eq!( + census("let _ = block_on((async || app.run(c))(),); assert!(menu(c).is_some());"), + [], + "a trailing comma after the future passed to block_on" + ); + assert_eq!( + census("let _ = wrap((async || app.run(c))()); assert!(menu(c).is_some());"), + [(2, "census")], + "an async closure called where it is written and passed to another call does not run" + ); + assert_eq!( + census("let _saved = || block_on((async || app.run(c))()); assert!(menu(c).is_some());"), + [(2, "census")], + "block_on in an uncalled closure does not run the async closure" + ); assert_eq!( census("let _saved = Some(|| { app.run(c) }); assert!(menu(c).is_some());"), [(2, "census")],