diff --git a/Cargo.lock b/Cargo.lock index b6bdcc0afe..edef276a56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1262,6 +1262,7 @@ dependencies = [ "craft-browse", "craft-cms", "craft-color-ui", + "craft-control", "craft-dialogs", "craft-draw", "craft-font-catalog", @@ -1304,6 +1305,16 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-appkit" version = "0.1.0" @@ -1441,8 +1452,13 @@ name = "craft-control" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ + "craft-ai-agents", + "craft-atomic", "craft-control-protocol", + "craft-flags", "craft-platform", + "dirs", + "log", "serde", "serde_json", ] @@ -1570,6 +1586,16 @@ name = "craft-eps" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +dependencies = [ + "craft-atomic", + "dirs", + "toml_edit", +] + [[package]] name = "craft-font-catalog" version = "0.1.0" @@ -8699,6 +8725,7 @@ dependencies = [ name = "vectorcraft-cli" version = "0.25.1" dependencies = [ + "craft", "craft-dwg", "log", "objc2-core-foundation", diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index f3115d0779..fc781c31c0 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true } vectorcraft-text = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`). +craft = { workspace = true, features = ["automation-agents"] } # `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this # process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT), @@ -54,6 +56,7 @@ serde_json = { workspace = true } # The files of other crates that this crate compiles or its tests read, for CI's test selection. [package.metadata.craft] reads = [ + "apps/vectorcraft/src/agent_settings.rs", "apps/vectorcraft/src/mac_fonts.rs", "apps/vectorcraft/src/prefs_dir.rs", "apps/vectorcraft/src/profile.rs", diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index dd36a5e573..8855d3f9e3 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -2,7 +2,7 @@ //! //! ```text //! vectorcraft-cli --safe-mode SUBCOMMAND ... -//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... +//! vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... //! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] //! vectorcraft-cli commands //! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] @@ -39,6 +39,10 @@ macro_rules! out { }}; } +/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the +/// closed-app choice and the agent folders the app saved. +#[path = "../../vectorcraft/src/agent_settings.rs"] +mod agent_settings; /// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts. #[cfg(target_os = "macos")] #[path = "../../vectorcraft/src/mac_fonts.rs"] @@ -56,9 +60,11 @@ mod system_fonts; #[path = "../../vectorcraft/src/windows_cores.rs"] mod windows_cores; +use craft::automation::agents::WhenAppClosed; use serde_json::{Value, json}; use vectorcraft_engine::file_access::{self, AutomationRoots}; -use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server}; +use vectorcraft_mcp::agents::{LiveBackend, LiveConfig}; +use vectorcraft_mcp::{Backend, Headless, Remote, Server}; /// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as /// ripgrep does; any other write error is reported. @@ -79,9 +85,18 @@ USAGE: Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and does not take --connect. - vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants] - Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979 - (vectorcraft --control 7979), falling back to a headless in-process session. + vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants] + Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI + agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection + file the window publishes in the settings folder: no port or token to configure, and an app + opened after the session started is found too. Otherwise the call runs in a session without + a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI + Integrations applies (open VectorCraft, a session without a window in the agent folders, or + an error); --when-closed overrides it. Files of the open window's agent requests stay in the + agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the + agent_folders tool names them. --headless always runs without a window. + --connect ADDR (deprecated, removed in a later release) drives an app started with + vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN. --automation-read-root / --automation-write-root confine the files the agent's commands read (open, place, relink, library loads…) and write (save, export, package, library saves…) to DIR, links followed; each may be given more than once, a path inside any of its folders being @@ -286,6 +301,20 @@ fn with_stores(mut h: Headless) -> Headless { h } +/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed` +/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with +/// the user's stores, or confined to the agent folders without them. +fn live_config(dir: std::path::PathBuf, when_closed: Option) -> LiveConfig { + let mut cfg = LiveConfig::new(dir, agent_settings::read_settings); + cfg.when_closed = when_closed; + cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE)); + cfg.headless = Box::new(|roots| match roots { + Some(roots) => Headless::with_document().with_automation_roots(Some(roots)), + None => with_stores(Headless::with_document()), + }); + cfg +} + /// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`). fn accepting_grants(mut h: Headless, allow: bool) -> Headless { if allow { @@ -294,26 +323,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless { h } -/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own -/// plug-ins, so `--connect` is refused and the default does not connect. +/// The stderr line `mcp --connect` prints: the flag works for one more release. +const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents"; + +/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's +/// switch), found through its connection file on every tool call, otherwise a headless session +/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and +/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless. +/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated). fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { - if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) { + if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) { return help(); } let mut connect: Option = None; let mut headless = false; + let mut when_closed: Option = None; let mut allow_grants = false; let (mut read_roots, mut write_roots): (Vec, Vec) = (vec![], vec![]); let mut it = args.iter(); while let Some(a) = it.next() { // The roots also come as `--flag=DIR`, as the other Craft apps take them. let (flag, inline) = match a.split_once('=') { - Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())), + Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())), _ => (a.as_str(), None), }; match flag { "--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?), "--headless" => headless = true, + "--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?), "--allow-plugin-grants" => allow_grants = true, "--automation-read-root" | "--automation-write-root" => { let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?; @@ -334,6 +371,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { if safe_mode && connect.is_some() { return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control `".into()); } + let when_closed = match when_closed.as_deref() { + None => None, + Some(choice) => { + let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?; + if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) { + return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into()); + } + Some(parsed) + } + }; let read: Vec<&Path> = read_roots.iter().map(Path::new).collect(); let write: Vec<&Path> = write_roots.iter().map(Path::new).collect(); let roots = AutomationRoots::new(&read, &write)?; @@ -349,13 +396,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { } else if headless || safe_mode || allow_grants { Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants)) } else if let Some(addr) = connect { + eprintln!("{CONNECT_DEPRECATED}"); // Explicit address: fail loudly if the app isn't there. let token = vectorcraft_mcp::control_token()?; Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?) } else { - // No token or no app listening: the headless session answers instead. - match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) { - Some(r) => Box::new(r), + match prefs_dir::prefs_dir() { + Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))), + // No settings folder (no home folder): no window can be found either, so `--when-closed error` + // refuses rather than answering from a session the agent didn't ask for. + None if when_closed == Some(WhenAppClosed::Error) => { + return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into()); + } None => Box::new(with_stores(Headless::with_document())), } }; diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 0b1c560901..dc96dd69b8 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() { let r = run_in(&config, &[("pdf.preset.list", json!({}))]); assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true)); } + +/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one +/// release but says it is deprecated before it connects. +#[test] +fn mcp_when_closed_and_the_deprecated_connect() { + let fails = |args: &[&str], why: &str| { + let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success() && err.contains(why), "{args:?}: {err}"); + err.into_owned() + }; + fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error"); + fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window"); + fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window"); + let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated"); + assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}"); +} diff --git a/apps/vectorcraft/src/agent_settings.rs b/apps/vectorcraft/src/agent_settings.rs new file mode 100644 index 0000000000..68065aa08b --- /dev/null +++ b/apps/vectorcraft/src/agent_settings.rs @@ -0,0 +1,77 @@ +//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder +//! (`prefs_dir.rs`). The desktop app writes them when they change (`prefs.agents`); `vectorcraft-cli` +//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice +//! and the agent folders. + +use std::io::Read as _; +use std::path::Path; + +use craft::automation::agents::AgentSettings; +use serde_json::Value; + +/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed", +/// "allowAgentControl"}`, the framework's `AgentSettings`. +pub const SETTINGS_FILE: &str = "agents.json"; + +/// The largest settings file read; the settings are a few short strings. +const MAX_SETTINGS_FILE: u64 = 64 * 1024; + +/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read, +/// so neither the app nor the CLI fails over them. One bad value resets only itself. +pub fn read_settings(dir: &Path) -> AgentSettings { + let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() }; + let mut text = String::new(); + if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE { + return AgentSettings::default(); + } + let Ok(Value::Object(saved)) = serde_json::from_str::(&text) else { return AgentSettings::default() }; + let mut settings = AgentSettings::default(); + for (key, value) in saved { + let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue }; + if one.contains_key(&key) { + one.insert(key, value); + if let Ok(next) = serde_json::from_value(Value::Object(one)) { + settings = next; + } + } + } + settings +} + +/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a +/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half. +// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them. +#[allow(dead_code)] +pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?; + let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id())); + std::fs::write(&partial, text)?; + std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| { + let _ = std::fs::remove_file(&partial); + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use craft::automation::agents::WhenAppClosed; + + // Settings saved by the app read back in the CLI, and a damaged file or value never fails it. + #[test] + fn saved_settings_read_back_and_bad_values_reset_alone() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(read_settings(dir.path()), AgentSettings::default()); + let mut settings = AgentSettings::default(); + settings.read_root = "/in".into(); + settings.when_app_closed = WhenAppClosed::Headless; + write_settings(dir.path(), &settings).unwrap(); + assert_eq!(read_settings(dir.path()), settings); + std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap(); + assert_eq!(read_settings(dir.path()), AgentSettings::default()); + std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap(); + let read = read_settings(dir.path()); + assert_eq!(read.when_app_closed, WhenAppClosed::Error); + assert_eq!(read.read_root, ""); + } +} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 193ab5fad4..d772397ce3 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -27,6 +27,7 @@ //! how the window's frames reach the display (`presentation`). #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] +mod agent_settings; mod automation_args; #[cfg(test)] mod build_channel; @@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec, launched: Option<&Listening>) -> Option { + use craft::automation::agents::{AgentSwitch, remove_stale_connection}; + use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn}; + let dir = prefs_dir::prefs_dir()?; + remove_stale_connection(&dir); + let switch = AgentSwitch::watch(LAUNCHER_APP_ID, { + let ctx = ctx.clone(); + move || ctx.request_repaint() + }); + let save_dir = dir.clone(); + let save: SaveFn = Box::new(move |settings| { + agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display())) + }); + let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION")); + let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save); + // The port it listens on (the one the system picked for `--control 0`), none when it couldn't. + Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents }) +} + /// The control channel's port, and the token's notice with the token itself. type ControlChannel = (Option, Option<(String, String)>); @@ -1056,6 +1081,12 @@ fn main() -> std::process::ExitCode { } } } + if !nightly + && prefs_enabled() + && let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref()) + { + app = app.with_agents(agents); + } #[cfg(target_os = "macos")] { open_documents::set_ui(&cc.egui_ctx); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 8fe914a87f..0c8831c9ab 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -93,7 +93,7 @@ impl AutomationRoots { /// Roots that grant no access of either kind: inside [`confine`] with them, every path a /// command reads or writes is refused. - pub(crate) fn none() -> Arc { + pub fn none() -> Arc { Arc::new(Self { read: Vec::new(), write: Vec::new() }) } @@ -124,6 +124,11 @@ impl AutomationRoots { if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) } } + /// The folders of the kind `access`, as people read them. + pub fn folders(&self, access: Access) -> impl Iterator { + self.of(access).iter().map(|r| r.shown.as_path()) + } + /// The roots of the kind `access`. fn of(&self, access: Access) -> &[Root] { match access { diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index b5544b958c..59dd3522de 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -22,7 +22,9 @@ vectorcraft-format = { workspace = true } vectorcraft-tools = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } -craft = { workspace = true, features = ["automation"] } +# `automation-agents` and `control-agents`: plain `mcp` finds the open window through the ArtCraft +# Launcher's switch and the connection file, with the shared live client and the agent folders. +craft = { workspace = true, features = ["automation", "automation-agents", "control-agents"] } serde_json = { workspace = true } log = { workspace = true } diff --git a/crates/mcp/src/agents.rs b/crates/mcp/src/agents.rs new file mode 100644 index 0000000000..8f7a8bc8b4 --- /dev/null +++ b/crates/mcp/src/agents.rs @@ -0,0 +1,336 @@ +//! Agents in the open window: the CLI's side of the ArtCraft Launcher's switch. +//! +//! While the launcher's *Settings › AI agents* switch names VectorCraft (behind the suite's `AI-MCP` +//! flag), the desktop app serves its control channel on loopback and publishes where in its +//! settings folder (`craft::automation::agents::AgentLink`, `vectorcraft_ui_egui::agents`). Plain +//! `vectorcraft-cli mcp` reads that file on every tool call ([`LiveBackend`], over the shared +//! `craft::automation::agents::Live`), so an MCP client's configuration holds no port and no token, +//! and the app may start, quit or move to another port while the client stays connected. Adding +//! VectorCraft to MCP clients is the launcher's job (one entry for every Craft app); VectorCraft +//! writes no client configuration. +//! +//! What is VectorCraft's here: its launcher id, its window client ([`Window`], which makes the app +//! prove it holds the token before it proves it holds it too) and its headless session +//! ([`Headless`] with the agent folders as automation roots). + +use std::cell::RefCell; +use std::io::{BufRead, BufReader, ErrorKind, Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use craft::automation::agents::{self as shared, AgentSettings, Consent, HeadlessFolders, Route, WhenAppClosed}; +use craft::automation::client::{CALL_TIMEOUT, CONNECT_TIMEOUT, MAX_REPLY_BYTES}; +use craft::automation::security::{self, ProofRole}; +use craft::control::agents::{AgentFolders, folders_answer}; +use serde_json::{Value, json}; +use vectorcraft_engine::file_access::{Access, AutomationRoots}; + +use crate::backend::Backend; +use crate::headless::Headless; + +/// The id the ArtCraft Launcher's app list names VectorCraft by (its catalog id). +pub const LAUNCHER_APP_ID: &str = "vectorcraft"; +/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/VectorCraft`). +pub const APP_NAME: &str = "VectorCraft"; +/// The desktop app's file name beside the CLI (without `.exe`). +pub const APP_EXE: &str = "vectorcraft"; +/// The method the `agent_folders` tool calls: the folders this session's file commands may use. +pub const FOLDERS_METHOD: &str = "agent.folders"; +/// What a tool that needs the window says in a session without one. +pub const NEEDS_WINDOW: &str = "needs the open VectorCraft window: open VectorCraft with AI agents on (ArtCraft Launcher › Settings › AI agents) and run `vectorcraft-cli mcp` without --headless"; + +/// Whether the person lets agents use VectorCraft now: with the suite's `AI-MCP` flag, the +/// launcher's switch. VectorCraft had no agent consent of its own before the switch, so without +/// the flag agents get a session without a window. +pub fn allowed_now() -> bool { + shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false) +} + +/// The automation roots for `folders`: what a session with these folders may open and save. A kind +/// without a folder is refused, and so is everything when there is no folder at all. +pub fn roots_for(folders: &AgentFolders) -> Result, String> { + let read: Vec<&Path> = folders.read.as_deref().into_iter().collect(); + let write: Vec<&Path> = folders.write.as_deref().into_iter().collect(); + Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none)) +} + +/// The `agent_folders` answer of a headless session confined to `roots` (`None`: not confined). +/// With more than one folder of a kind (`--automation-read-root` given twice), `read_folders` / +/// `write_folders` list them all. +pub(crate) fn headless_folders(roots: Option<&AutomationRoots>) -> Value { + let Some(roots) = roots else { + // A session started without automation roots (`--headless` without them, or with the + // agents switch off) isn't confined: say so rather than claim it has no folders. + return json!({ + "read_folder": null, + "write_folder": null, + "unrestricted": true, + "note": "This session was started without automation roots: its file commands open and save wherever the user can.", + }); + }; + let (read, write): (Vec<&Path>, Vec<&Path>) = (roots.folders(Access::Read).collect(), roots.folders(Access::Write).collect()); + let mut folders = AgentFolders::default(); + folders.read = read.first().map(|p| p.to_path_buf()); + folders.write = write.first().map(|p| p.to_path_buf()); + let mut answer = folders_answer(&folders); + for (key, all) in [("read_folders", &read), ("write_folders", &write)] { + if all.len() > 1 + && let Some(o) = answer.as_object_mut() + { + o.insert(key.into(), json!(all.iter().map(|p| p.to_string_lossy()).collect::>())); + } + } + answer +} + +// ---- The open window --------------------------------------------------------------------------- + +/// How often a call waiting for its reply looks whether it was cancelled. +const CANCEL_POLL: Duration = Duration::from_millis(100); + +/// One authenticated connection to the open window. The app proves it holds the token first +/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the +/// wire, and a program that took a stale port learns nothing derived from it. +pub struct Window { + addr: SocketAddr, + token: String, + conn: Option<(BufReader, TcpStream)>, + next_id: u64, +} + +impl Window { + /// A client for the window on `127.0.0.1:port` with `token`; connects on the first call. + pub fn new(port: u16, token: String) -> Self { + Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 } + } + + /// Connects and runs the challenge handshake. + pub fn connect(&mut self) -> Result<(), String> { + self.conn = None; + let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?; + stream.set_nodelay(true).ok(); + stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?; + let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream); + let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?; + let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}), false)? + .map_err(|e| format!("{} refused challenge authentication ({e}); the agent token was not used", self.addr))?; + let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned); + let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else { + return Err(format!("{} answered the challenge without a proof; the agent token was not used", self.addr)); + }; + if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) { + return Err(format!("{} could not prove it holds VectorCraft's agent token; nothing was sent to it", self.addr)); + } + let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?; + round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}), false)? + .map_err(|e| format!("VectorCraft refused the agent token: {e}"))?; + self.conn = Some(conn); + Ok(()) + } +} + +/// Sends one request and reads the reply with its `id` (lines for other ids are skipped): `Err` +/// when the connection failed or the call was cancelled while it waited, `Ok(Err)` when the app +/// answered with an error. With `cancellable`, a cancelled MCP call stops waiting. +fn round_trip( + conn: &mut (BufReader, TcpStream), + id: u64, + method: &str, + params: Value, + cancellable: bool, +) -> Result, String> { + let (reader, writer) = conn; + let line = json!({"id": id, "method": method, "params": params}).to_string(); + writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?; + let deadline = Instant::now() + CALL_TIMEOUT; + loop { + let reply = read_line(reader, deadline, cancellable)?; + let v: Value = serde_json::from_slice(&reply).map_err(|e| format!("bad reply from the window: {e}"))?; + if v.get("id").and_then(Value::as_u64) != Some(id) { + continue; + } + return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) { + Ok(v.get("result").cloned().unwrap_or(Value::Null)) + } else { + Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned()) + }); + } +} + +/// One reply line, at most [`MAX_REPLY_BYTES`], read by `deadline`. +fn read_line(reader: &mut BufReader, deadline: Instant, cancellable: bool) -> Result, String> { + let mut line = Vec::new(); + loop { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err("the window did not answer in time".into()); + } + reader.get_ref().set_read_timeout(Some(left.min(CANCEL_POLL))).map_err(|e| e.to_string())?; + let room = (MAX_REPLY_BYTES + 1).saturating_sub(line.len() as u64); + // `read_until` keeps what it read before a timeout, so the line goes on where it stopped. + match reader.by_ref().take(room).read_until(b'\n', &mut line) { + Ok(0) => return Err("the window closed the connection".into()), + Ok(_) if line.ends_with(b"\n") => return Ok(line), + Ok(_) if line.len() as u64 > MAX_REPLY_BYTES => return Err("the window's reply is too long".into()), + Ok(_) => return Err("the window closed the connection".into()), + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { + if cancellable && vectorcraft_engine::cancel::is_cancelled() { + return Err("cancelled".into()); + } + } + Err(e) if e.kind() == ErrorKind::Interrupted => {} + Err(e) => return Err(e.to_string()), + } + } +} + +impl Backend for Window { + fn call(&mut self, method: &str, params: Value) -> Result { + if self.conn.is_none() { + self.connect().map_err(|e| format!("the VectorCraft window is not reachable: {e}; `{method}`: nothing was sent"))?; + } + let id = self.next_id; + self.next_id = self.next_id.wrapping_add(1).max(1); + let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) }; + let cancellable = vectorcraft_engine::cancel::is_cancellable(); + match round_trip(conn, id, method, params, cancellable) { + Ok(answer) => answer, + // Never sent again: the request may have run. The next call reconnects. + Err(e) => { + self.conn = None; + if e == "cancelled" { + return Err(format!( + "the VectorCraft window: `{method}` cancelled; the app may still finish what it was asked, which can't be stopped from here" + )); + } + Err(format!("lost the connection to the VectorCraft window ({e}); `{method}` may or may not have run: inspect state before retrying")) + } + } + } + + fn has_ui(&self) -> bool { + true + } + + fn describe(&self) -> String { + format!("the open VectorCraft window ({})", self.addr) + } +} + +// ---- The live backend -------------------------------------------------------------------------- + +type SharedWindow = Arc>; +/// The headless session stays on the server's thread, as the backend does. +type SharedHeadless = Rc>; + +/// Makes each new headless session (the CLI attaches the user's stores) from its automation roots. +pub type HeadlessMaker = Box>) -> Headless + Send + Sync>; + +/// What plain `vectorcraft-cli mcp` needs to find the window. +pub struct LiveConfig { + /// The app's settings folder: connection file, token file and agent settings. + pub config_dir: PathBuf, + /// Reads the agent settings saved in a settings folder (`agents.json`). + pub read_settings: fn(&Path) -> AgentSettings, + /// Overrides the app's closed-app choice (`--when-closed`). + pub when_closed: Option, + /// The command's folders (`--automation-read-root`, `--automation-write-root`). + pub read_roots: Vec, + pub write_root: Option, + /// Starts the app; `None` when this install can't. + pub launch: Option, + pub launch_timeout: Duration, + /// Whether agents may use the app now ([`allowed_now`]); tests replace it. + pub allowed: fn() -> bool, + /// The default agent folder for an empty folder setting; tests replace it. + pub default_folder: Option, + /// Makes each new headless session. + pub headless: HeadlessMaker, +} + +impl LiveConfig { + /// The settings in `config_dir` as `read_settings` reads them, the launcher's switch, the + /// default agent folder, and a plain headless session with a document. + pub fn new(config_dir: PathBuf, read_settings: fn(&Path) -> AgentSettings) -> Self { + Self { + config_dir, + read_settings, + when_closed: None, + read_roots: Vec::new(), + write_root: None, + launch: None, + launch_timeout: shared::LAUNCH_TIMEOUT, + allowed: allowed_now, + default_folder: craft::control::agents::default_folder(APP_NAME), + headless: Box::new(|roots| Headless::with_document().with_automation_roots(roots)), + } + } +} + +/// Plain `vectorcraft-cli mcp`: every call goes to the open window while the person lets agents +/// use it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup +/// is the shared `craft::automation::agents::Live`; a session that went headless stays headless. +pub struct LiveBackend { + live: shared::Live, + config_dir: PathBuf, + read_settings: fn(&Path) -> AgentSettings, + default_folder: Option, +} + +impl LiveBackend { + pub fn new(cfg: LiveConfig) -> Self { + let LiveConfig { config_dir, read_settings, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } = + cfg; + let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir)); + let connect = |w: &shared::Window| -> Result { + let mut window = Window::new(w.port, w.token.clone()); + window.connect()?; + Ok(Arc::new(Mutex::new(window))) + }; + let make_headless = move |wanted: &HeadlessFolders| -> Result { + let roots = if wanted.read.is_empty() && wanted.write.is_none() { + None + } else { + let read: Vec<&Path> = wanted.read.iter().map(PathBuf::as_path).collect(); + let write: Vec<&Path> = wanted.write.as_deref().into_iter().collect(); + Some(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none)) + }; + Ok(Rc::new(RefCell::new(headless(roots)))) + }; + let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, make_headless); + shared_cfg.when_closed = when_closed; + shared_cfg.read_roots = read_roots; + shared_cfg.write_root = write_root; + shared_cfg.launch = launch; + shared_cfg.launch_timeout = launch_timeout; + shared_cfg.default_folder = default_folder.clone(); + Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder } + } + + /// The folders the open window lets agents use, as the window opens them. + fn window_folders(&self) -> Value { + folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref())) + } +} + +impl Backend for LiveBackend { + fn call(&mut self, method: &str, params: Value) -> Result { + match self.live.resolve()? { + Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()), + Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params), + Route::Headless(h) => h.borrow_mut().call(method, params), + } + } + + fn has_ui(&self) -> bool { + matches!(self.live.resolve(), Ok(Route::Window(_))) + } + + fn describe(&self) -> String { + "the open VectorCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window" + .into() + } +} diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index e73a3d9da5..5bbb455854 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -86,6 +86,12 @@ impl Remote { impl Backend for Remote { fn call(&mut self, method: &str, params: Value) -> Result { + if method == crate::agents::FOLDERS_METHOD { + return Err(format!( + "the app at {} was started with --control, so agent folders don't apply: its own --automation-read-root and --automation-write-root, if given, confine it", + self.addr + )); + } let addr = self.addr.clone(); let client = self.open_client(method)?; // The app can't stop what it runs, but a cancelled call stops waiting for it. diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 593ca61c64..51f7db2955 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -163,13 +163,11 @@ impl Headless { } None if KEYBOARD_ONLY.contains(&id) => { return Err(format!( - "`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, `--connect` included" + "`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, in the open window too" )); } None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => { - return Err(format!( - "`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`" - )); + return Err(format!("`{id}` is a desktop UI command (`ui: true`): it {}", crate::agents::NEEDS_WINDOW)); } None => self.session.check_params(id, params).map_err(|e| e.to_string())?, } @@ -451,9 +449,8 @@ impl Headless { "app.save" => self.save(p), "app.export" => self.export(p), "app.quit" => Ok(Value::Null), - m if m.starts_with("ui.") => { - Err(format!("`{m}` needs the desktop app (start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`)")) - } + crate::agents::FOLDERS_METHOD => Ok(crate::agents::headless_folders(self.roots.as_deref())), + m if m.starts_with("ui.") => Err(format!("`{m}` {}", crate::agents::NEEDS_WINDOW)), other => Err(format!("unknown method `{other}`")), } } diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 7e104e85f2..dfe6bdd67b 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -4,9 +4,15 @@ //! JSON-RPC 2.0, hand-written (no async runtime). The server exposes VectorCraft as a set of MCP //! tools and resources and forwards everything to a [`Backend`]: //! +//! - [`agents::LiveBackend`] (plain `vectorcraft-cli mcp`) sends each call to the open window +//! while the ArtCraft Launcher's switch lets agents use VectorCraft, through the connection file +//! the window publishes ([`agents::Window`]). While agents may not use it, calls go to a +//! [`Headless`] session; while they may but VectorCraft is closed, the closed-app choice of +//! Preferences › AI Integrations (or `--when-closed`) starts the app, uses a headless session in +//! the agent folders, or answers with an error. //! - [`Remote`] talks to a running desktop app through its loopback JSON-lines control channel -//! (`vectorcraft --control 7979`): one `{"id","method","params"}` line in, one -//! `{"id","ok","result"|"error"}` line out. +//! (`vectorcraft --control 7979`, `vectorcraft-cli mcp --connect`, deprecated): one +//! `{"id","method","params"}` line in, one `{"id","ok","result"|"error"}` line out. //! - [`Headless`] hosts an in-process [`vectorcraft_engine::Session`] and implements the same //! control-channel method names itself (rendering screenshots with `vectorcraft-render`), so agents //! can draw and look at the result without a window. @@ -15,6 +21,7 @@ #![forbid(unsafe_code)] #![doc(test(attr(forbid(unsafe_code))))] +pub mod agents; mod backend; mod headless; mod intake; diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 7741d9228f..6e4dc10fba 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -405,7 +405,7 @@ Method: removeWord / dictionary; for this document only, text.spelling.ignoreAll. 4. Prefer those commands over inventing replacements. screenshot if the layout may reflow. -Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); use --connect for the underlines.", +Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); the underlines need the open window.", }, PromptDef { name: "variables-bind", diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 231cbd5f9f..60b27bacbf 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use crate::{Backend, Headless, PROTOCOL_VERSION, Remote, Server, tool_definitions}; +mod agents; mod batchdraw; mod concurrency; mod conventions; @@ -279,10 +280,11 @@ fn tool_schemas_are_valid() { "transform", "create_graph", "text_wrap", + "agent_folders", ] { assert!(names.contains(want), "missing tool {want}"); } - assert_eq!(tools.len(), 33, "parity docs and #6460 expect 33 MCP tools"); + assert_eq!(tools.len(), 34, "parity docs and #6460 expect 34 MCP tools (agent_folders: #10621)"); } /// Headless `command_list` must expose engine commands that a stale release CLI used to omit (#6460). @@ -335,7 +337,7 @@ fn headless_command_list_includes_ui_commands() { } let r = call(&mut s, 40, "command_run", json!({"id": "view.fitArtboard", "params": {}})); assert_eq!(r["isError"], true, "{r}"); - assert!(text_of(&r).contains("--connect"), "{r}"); + assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}"); } /// Desktop commands that the app refuses for every automated request are not offered through @@ -1102,7 +1104,7 @@ fn answer_dialog_needs_the_desktop_app() { let mut s = server(); let r = call(&mut s, 1, "answer_dialog", json!({"action": "confirm"})); assert_eq!(r["isError"], true, "{r}"); - assert!(text_of(&r).contains("needs the desktop app"), "{r}"); + assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}"); } /// How long a fake app waits for [`Remote`] to connect or to send, and how long a test waits for diff --git a/crates/mcp/src/tests/agents.rs b/crates/mcp/src/tests/agents.rs new file mode 100644 index 0000000000..4be7aa0e05 --- /dev/null +++ b/crates/mcp/src/tests/agents.rs @@ -0,0 +1,158 @@ +//! Plain `mcp` in front of the open window (`crate::agents`): the window gets the calls only while +//! agents are allowed and it proves it holds the token; otherwise the closed-app choice applies. + +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use craft::automation::agents::{AgentSettings, Connection, TOKEN_FILE, WhenAppClosed, write_connection}; +use craft::automation::security::{AuthStep, ServerHandshake}; +use serde_json::{Value, json}; + +use super::TempFolder; +use crate::Backend; +use crate::agents::{FOLDERS_METHOD, LiveBackend, LiveConfig}; + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +/// A stand-in for the window's control server holding `token`: it authenticates as the shared +/// server does and answers every request with `{"window": true, "method"}`. The count is of the +/// requests it got after authentication. +fn fake_window(token: &'static str) -> (u16, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let served = Arc::new(AtomicUsize::new(0)); + let count = served.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { return }; + let count = count.clone(); + std::thread::spawn(move || { + let mut writer = stream.try_clone().unwrap(); + let mut handshake = ServerHandshake::new(); + let mut signed_in = false; + for line in BufReader::new(stream).lines() { + let Ok(line) = line else { return }; + let reply = if signed_in { + count.fetch_add(1, Ordering::SeqCst); + let req: Value = serde_json::from_str(&line).unwrap(); + json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}}) + } else { + let (reply, step) = handshake.reply(&line, token); + signed_in = matches!(step, AuthStep::Authenticated); + reply + }; + if writeln!(writer, "{reply}").is_err() { + return; + } + } + }); + } + }); + (port, served) +} + +/// Publishes a window on `port` in the settings folder `dir`, as the app's agents link does, with +/// [`TOKEN`] in its token file. +fn publish(dir: &Path, port: u16) { + let token_file = dir.join(TOKEN_FILE); + std::fs::write(&token_file, TOKEN).unwrap(); + // The client reads only a token its owner alone can read, as the app writes it. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + write_connection(dir, &Connection::new(port, token_file, "VectorCraft test")).unwrap(); +} + +/// A port nothing listens on. +fn closed_port() -> u16 { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +fn settings_headless(_: &Path) -> AgentSettings { + let mut s = AgentSettings::default(); + s.when_app_closed = WhenAppClosed::Headless; + s +} + +fn settings_error(_: &Path) -> AgentSettings { + let mut s = AgentSettings::default(); + s.when_app_closed = WhenAppClosed::Error; + s +} + +fn live(dir: &Path, allowed: fn() -> bool, read_settings: fn(&Path) -> AgentSettings, default_folder: PathBuf) -> LiveBackend { + let mut cfg = LiveConfig::new(dir.to_path_buf(), read_settings); + cfg.allowed = allowed; + cfg.default_folder = Some(default_folder); + LiveBackend::new(cfg) +} + +#[test] +fn plain_mcp_reaches_the_window_while_agents_are_allowed() { + let dir = TempFolder::new("agents-window"); + let (port, served) = fake_window(TOKEN); + publish(&dir, port); + let mut b = live(&dir, || true, settings_headless, dir.file("Agents")); + assert!(b.has_ui()); + let r = b.call("document.inspect", json!({})).unwrap(); + assert_eq!(r["window"], true, "{r}"); + assert!(served.load(Ordering::SeqCst) >= 1); + // The window's folders are the agent folders as the window opens them: the default one here. + let folders = b.call(FOLDERS_METHOD, json!({})).unwrap(); + assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy())); + assert_eq!(folders["write_folder"], folders["read_folder"]); +} + +// With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with +// only the command's folders: the closed-app choice (an error here) is for agents the person let in. +#[test] +fn with_agents_off_plain_mcp_runs_headless() { + let dir = TempFolder::new("agents-off"); + let mut b = live(&dir, || false, settings_error, dir.file("Agents")); + assert!(!b.has_ui()); + let r = b.call("document.inspect", json!({})); + assert!(r.as_ref().is_ok_and(|r| r["window"] != true), "{r:?}"); + assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true); + assert!(!dir.file("Agents").exists(), "the agent folder is made only for agents the person let in"); +} + +#[test] +fn a_window_that_cannot_prove_the_token_gets_nothing() { + let dir = TempFolder::new("agents-bad-token"); + let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); + publish(&dir, port); + let mut b = live(&dir, || true, settings_headless, dir.file("Agents")); + let e = b.call("document.inspect", json!({})).unwrap_err(); + assert!(e.contains("could not prove"), "{e}"); + assert_eq!(served.load(Ordering::SeqCst), 0); +} + +#[test] +fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() { + let dir = TempFolder::new("agents-stale"); + publish(&dir, closed_port()); + let mut b = live(&dir, || true, settings_error, dir.file("Agents")); + let e = b.call("document.inspect", json!({})).unwrap_err(); + assert!(e.contains("isn't running"), "{e}"); + + // Headless: a session without a window, confined to the agent folders. + let mut b = live(&dir, || true, settings_headless, dir.file("Agents")); + assert!(!b.has_ui()); + let folders = b.call(FOLDERS_METHOD, json!({})).unwrap(); + assert_eq!(folders["read_folder"], json!(std::fs::canonicalize(dir.file("Agents")).map(shown).unwrap())); + let outside = dir.file("outside.svg"); + std::fs::write(&outside, r#""#).unwrap(); + let e = b.call("app.open", json!({"path": outside.to_string_lossy()})).unwrap_err(); + assert!(e.contains("outside the read root"), "{e}"); +} + +/// A canonical path as the automation roots show it: without Windows' `\\?\` prefix. +fn shown(p: PathBuf) -> String { + let s = p.to_string_lossy().into_owned(); + s.strip_prefix(r"\\?\").map_or(s.clone(), str::to_owned) +} diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 98267484e0..cc187ea408 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -103,7 +103,7 @@ pub fn tool_definitions() -> Vec { tool( "command_list", "List commands", - "Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id headless needs --connect). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.", + "Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id needs the open window). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.", obj( json!({"filter": string("Case-insensitive id, label or menu substring"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabled_only": {"type":"boolean"}, "brief": {"type":"boolean", "description": BRIEF}}), &[], @@ -161,7 +161,7 @@ pub fn tool_definitions() -> Vec { tool( "list_commands", "List commands", - "List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id run headless needs --connect). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.", + "List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id needs the open window). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.", obj( json!({"filter": string("Case-insensitive substring matched against id, label and menu path (e.g. \"align\", \"Object\")"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabledOnly": {"type": "boolean", "description": "Only commands that can run right now"}, "brief": {"type": "boolean", "description": BRIEF}}), &[], @@ -528,5 +528,6 @@ pub fn tool_definitions() -> Vec { ), tool("undo", "Undo", "Undo the last change (Edit → Undo). redo reapplies it.", empty(), false), tool("redo", "Redo", "Redo the last undone change (Edit → Redo): the change the last undo took back.", empty(), false), + tool(craft::control::agents::FOLDERS_TOOL, "Agent folders", craft::control::agents::FOLDERS_TOOL_DESCRIPTION, empty(), true), ] } diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 752f72b928..80dea79008 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -219,6 +219,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result screenshot(b, a), + craft::control::agents::FOLDERS_TOOL => j(b.call(crate::agents::FOLDERS_METHOD, json!({}))?), "open_file" => { let path = absolute_path(b, req_str(a, "path")?)?; let mut p = json!({"path": path}); diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 1b00199800..22cb308a72 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -11,7 +11,7 @@ pub(super) fn req_str<'a>(a: &'a Args, k: &str) -> Result<&'a str, String> { } /// A file tool's path made absolute against this process's working directory when it goes to the app -/// (`--connect`). Headless, and for an empty path, it is returned as given. +/// (the open window). Headless, and for an empty path, it is returned as given. pub(super) fn absolute_path(b: &dyn Backend, p: &str) -> Result { if p.is_empty() || !b.has_ui() { return Ok(p.to_owned()); @@ -25,13 +25,7 @@ pub(super) fn exec(b: &mut dyn Backend, cmd: &str, params: Value) -> Result Result<(), String> { - if b.has_ui() { - Ok(()) - } else { - Err(format!( - "`{tool}` needs the desktop app: run `vectorcraft --control 7979` and start the server with `vectorcraft-cli mcp --connect 127.0.0.1:7979`" - )) - } + if b.has_ui() { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) } } /// Paint argument → `paint.setFill` / `paint.setStroke` params. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 891f1388c3..9151b62986 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -171,6 +171,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), + ( + "prefs.agents", + "AI Integrations", + "", + "{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences", + ), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), ( "view.refreshMonitorProfile", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index ac7b1fe1a6..fe411e7c59 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -78,7 +78,9 @@ log = { workspace = true } # Floating panels open in OS windows of their own on the desktop; on the web they stay in the page. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The folder picker and the updater are native only (`craft/Cargo.toml`: rfd and getrandom have no wasm build). -craft = { workspace = true, features = ["dialogs", "update"] } +# Agents in the open window (`src/agents.rs`): the ArtCraft Launcher's switch, the link host with its control +# server and the Agents page of Preferences (`automation-agents`), and the default agent folder (`control-agents`). +craft = { workspace = true, features = ["dialogs", "update", "automation-agents", "control-agents"] } # The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in # Cargo.lock with the time-zone crates `clock` uses. chrono = { workspace = true, features = ["clock"] } diff --git a/crates/ui-egui/src/agents.rs b/crates/ui-egui/src/agents.rs new file mode 100644 index 0000000000..4ab629e70a --- /dev/null +++ b/crates/ui-egui/src/agents.rs @@ -0,0 +1,188 @@ +//! Agents in the open window: while the ArtCraft Launcher's *Settings › AI agents* switch names +//! VectorCraft, the window serves its control channel to agents on loopback. +//! +//! The switch, the control server, its token and the connection file `vectorcraft-cli mcp` finds +//! the window by are the framework's (`craft::automation::agents::AgentSwitch` and `AgentLink`). +//! VectorCraft supplies its agent settings (saved by `prefs.agents`), answers the requests with its +//! own control methods ([`crate::control`]) and confines every file they open or save to the agent +//! folders: those set in Preferences › AI Integrations, or `Documents/ArtCraft/Agents/VectorCraft` +//! for an empty one. Without a folder of a kind, that kind of access is refused. + +use std::path::PathBuf; +use std::sync::Arc; + +use craft::automation::ControlChannel; +use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem}; +use craft::ui::runtime::windows::WindowHost; +use serde_json::{Value, json}; +use vectorcraft_engine::file_access::{self, AutomationRoots}; + +use crate::VectorcraftApp; + +/// The id the ArtCraft Launcher's app list names VectorCraft by (its catalog id). +pub const LAUNCHER_APP_ID: &str = "vectorcraft"; +/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/VectorCraft`). +pub const APP_NAME: &str = "VectorCraft"; +/// The Preferences page of the agent settings, and the key they sit under in its draft. +pub const PAGE: &str = "integrations"; +/// The page's title in Preferences, as PhotoCraft names it. +pub const PAGE_TITLE: &str = "AI Integrations"; + +/// Saves the agent settings where `vectorcraft-cli mcp` reads them; `Err` says why it couldn't. +pub type SaveFn = Box Result<(), String>>; + +/// The agents link of the open window. +pub struct Agents { + /// The link; `None` while the launch options (`--control`) manage the control channel. + link: Option, + /// The status shown while the launch options manage the control channel. + launch: AgentLinkStatus, + switch: AgentSwitch, + settings: AgentSettings, + save: SaveFn, + default_folder: Option, +} + +impl Agents { + /// The link for the window, keeping its token and connection file in `settings_dir` and naming + /// `app` (the version string) in the connection file, following `switch` with the saved + /// `settings`; `save` stores the settings when `prefs.agents` changes them. + pub fn new(settings_dir: Option, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn) -> Self { + Self { + link: Some(AgentLink::new(settings_dir, app)), + launch: AgentLinkStatus::default(), + switch, + settings, + save, + default_folder: craft::control::agents::default_folder(APP_NAME), + } + } + + /// The window was started with `--control`, listening on `port` (none when it couldn't): that + /// channel serves the whole run, the link stays off and Preferences says the launch options + /// manage it. + pub fn launched_with_control(mut self, port: Option) -> Self { + self.link = None; + self.launch.port = port; + self.launch.launch_flags = true; + self + } + + /// `default` replaces the default agent folder (tests). + pub fn with_default_folder(mut self, default: Option) -> Self { + self.default_folder = default; + self + } + + /// The saved agent settings. + pub fn settings(&self) -> &AgentSettings { + &self.settings + } + + /// Where the link stands, for Preferences and `ui.inspect`. + pub fn status(&self) -> &AgentLinkStatus { + self.link.as_ref().map_or(&self.launch, AgentLink::status) + } + + /// The suite's `AI-MCP` flag: the launcher's switch decides, and Preferences shows its state. + pub fn mcp_flag(&self) -> bool { + self.switch.mcp_flag() + } + + /// Whether the launcher's switch lets agents use VectorCraft now. + pub fn allowed(&self) -> bool { + // VectorCraft had no agent consent of its own before the switch. + self.switch.allows(false) + } + + /// Saves `settings`; the link applies them on the next pass. + fn set(&mut self, settings: AgentSettings) -> Result<(), String> { + (self.save)(&settings)?; + self.settings = settings; + Ok(()) + } +} + +/// What agent requests may open and save with `settings`: the agent folders (`default` for an empty +/// setting), or nothing. `Err` says why a folder can't be used. +fn roots_for(settings: &AgentSettings, default: Option<&std::path::Path>) -> Result, String> { + let folders = settings.folders_with(default); + let read: Vec<&std::path::Path> = folders.read.as_deref().into_iter().collect(); + let write: Vec<&std::path::Path> = folders.write.as_deref().into_iter().collect(); + Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none)) +} + +/// Once per pass: brings the link in line with the launcher's switch and the saved settings. The +/// control server starts, moves or stops; while it runs, its requests are the app's control channel +/// and run inside the agent folders ([`VectorcraftApp::run_control`]). +pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(agents) = app.agents.as_mut() else { return }; + let allowed = agents.allowed(); + let Some(link) = agents.link.as_mut() else { return }; + let update = link.sync(allowed.then_some(&agents.settings), &WindowHost::of(ctx)); + if update.stopped { + app.channel = None; + app.deferred_control = None; + } + if let Some(requests) = update.requests { + app.channel = Some(ControlChannel::new(requests)); + } + if !update.changed { + return; + } + app.automation_roots = Some(if link.status().port.is_none() { + AutomationRoots::none() + } else { + // Opened only when something changed: the default folder is created on the way. + roots_for(&agents.settings, agents.default_folder.as_deref()).unwrap_or_else(|e| { + link.note(LinkProblem::App(format!("Agents can't open or save files: {e}"))); + AutomationRoots::none() + }) + }); +} + +/// The keys `prefs.agents` takes. +const KEYS: [&str; 4] = ["controlPort", "readRoot", "writeRoot", "whenAppClosed"]; + +/// `prefs.agents`: the agent settings of Preferences › AI Integrations, the link's status and the +/// launcher's switch. `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` changes and saves those +/// settings first. Agents can't change them: their requests run confined to the agent folders, and +/// widening those is the person's choice. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + let Some(agents) = app.agents.as_mut() else { + return Err("agents can't use this window: it keeps no preferences (VECTORCRAFT_NO_PREFS), or it is a nightly".into()); + }; + let given = p.as_object().filter(|o| !o.is_empty()); + if let Some(given) = given { + if let Some(unknown) = given.keys().find(|k| !KEYS.contains(&k.as_str())) { + return Err(format!("unknown agent setting `{unknown}` ({})", KEYS.join(", "))); + } + if file_access::current().is_some() { + return Err("agents can't change the agent settings: the person sets them in Preferences › AI Integrations".into()); + } + let mut next = serde_json::to_value(agents.settings()).map_err(|e| e.to_string())?; + if let Some(next) = next.as_object_mut() { + next.extend(given.clone()); + } + let next: AgentSettings = serde_json::from_value(next).map_err(|e| format!("bad agent setting: {e}"))?; + if next.control_port > u32::from(u16::MAX) { + return Err(format!("controlPort must be 0 to {}, not {}", u16::MAX, next.control_port)); + } + agents.set(next)?; + } + Ok(json!({"settings": agents.settings(), "status": agents.status(), "allowed": agents.allowed(), "mcpFlag": agents.mcp_flag()})) +} + +/// The agent settings as Preferences shows them: under [`PAGE`] in its draft. +pub(crate) fn draft_value(app: &VectorcraftApp) -> Option { + serde_json::to_value(app.agents.as_ref()?.settings()).ok() +} + +/// What Preferences' Agents page needs each pass: the link's status and the suite's `AI-MCP` flag. +pub(crate) fn page_state(app: &VectorcraftApp) -> Option<(AgentLinkStatus, bool)> { + let agents = app.agents.as_ref()?; + Some((agents.status().clone(), agents.mcp_flag())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/agents/tests.rs b/crates/ui-egui/src/agents/tests.rs new file mode 100644 index 0000000000..d6b9757e18 --- /dev/null +++ b/crates/ui-egui/src/agents/tests.rs @@ -0,0 +1,135 @@ +//! Agents in the open window: the link follows the launcher's switch, agent requests stay inside +//! the agent folders, and agents can't change the agent settings. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use craft::automation::agents::{AgentSettings, AgentSwitch, CONNECTION_FILE, read_connection}; +use craft::automation::client::ControlClient; +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::file_access::{self, AutomationRoots}; + +use super::Agents; +use crate::{Services, VectorcraftApp}; + +/// A test's folder with `settings` (the app's settings folder), `in` (the read folder, with +/// `a.svg`), `out` (the write folder) and `outside` (with `b.svg`). +fn folders(tag: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-ui-agents-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["settings", "in", "out", "outside"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + let svg = r#""#; + std::fs::write(base.join("in/a.svg"), svg).unwrap(); + std::fs::write(base.join("outside/b.svg"), svg).unwrap(); + base +} + +fn s(p: PathBuf) -> String { + p.to_string_lossy().into_owned() +} + +/// An app with the desktop's file services whose agents link follows `switch`, with `in` and `out` +/// as the agent folders; the settings it saves land in the returned list. +fn app_with_agents(base: &Path, switch: AgentSwitch) -> (VectorcraftApp, Arc>>) { + let services = Services { + read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + write: Some(Box::new(|p: &str, b: &[u8]| vectorcraft_format::write_atomic(Path::new(p), b).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut settings = AgentSettings::default(); + settings.read_root = s(base.join("in")); + settings.write_root = s(base.join("out")); + let saved = Arc::new(Mutex::new(Vec::new())); + let into = saved.clone(); + let save: super::SaveFn = Box::new(move |settings| { + into.lock().unwrap().push(settings.clone()); + Ok(()) + }); + let agents = Agents::new(Some(base.join("settings")), "VectorCraft test".into(), switch, settings, save).with_default_folder(None); + let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services).with_agents(agents)); + (app, saved) +} + +/// One request from an agent's client through the link's server, answered by the app's frames: the client +/// thread hands its reply back over a channel, and the app runs a pass while it waits. +fn agent_request(app: &mut VectorcraftApp, client: &mut Option, method: &str, params: Value) -> Result { + let ctx = app.ui_ctx.clone().unwrap_or_default(); + let mut c = client.take().expect("a connected client"); + let sent = method.to_owned(); + let (done, reply) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let r = c.call(&sent, params); + let _ = done.send((c, r)); + }); + for _ in 0..2000 { + app.run_control(&ctx); + app.poll_input(&ctx); + if let Ok((c, r)) = reply.recv_timeout(std::time::Duration::from_millis(5)) { + *client = Some(c); + return r; + } + } + panic!("the app did not answer {method:?}") +} + +// With the launcher's switch naming VectorCraft, the window serves agents on loopback and publishes +// where; their requests open and save only inside the agent folders, while the person is not confined. +#[test] +fn agents_reach_the_window_only_inside_the_agent_folders() { + let base = folders("on"); + let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, true)); + let ctx = app.ui_ctx.clone().unwrap_or_default(); + super::sync(&mut app, &ctx); + let port = app.agents.as_ref().and_then(|a| a.status().port).expect("the link listens while the switch allows it"); + let connection = read_connection(&base.join("settings")).unwrap().expect("the connection file is published"); + assert_eq!(connection.port, port); + let token = std::fs::read_to_string(&connection.token_file).unwrap(); + let mut client = Some(ControlClient::connect(([127, 0, 0, 1], port).into(), token.trim()).unwrap()); + + let inside = agent_request(&mut app, &mut client, "app.open", json!({"path": s(base.join("in/a.svg"))})); + assert!(inside.is_ok(), "{inside:?}"); + let outside = agent_request(&mut app, &mut client, "app.open", json!({"path": s(base.join("outside/b.svg"))})); + assert!(outside.as_ref().is_err_and(|e| e.contains("outside the read root")), "{outside:?}"); + let saved = agent_request(&mut app, &mut client, "app.export", json!({"path": s(base.join("outside/a.png")), "format": "png"})); + assert!(saved.as_ref().is_err_and(|e| e.contains("outside the write root")), "{saved:?}"); + assert!(!base.join("outside/a.png").exists()); + // The person at the keyboard opens what they like. + assert!(app.run("file.open", json!({"path": s(base.join("outside/b.svg"))})).is_ok()); + let _ = std::fs::remove_dir_all(&base); +} + +// With the switch off, nothing listens and no connection file is published. +#[test] +fn with_the_switch_off_nothing_listens() { + let base = folders("off"); + let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, false)); + let ctx = app.ui_ctx.clone().unwrap_or_default(); + super::sync(&mut app, &ctx); + assert!(app.channel.is_none()); + assert_eq!(app.agents.as_ref().and_then(|a| a.status().port), None); + assert!(!base.join("settings").join(CONNECTION_FILE).exists()); + let _ = std::fs::remove_dir_all(&base); +} + +// `prefs.agents` saves the person's settings, refuses unknown keys, and refuses every change from a +// confined request: agents can't widen their own folders. +#[test] +fn prefs_agents_saves_and_agents_cannot_change_it() { + let base = folders("prefs"); + let (mut app, saved) = app_with_agents(&base, AgentSwitch::fixed(true, false)); + let r = app.run("prefs.agents", json!({"whenAppClosed": "headless"})).unwrap(); + assert_eq!(r["settings"]["whenAppClosed"], "headless"); + assert_eq!(saved.lock().unwrap().len(), 1); + assert!(app.run("prefs.agents", json!({"port": 7})).is_err()); + assert!(app.run("prefs.agents", json!({"controlPort": 70000})).is_err()); + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap(); + let widened = file_access::confine(Some(&roots), || app.run("prefs.agents", json!({"readRoot": s(base.clone())}))); + assert!(widened.is_err_and(|e| e.contains("can't change the agent settings"))); + assert_eq!(saved.lock().unwrap().len(), 1, "nothing more was saved"); + // Reading them is fine. + assert!(file_access::confine(Some(&roots), || app.run("prefs.agents", json!({}))).is_ok()); + let _ = std::fs::remove_dir_all(&base); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 654e9492b2..ae1fa2c69f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -286,6 +286,8 @@ impl VectorcraftApp { prefs_changed: false, touch_screen: false, automation_roots: None, + #[cfg(not(target_arch = "wasm32"))] + agents: None, pending_plugin_install: None, pending_profile_open: None, queued_profile_opens: Default::default(), @@ -315,6 +317,22 @@ impl VectorcraftApp { pub fn with_automation_roots(mut self, roots: Option>) -> Self { let Some(roots) = roots else { return self }; self.automation_roots = Some(roots); + self.check_file_services(); + self + } + + /// Lets agents into this window while the ArtCraft Launcher's switch names VectorCraft + /// ([`crate::agents`]): their requests, the input they inject and the saves they start read and + /// write only inside the agent folders, as with [`Self::with_automation_roots`]. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_agents(mut self, agents: crate::agents::Agents) -> Self { + self.agents = Some(Box::new(agents)); + self.check_file_services(); + self + } + + /// Has the host's file services check every path against the roots in force ([`file_access`]). + fn check_file_services(&mut self) { let s = &mut self.services; if let Some(read) = s.read.take() { s.read = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| read(p)))); @@ -339,7 +357,6 @@ impl VectorcraftApp { *service = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| open(p)))); } } - self } /// The folders this pass may read and write: the automation roots while the pass carries @@ -632,6 +649,8 @@ impl VectorcraftApp { } crate::keymap::note_os(ctx); prefs_dialog::apply_runtime(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + crate::agents::sync(self, ctx); self.run_control(ctx); // Plug-ins loading on other threads since launch install as their loads finish; until then // the host keeps coming back to look again, and once more when the last one installs, for diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8cedd51928..140187d464 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -24,6 +24,9 @@ macro_rules! tl { } pub mod addons; +/// Agents in the open window through the ArtCraft Launcher's switch (desktop). +#[cfg(not(target_arch = "wasm32"))] +pub mod agents; pub mod background; mod brand; pub mod canvas; @@ -343,6 +346,9 @@ pub struct VectorcraftApp { /// (`--automation-read-root`, `--automation-write-root`); `None`: anywhere. See /// [`Self::with_automation_roots`]. automation_roots: Option>, + /// The agents link while the ArtCraft Launcher's switch may let agents in ([`Self::with_agents`]). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) agents: Option>, /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 35b09d45b6..3781fb0a7b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -299,6 +299,10 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::agents::command(app, p), + #[cfg(target_arch = "wasm32")] + "prefs.agents" => Err("agents in the open window need the desktop app".into()), // Edit → Color Settings… / Assign Profile… (no params): show the colour-management panel // wherever it is, as Window › Separations Preview does (it isn't in an icon column, so a // flyout for it never opened: #4542), scrolled to its Color Settings section, which a short diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 7d053a9a3f..094c33847e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -172,6 +172,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), + ( + "prefs.agents", + "AI Integrations", + "", + "{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences", + ), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), ( "view.refreshMonitorProfile", diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 04dc977291..193ea99ec9 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -173,6 +173,30 @@ impl PrefsWindow { } } +/// The English names of the window's pages: the preference categories, then AI Integrations where agents may use the +/// window (the desktop app with preferences). +fn categories(app: &VectorcraftApp) -> impl Iterator { + #[cfg(not(target_arch = "wasm32"))] + let agents = app.agents.is_some().then_some(crate::agents::PAGE_TITLE); + #[cfg(target_arch = "wasm32")] + let agents = { + let _ = app; + None + }; + PREF_CATEGORIES.iter().copied().chain(agents) +} + +/// The agent settings as the AI Integrations page edits them; `None` where the window has no such page. +fn agent_settings(app: &VectorcraftApp) -> Option { + #[cfg(not(target_arch = "wasm32"))] + return crate::agents::draft_value(app); + #[cfg(target_arch = "wasm32")] + { + let _ = app; + None + } +} + /// Whether `key` is a row of the window: a UI-only field, a preference or a preference group. fn is_known(key: &str) -> bool { UI_FIELDS.iter().any(|f| f.0 == key) || spec(key).is_some() || PREF_GROUPS.contains(&key) @@ -203,7 +227,10 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { draft.set("__smartGuides", &app.ui.view.smart_guides); draft.set("__snapToGrid", &app.ui.view.snap_to_grid); draft.set("__taskBar", &app.ui.task_bar); - let selected = category.and_then(|c| PREF_CATEGORIES.iter().find(|x| x.eq_ignore_ascii_case(c))).copied().unwrap_or(PREF_CATEGORIES[0]); + if let Some(agents) = agent_settings(app) { + draft.set(model::AGENTS_KEY, &agents); + } + let selected = category.and_then(|c| categories(app).find(|x| x.eq_ignore_ascii_case(c))).unwrap_or(PREF_CATEGORIES[0]); // The saved delay, so OK writes the delay in use in its place. let mut source = draft.clone(); if let Some(saved) = &saved_delay { @@ -298,11 +325,12 @@ pub(crate) fn fields(app: &VectorcraftApp) -> Option> { /// Sets one field as the user editing it would (`ui.dialog.set`). `Err` while the window is closed, for an unknown /// key or a value of the wrong kind. pub(crate) fn set_field(app: &mut VectorcraftApp, key: &str, value: Value) -> Result<(), String> { + let category = (key == "__category").then(|| value.as_str().map(|name| (name, categories(app).find(|c| c.eq_ignore_ascii_case(name))))); let w = app.prefs.as_mut().ok_or("no dialog open")?; match key { "__category" => { - let name = value.as_str().ok_or("`__category` takes text")?; - let category = PREF_CATEGORIES.iter().find(|c| c.eq_ignore_ascii_case(name)).ok_or_else(|| format!("no category `{name}`"))?; + let (name, category) = category.flatten().ok_or("`__category` takes text")?; + let category = category.ok_or_else(|| format!("no category `{name}`"))?; w.state.selected = category.to_string(); Ok(()) } diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 847610adb4..2cc8b0c387 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -33,6 +33,28 @@ pub(super) const WARNING_DIALOGS: &[&str] = &["showExternalScriptWarning"]; /// The row key of the Reset All Warning Dialogs button. const RESET_WARNINGS_KEY: &str = "resetWarningDialogs"; +/// The draft key of the agent settings of Preferences › AI Integrations (`prefs.agents`). +pub(super) const AGENTS_KEY: &str = "integrations"; + +/// Preferences › AI Integrations: with the suite's `AI-MCP` flag, the framework's Agents page over the agent settings +/// in the draft (the ArtCraft Launcher's switch decides; the page has none of its own); without it, a line that says +/// so, as VectorCraft had no agent settings before the switch. Returns whether the draft changed. +#[cfg(not(target_arch = "wasm32"))] +fn agents_page(live: &mut Live<'_>, ui: &mut egui::Ui) -> bool { + use craft::ui::contract::Show as _; + use craft::ui::display::{Shade, Text}; + let Some((status, mcp_flag)) = crate::agents::page_state(live.app) else { return false }; + if !mcp_flag { + Text::new(tl!( + "Agents use VectorCraft without a window. The ArtCraft Launcher's Settings › AI agents switch lets them into the open window once the suite's AI-MCP flag is on." + )) + .shade(Shade::Muted) + .show(ui); + return false; + } + craft::automation::ui::agents::AgentsPage::new(AGENTS_KEY, &mut live.w.draft, &status).mcp_flag(true).show(ui).changed +} + /// Turns the warning preferences `keys` back on in the draft, as Reset All Warning Dialogs does; OK or Apply writes /// them. pub(super) fn reset_warning_dialogs(w: &mut PrefsWindow, keys: &[&str]) { @@ -358,7 +380,15 @@ impl Live<'_> { impl PreferencesModel for Live<'_> { fn pages(&self) -> Vec> { - PREF_CATEGORIES.iter().map(|&cat| self.page(cat)).collect() + let pages = PREF_CATEGORIES.iter().map(|&cat| self.page(cat)); + // The agent settings, drawn whole by the framework's Agents page, on the desktop. + #[cfg(not(target_arch = "wasm32"))] + let pages = pages.chain(self.app.agents.is_some().then(|| { + use crate::agents::PAGE_TITLE; + let keywords = "agents AI MCP ArtCraft Launcher control port folders"; + PageSpec::custom(PAGE_TITLE, tl!(PAGE_TITLE)).keywords(keywords).resettable(false) + })); + pages.collect() } fn set(&mut self, key: &str, value: PrefValue) { @@ -429,7 +459,12 @@ impl PreferencesModel for Live<'_> { } } - fn custom_page(&mut self, _ui: &mut egui::Ui, _page: &str) -> bool { + fn custom_page(&mut self, ui: &mut egui::Ui, page: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if page == crate::agents::PAGE_TITLE { + return agents_page(self, ui); + } + let _ = (ui, page); false } @@ -478,12 +513,33 @@ impl PreferencesDraft for Live<'_> { || current.get(k).and_then(Value::as_f64) == self.w.source.get::(k).as_ref().and_then(Value::as_f64)) }) .collect(); - let values: Map = edited.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); + let values: Map = + edited.iter().filter(|(k, _)| !k.starts_with("__") && *k != AGENTS_KEY).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); let document_units = self.w.reset_units.as_deref().is_none_or(|u| values.get("unitsGeneral").and_then(Value::as_str) != Some(u)); + // The agent settings are saved where `vectorcraft-cli mcp` reads them, not with the preferences: only the + // fields changed in the window, so one `prefs.agents` changed while it is open keeps its new value. First, + // so a refused agent setting leaves the preferences unapplied too. + if let Some(agents) = edited.get(AGENTS_KEY).and_then(Value::as_object) { + let read = self.w.source.get::>(AGENTS_KEY).unwrap_or_default(); + let given: Map = + agents.iter().filter(|(k, v)| *k != "allowAgentControl" && read.get(*k) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect(); + if !given.is_empty() { + self.app.run("prefs.agents", Value::Object(given))?; + } + } // A refused folder, typed or picked, comes back here as the engine's message. - if !values.is_empty() { - self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?; + if !values.is_empty() + && let Err(e) = self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units })) + { + // The agent settings were saved: the window shows them as saved (its own edits among them, a change made + // outside it kept), and Apply doesn't send them again. + if let Some(agents) = super::agent_settings(self.app) { + self.w.draft.set(AGENTS_KEY, &agents); + self.w.source.set(AGENTS_KEY, &agents); + self.w.opened.set(AGENTS_KEY, &agents); + } + return Err(e); } let row = |key: &str| edited.get(key).and_then(Value::as_bool); // When OK enters the Touch workspace, the task bar is set before the switch, so it goes to the workspace being @@ -524,6 +580,9 @@ impl PreferencesDraft for Live<'_> { self.w.draft.set("__smartGuides", &self.app.ui.view.smart_guides); self.w.draft.set("__snapToGrid", &self.app.ui.view.snap_to_grid); self.w.draft.set("__taskBar", &self.app.ui.task_bar); + if let Some(agents) = super::agent_settings(self.app) { + self.w.draft.set(AGENTS_KEY, &agents); + } self.w.opened = self.w.draft.clone(); self.w.source = self.w.draft.clone(); self.w.touched.clear(); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 5b15a52f69..4e7de7049b 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1589,3 +1589,54 @@ fn reset_all_warning_dialogs_turns_a_dismissed_warning_back_on() { click_reset_warnings(&mut a); assert!(!a.prefs.as_ref().unwrap().touched.contains("showExternalScriptWarning"), "a dimmed button changes nothing"); } + +/// Preferences › AI Integrations (desktop): the page is there while the window has an agents link, it opens by +/// name, and OK saves an edited agent setting through `prefs.agents` instead of `prefs.set`. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn ai_integrations_page_saves_the_agent_settings_on_ok() { + use craft::automation::agents::{AgentSettings, AgentSwitch}; + use std::sync::{Arc, Mutex}; + let saved: Arc>> = Arc::default(); + let into = saved.clone(); + let save: crate::agents::SaveFn = Box::new(move |s| { + into.lock().unwrap().push(s.clone()); + Ok(()) + }); + let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save) + .with_default_folder(None); + let mut a = app().with_agents(agents); + open(&mut a, Some("ai integrations")); + assert_eq!(page(&a), Some(crate::agents::PAGE_TITLE)); + assert!(with_pages(&mut a, |pages| pages.iter().any(|p| p.id == crate::agents::PAGE_TITLE && p.custom))); + a.prefs.as_mut().unwrap().draft.set("integrations.whenAppClosed", &"error"); + confirm(&mut a).unwrap(); + let saved = saved.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].when_app_closed, craft::automation::agents::WhenAppClosed::Error); +} + +/// OK sends only the agent settings changed in the window: one changed through `prefs.agents` while Preferences is +/// open keeps its new value. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn ok_keeps_an_agent_setting_changed_while_preferences_is_open() { + use craft::automation::agents::{AgentSettings, AgentSwitch}; + use std::sync::{Arc, Mutex}; + let saved: Arc>> = Arc::default(); + let into = saved.clone(); + let save: crate::agents::SaveFn = Box::new(move |s| { + into.lock().unwrap().push(s.clone()); + Ok(()) + }); + let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save) + .with_default_folder(None); + let mut a = app().with_agents(agents); + open(&mut a, Some(crate::agents::PAGE_TITLE)); + a.run("prefs.agents", json!({"readRoot": "/elsewhere"})).unwrap(); + a.prefs.as_mut().unwrap().draft.set("integrations.whenAppClosed", &"error"); + confirm(&mut a).unwrap(); + let last = saved.lock().unwrap().last().cloned().unwrap(); + assert_eq!(last.read_root, "/elsewhere", "the window did not send back the folder it opened with"); + assert_eq!(last.when_app_closed, craft::automation::agents::WhenAppClosed::Error); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 71e3d0fae9..23ab4f671a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol -> **Last updated:** 2026-11-19 · **Change:** #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). +> **Last updated:** 2026-12-03 · **Change:** the window serves agents while the ArtCraft Launcher's AI agents switch names VectorCraft ([Agents in the open window](#agents-in-the-open-window)); previously: #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726). `vectorcraft --control ` listens on `127.0.0.1:` (loopback only). The port must be a number from 1 to 65535 (`--control=` works too), given once; otherwise the app prints an error and exits @@ -33,6 +33,18 @@ persistent clients can send further requests within these bounds, or reconnect a These transport budgets are separate from the existing 60-second command-processing wait. Transport: `apps/vectorcraft/src/control_server.rs`. +## Agents in the open window + +While the ArtCraft Launcher's *Settings › AI agents* switch names VectorCraft, the window serves this protocol +without `--control`, on a loopback port of its own (*Edit › Preferences › AI Integrations › Control Port*; 0 +picks a free one), and publishes the port, its process id and the token file in `agent-connection.json` in +the settings folder. It stops and removes the file when the switch turns off. Each connection must +authenticate before anything else is answered, with the token in `agent-control.token` there (readable by +the user only): `auth.challenge {clientNonce}` and then `auth {proof}`, which `vectorcraft-cli mcp` uses so the +token never crosses the wire, or `auth {token}`. Every request on it runs inside the agent folders of +Preferences › AI Integrations, as with `--automation-read-root` and `--automation-write-root`, and +`prefs.agents` refuses to change them from there. See [Agents in the open window](mcp.md#agents-in-the-open-window). + ## Synthetic input budgets `ui.drag` accepts at most **256** `steps`; `ui.click` and `ui.drag` accept at most **16** `count`. diff --git a/docs/mcp.md b/docs/mcp.md index cc0e00cf5f..0e5d869d6a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **Last updated:** 2026-11-27 · **Change:** Anchor Inspector: canceled Corner and Shared Edge option edits restore their opening values; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. +> **Last updated:** 2026-12-03 · **Change:** plain `vectorcraft-cli mcp` finds the open window through the ArtCraft Launcher's AI agents switch (no port or token to configure), `--when-closed`, the `agent_folders` tool, Preferences › AI Integrations and `prefs.agents`; `--connect` is deprecated. Previously: Anchor Inspector: canceled Corner and Shared Edge option edits restore their opening values; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). @@ -8,21 +8,53 @@ (newline-delimited JSON-RPC 2.0; see [Protocol](#protocol) for version negotiation). Agents use it to draw, inspect and look at VectorCraft documents. -It has two backends: +It has three ways to run: | Mode | How | What works | |---|---|---| -| **Remote** | `vectorcraft-cli mcp --connect 127.0.0.1:7979` (the app must run with `vectorcraft --control 7979`) | Everything. Tool calls are forwarded over the [control protocol](control-protocol.md), so you watch the app change live. | -| **Headless** | `vectorcraft-cli mcp --headless` | An in-process engine session with a CPU renderer. Everything except the UI-only tools (`inspect_ui` or `ui_inspect`, `type_text`, `answer_dialog`, `open_panel`, `screenshot {window:true}` or `ui_screenshot`). | +| **Open window** | `vectorcraft-cli mcp` while the ArtCraft Launcher's *Settings › AI agents* switch lets agents use VectorCraft (see [Agents in the open window](#agents-in-the-open-window)); `--automation-read-root` or `--automation-write-root` make it headless instead | Everything. Each tool call goes to the open VectorCraft window, so you watch the app change live. | +| **Headless** | `vectorcraft-cli mcp --headless` or with automation roots, or plain `mcp` while agents may not use the open window | An in-process engine session with a CPU renderer. Everything except the UI-only tools (`inspect_ui` or `ui_inspect`, `type_text`, `answer_dialog`, `open_panel`, `screenshot {window:true}` or `ui_screenshot`). | +| **Remote** (deprecated) | `vectorcraft-cli mcp --connect 127.0.0.1:7979` (the app must run with `vectorcraft --control 7979` and `VECTORCRAFT_CONTROL_TOKEN`) | Everything, over the [control protocol](control-protocol.md). `--connect` prints a deprecation line and goes away in a later release. | -With no flag, the server tries `127.0.0.1:7979` and falls back to headless. Logs go to stderr; stdout carries -only protocol messages. +Logs go to stderr; stdout carries only protocol messages. + +## Agents in the open window + +One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents use Craft +apps* (behind the suite's `AI-MCP` flag). The launcher also adds one `ArtCraft` entry to the MCP clients it +knows; VectorCraft writes no client configuration of its own. + +While the switch names VectorCraft, the open window serves its control channel on loopback and publishes +`agent-connection.json` (port, process id, token file) in its settings folder; the token stays in +`agent-control.token` there, readable by the user only. Plain `vectorcraft-cli mcp` reads that file before every tool +call and authenticates with the challenge handshake (the window proves it holds the token first; the token +itself never crosses the wire). So no port or token goes into a client's configuration, the app may be +opened after the MCP session started, and it may quit or restart while the session goes on. When the switch +turns off, the window stops listening and removes the file. + +Every file an agent's request opens or saves in the window stays inside the agent folders: those set in +*Edit › Preferences › AI Integrations*, or `Documents/ArtCraft/Agents/VectorCraft` when none is set (made when +first used). A request outside them is refused, as with `--automation-read-root`. The person at the keyboard +is not confined. The `agent_folders` tool tells the agent which folders it may use. + +While agents may use VectorCraft but it is closed, Preferences › AI Integrations chooses what plain `mcp` +does: open VectorCraft and wait for it (the default), run the call in a session without a window confined to +the agent folders, or answer with an error that asks to open VectorCraft. `--when-closed +launch|headless|error` overrides the choice for one server. A session that went headless stays headless, so +documents don't move under the agent. While agents may not use VectorCraft, plain `mcp` runs headless with +only the folders given on its command line, as before. + +Preferences › AI Integrations shows the switch's state, the port agents connect on, Control Port (0: any free +port), the two folders and the closed-app choice. Without the `AI-MCP` flag it only says that agents use +VectorCraft without a window. The same settings are the UI command `prefs.agents {controlPort?, readRoot?, +writeRoot?, whenAppClosed?}`, which agents' own requests can read but not change. Started with `--control`, +the window serves that channel for the whole run instead, and the page says so. ### Command catalogue (headless vs remote) `command_list` / `list_commands` / `vectorcraft://commands` return the live catalogue for the backend in use: -- **Headless:** engine and plug-in commands, plus the desktop menu catalogue (`UI_COMMANDS`) marked `"ui": true` so agents can discover ids such as `view.fitArtboard`, `file.newDialog` and `window.*`. Running a UI-only command that the headless host does not implement returns an error that points at `--connect`. +- **Headless:** engine and plug-in commands, plus the desktop menu catalogue (`UI_COMMANDS`) marked `"ui": true` so agents can discover ids such as `view.fitArtboard`, `file.newDialog` and `window.*`. Running a UI-only command that the headless host does not implement returns an error that asks for the open window. The catalogue is mirrored in `crates/mcp/src/ui_catalog.rs` (mcp does not depend on ui-egui). Regenerate with `cargo xtask ui-commands`; `cargo xtask ci` runs `ui-commands --check` so the mirror cannot drift. - **Remote:** the same lists, with each UI entry's `enabled` taken from the live app. Run UI commands with `command_run` / `run_command` or `invoke_menu`. @@ -40,11 +72,13 @@ cargo install --path apps/vectorcraft-cli --locked export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH" vectorcraft-cli --help claude mcp add vectorcraft -- vectorcraft-cli mcp -# or pin a mode: +# or always without a window: claude mcp add vectorcraft-headless -- vectorcraft-cli mcp --headless -claude mcp add vectorcraft-app -- vectorcraft-cli mcp --connect 127.0.0.1:7979 ``` +With the ArtCraft Launcher, its AI agents switch adds the `ArtCraft` entry for you, and these commands are only +needed for a build of your own. + Cargo installs a binary, not a symlink into `target/`, so it survives `cargo clean`. Re-run the install command after updating the checkout. By default the executable goes in `$CARGO_HOME/bin` (`~/.cargo/bin` when unset), or @@ -66,7 +100,7 @@ installed binary path, not a literal `~` or `$HOME` expression. Avoid symlinks i `target/release`: cleaning the build directory breaks them. A source build alone does not put the CLI on `PATH`. -For a live session, start the app first: `cargo run --release -p vectorcraft -- --control 7979`. +For a live session, turn on the launcher's AI agents switch (for a build of your own, set the `AI-MCP` flag and name `vectorcraft` in the launcher's app list) and open the app: `cargo run --release -p vectorcraft`. ### From an installed release @@ -76,33 +110,21 @@ The release packages ship `vectorcraft-cli` alongside the desktop app, so no bui |---|---| | Windows (MSI) | `%LOCALAPPDATA%\Programs\ArtCraft\VectorCraft\vectorcraft-cli.exe` by default (`C:\Program Files\ArtCraft\VectorCraft\vectorcraft-cli.exe` for an all-users install, under `Program Files (x86)` instead for the 32-bit build, or wherever you installed it otherwise), not on `PATH` | | Linux (deb, rpm) | `/usr/bin/vectorcraft-cli` | -| macOS | the separate `vectorcraft-cli--macos-.zip` release asset (the `.app` holds only the desktop app) | +| macOS | `VectorCraft.app/Contents/MacOS/vectorcraft-cli`, beside the app, where the ArtCraft Launcher finds it (`/Applications/VectorCraft.app` by default), or the separate `vectorcraft-cli--macos-.zip` release asset | ```sh # Windows (PowerShell), default install folder claude mcp add vectorcraft -- "$env:LOCALAPPDATA\Programs\ArtCraft\VectorCraft\vectorcraft-cli.exe" mcp +# macOS, VectorCraft in /Applications (the default; put your own path to VectorCraft.app otherwise) +claude mcp add vectorcraft -- "/Applications/VectorCraft.app/Contents/MacOS/vectorcraft-cli" mcp # Linux, or macOS with the CLI unzipped onto PATH claude mcp add vectorcraft -- vectorcraft-cli mcp ``` -For a live session, start the installed app with the control port before the MCP client starts the server: - -```sh -# macOS: quit VectorCraft first, since `open -a` passes no arguments to an app that is already running -open -a VectorCraft --args --control 7979 -# Windows (PowerShell), default install folder -& "$env:LOCALAPPDATA\Programs\ArtCraft\VectorCraft\vectorcraft.exe" --control 7979 -# Linux (deb, rpm) -vectorcraft --control 7979 -``` - -The Dock, Start menu and desktop launchers start the app without `--control`, so the app opens no control -port unless `VECTORCRAFT_CONTROL_PORT` is set. `vectorcraft-cli mcp` with no flag tries `127.0.0.1:7979` -once, when it starts: a server that started before the app stays headless until the MCP client restarts -it. `open -a` and PowerShell's `&` return before the app opens the port, so wait until the VectorCraft -window is open before you start the MCP client. With `--connect`, a server that finds no app stops and -prints `vectorcraft-cli: cannot connect to 127.0.0.1:7979: ` followed by the system's connection error, for -example `connection timed out`. +For a live session, turn on *Settings › AI agents* in the ArtCraft Launcher and open VectorCraft as usual (Dock, +Start menu, desktop launcher). The server finds the window whenever it opens, unless the session already went headless +(a call made while VectorCraft was closed, with the headless closed-app choice); such a session needs a new +MCP session to use the window. See [Agents in the open window](#agents-in-the-open-window). ## Confining file access @@ -832,6 +854,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | For example, create editable Japanese area type with the engine's vertical writing mode: @@ -10861,7 +10884,7 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture {"name":"pointer_gesture","arguments":{"tool":"selection","mods":{"cmd":true},"events":[{"kind":"down","x":175,"y":125},{"kind":"up","x":175,"y":125}]}} ``` -The preferences for the view need the desktop app (`vectorcraft-cli mcp --connect`): `zoomWithMouseWheel` (the +The preferences for the view need the open window (see [Agents in the open window](#agents-in-the-open-window)): `zoomWithMouseWheel` (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; the control channel's `ui.wheel` turns the wheel), `trackpadRotateView` (on by default: a two-finger rotation on a Mac trackpad, in the macOS app or in Safari, turns the view about the pointer once it reaches 5°; with it off, the gesture does not turn diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index abbd173117..6cf069a8a8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1190,7 +1190,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). - - MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). + - MCP server with 34 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command, agent folders), attached to the open window through the ArtCraft Launcher's AI agents switch or headless (#10621). Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id needs the open window to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (headless, `notifications/cancelled` stops it at the next page or group and writes nothing; in the open window it only stops the call waiting, and the app may still finish and write the export), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP window captures from an app that does not send the image back go through a file in a new folder inside the system's temporary folder, which only the user can open on Unix, instead of a fixed name in the shared folder; the folder is removed after the read, also when the capture or the read fails (`tests::conventions::an_old_app_captures_the_window_in_a_new_private_folder`). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index e4df44c17d..27dab6ddb2 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -117,6 +117,9 @@ echo "==> assembling $APP" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" # Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). cp "$WORK/bin/vectorcraft" "$APP/Contents/MacOS/VectorCraft" +# The CLI too, beside the app: the ArtCraft Launcher finds `vectorcraft-cli` next to the app's +# executable and registers `vectorcraft-cli mcp` for agents. +cp "$WORK/bin/vectorcraft-cli" "$APP/Contents/MacOS/vectorcraft-cli" cp "$ROOT/assets/app-icon/vectorcraft.icns" "$APP/Contents/Resources/VectorCraft.icns" sed -e "s/@VERSION@/$VERSION/g" -e "s/@SHORT_VERSION@/$SHORT_VERSION/g" \ -e "s/@BUILD_SHA@/${VECTORCRAFT_BUILD_SHA:-unknown}/g" \ @@ -127,7 +130,8 @@ printf 'APPL????' >"$APP/Contents/PkgInfo" copy_docs "$APP/Contents/Resources" # Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature). -# Today the only nested code is the main executable; frameworks/helpers would be signed here too. +# The bundled CLI is nested executable code; sign it before sealing the app bundle. +sign --options runtime --identifier ai.storyteller.vectorcraft-cli "$APP/Contents/MacOS/vectorcraft-cli" sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/VectorCraft" sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" codesign --verify --strict --deep --verbose=2 "$APP" diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 3861915380..c27d4a7a44 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -3,8 +3,11 @@ //! Rules, checked in `#[test]` functions (and `#[tokio::test]`, `#[test_case]`, //! `#[wasm_bindgen_test]`, and `#[test]` inside `proptest!`): //! * `all-unguarded`: `assert!(….all(…))` in a test that neither checks a length, emptiness, -//! count, first item or `any` in an assertion's condition or compared operands, nor takes a -//! first item by indexing, unwrapping or a panicking `let … else`: `.all()` is true for an empty +//! count, first item or `any` in an assertion's condition or compared operands (a check of a +//! plain local, such as `xs.len()`, counts for an `.all(…)` only when no code between them may +//! shrink or replace that local), nor takes an +//! item by a numeric index (not one it then iterates), or a first item by unwrapping or a +//! panicking `let … else`: `.all()` is true for an empty //! collection (negated `.all(…)`, including `== false`, and predicates saying that no item //! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier //! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver @@ -19,7 +22,8 @@ //! 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; +//! receiver, or the call the receiver is bound to), when nothing changes the source or a local +//! the receiver passes as a selector (`r.items(active)`) 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 @@ -66,9 +70,12 @@ //! arithmetic on both sides and two reads that differ only in the entry they name (a string or //! integer literal, a local or an indexed element); //! * `constant-echo`: every assertion of the test compares only constants, literals and enum -//! variants; +//! variants, without arithmetic or bitwise operators on user values; //! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the //! test bound (in scope) to such values, so nothing the code under test returned is checked; +//! `into`, and a method such as `to_string` on a value of a type the test names (`Input { n: 5 }`), +//! run code of that type and do not count as reading a fixture. Arithmetic and bitwise operators +//! on user values or containers holding them also run code under test; //! * `never-run`: a test that the `cfg` attributes on it, on the items around it or on the `mod` //! declarations above its file leave out of every target CI runs tests on (Linux and FreeBSD on //! x86_64, and Windows for the app and the UI crate's print tests). A test that still builds on @@ -95,7 +102,7 @@ //! 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 -//! workspace by crate and rule, and does not fail. +//! workspace by crate and rule, and the hits do not make it fail. use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -248,7 +255,8 @@ pub struct Hit { pub note: String, /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for - /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's + /// `self-compare` and `mirror`, through the compared operand or condition for `exact-pixel`, + /// through the variable's name for `env-gate-unset`, through the attribute's /// `]` for `ignore-without-reason`, through the call's `)` for `reads-source`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. @@ -374,7 +382,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } 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. + // test when it becomes newly off or moves from report-only to failing. let base_gates = module_gates(&gated, &read_base, &base_overrides); 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 }; @@ -415,12 +423,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } /// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test -/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place -/// among the tests of that name in those modules, so lines that moved still match and tests of one -/// name in different inline modules stay apart, even when a change removes one of the modules. +/// of `hit` in `src` that was failing too, unless `hit` is report-only. A test is matched by its name, +/// the inline modules around it and its place among the tests of that name in those modules, so +/// lines that moved still match and tests of one name in different inline modules stay apart, even +/// when a change removes one of the modules. fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { let place = test_place(src, &hit.test, hit.line); - base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match &place { + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test && (h.fails() || hit.report_only)).any(|h| match &place { Some(place) => test_place(base_src, &h.test, h.line).as_ref() == Some(place), None => h.line == hit.line, }) @@ -662,6 +671,15 @@ fn read_git_blob(root: &Path, rev: &str, path: &str, limit: u64) -> Option Option { + let size = |spec: &str| git(root, &["cat-file", "-s", spec]).ok()?.parse().ok(); + read_blob(rev, path, limit, size, |spec| { + let out = Command::new("git").current_dir(root).args(["cat-file", "blob", spec]).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned()) + }) +} + 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()), @@ -749,6 +767,9 @@ fn changed_lines(root: &Path, base: &str) -> Result Result>>> = RefCell::default(); + let can_change_test = |path: &str, line: usize| { + let mut cache = test_lines.borrow_mut(); + let lines = + cache.entry(path.to_owned()).or_insert_with(|| read_git_blob_verbatim(root, base, path, MAX_FILE).map(|src| lines_affecting_tests(&src))); + lines.as_ref().is_none_or(|l| l.contains(&line)) + }; + // The work tree is the new side of the diff. A file that cannot be read adds no blank lines. + let new_files: RefCell>> = RefCell::default(); + let code_after = |path: &str, line: usize| { + let mut cache = new_files.borrow_mut(); + let src = cache.entry(path.to_owned()).or_insert_with(|| read_small(root, path)); + src.as_deref().map_or(line, |s| next_code_line(s, line)) + }; + let mut out = parse_diff_in(&diff, &can_change_test, &code_after); for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) { out.insert(path.to_owned(), None); } Ok(out) } +/// [`parse_diff_in`] for a diff whose new side has no blank line after a deletion. +#[cfg(test)] +fn parse_diff(diff: &str, can_change_test: &dyn Fn(&str, usize) -> bool) -> BTreeMap>> { + parse_diff_in(diff, can_change_test, &|_, line| line) +} + +/// The first line of `src`, from 1-based `line` on, that holds code outside comments, or `line` +/// when none does. A line with only a block comment (`/* spacer */`) holds no code. +fn next_code_line(src: &str, line: usize) -> usize { + let code = mask_parts(src, true, false); + code.split(|&c| c == b'\n').enumerate().skip(line.saturating_sub(1)).find(|(_, l)| !l.trim_ascii().is_empty()).map_or(line, |(n, _)| n + 1) +} + /// The changed new-side lines in each file. A pure deletion includes its anchor and the following -/// line, or just line 1 when the anchor is 0. -fn parse_diff(diff: &str) -> BTreeMap>> { +/// line, or just line 1 when the anchor is 0, unless it deletes only blank lines and line comments +/// ([`inert_deleted_line`]) that `can_change_test(path, old line)` places outside literals and tests. +/// When a hunk removes only blank lines and line comments and one of them can change a test, the +/// changed lines also run from the line after the hunk's new lines up to `code_after(path, line)`, +/// the next new-side line with code, so a `return` that a removed skip comment explained counts +/// as changed. +fn parse_diff_in( + diff: &str, + can_change_test: &dyn Fn(&str, usize) -> bool, + code_after: &dyn Fn(&str, usize) -> usize, +) -> BTreeMap>> { let mut out: BTreeMap>> = BTreeMap::new(); let mut current: Option = 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); let mut old: Option = None; + // The hunk whose removed lines are being read: its new-side start and line count, whether a + // removed line so far can change code, whether every removed line so far is blank or a line + // comment, and the old line number of the next removed line. + type Removed = Option<(usize, usize, bool, bool, usize)>; + let mut deletion: Removed = None; + let flush = |deletion: &mut Removed, current: &Option, out: &mut BTreeMap>>| { + if let (Some((start, count, true, inert, _)), Some(path)) = (deletion.take(), current.as_ref()) { + // Only removed comments reach past the next line, to the code that they explained. + let next = if count == 0 { start.saturating_add(1) } else { start.saturating_add(count) }; + let end = if inert { next.max(code_after(path, next)) } else { next }; + if let Some(Some(lines)) = out.get_mut(path) { + if count == 0 { + lines.extend(start.max(1)..=end); + } else if inert { + lines.extend(next..=end); + } + } + } + }; for line in diff.lines() { + if let (Some((_, _, significant, inert, old_line)), false, Some(path)) = (deletion.as_mut(), header, current.as_deref()) { + if let Some(deleted) = line.strip_prefix('-') { + let blank_or_comment = inert_deleted_line(deleted); + *inert &= blank_or_comment; + *significant |= !blank_or_comment || can_change_test(path, *old_line); + *old_line += 1; + continue; + } + if line.starts_with('\\') { + continue; + } + } + flush(&mut deletion, ¤t, &mut out); if line.starts_with("diff --git ") { (header, new_file, old) = (true, false, None); } else if header && line.starts_with("new file mode") { @@ -791,17 +882,58 @@ fn parse_diff(diff: &str) -> BTreeMap>> { } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { header = false; if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { - if count == 0 { - lines.extend(start.max(1)..=start.saturating_add(1)); - } else { + if count > 0 { lines.extend(start..start + count); } + deletion = Some((start, count, false, true, hunk_old_start(hunk).unwrap_or(0))); } } } + flush(&mut deletion, ¤t, &mut out); out } +/// The first old line of a hunk header's `-a,b +c,d @@`. +fn hunk_old_start(hunk: &str) -> Option { + let old = hunk.split_whitespace().find(|w| w.starts_with('-'))?.trim_start_matches('-'); + old.split(',').next()?.parse().ok() +} + +/// Base lines where deleting a blank line or comment can change a test finding. +fn lines_affecting_tests(src: &str) -> BTreeSet { + let mut out = lines_in_literals(src); + let lines = Lines::new(src); + for test in tests_in(&mask(src)) { + out.extend(lines.of(test.attr)..=lines.of(test.close)); + } + out +} + +/// The 1-based lines of `src` that start inside a string or character literal, where a blank line +/// or a `//` line is part of the literal's value. +fn lines_in_literals(src: &str) -> BTreeSet { + // A marker byte at the start of each line stays in the masked text outside literals and is + // blanked inside one. + let marked: String = src.split('\n').map(|l| format!("\u{1}{l}")).collect::>().join("\n"); + let m = mask_parts(&marked, false, true); + let mut out = BTreeSet::new(); + let mut at = 0; + for (n, l) in marked.split('\n').enumerate() { + if m.get(at) == Some(&b' ') { + out.insert(n + 1); + } + at += l.len() + 1; + } + out +} + +/// Whether a deleted line outside tests and literals can be ignored: a blank line, or a line +/// comment that is not a `test-lint: allow` marker and does not open or close a block comment. +fn inert_deleted_line(line: &str) -> bool { + let t = line.trim(); + t.is_empty() || (t.starts_with("//") && !t.contains(ALLOW.trim_end()) && !t.contains("/*") && !t.contains("*/")) +} + /// The path in a `+++ ` label: git ends a label that contains a space with a tab, and writes a /// path with a quote, a backslash or a control character as a C-style quoted string. fn patch_path(label: &str) -> Option { @@ -863,38 +995,380 @@ fn ci_env(root: &Path, files: &[String]) -> Result, String> { Ok(names) } -/// Workflow mapping keys and assignments with capitalized environment variable names. +/// Workflow mapping keys and assignments with capitalized environment variable names. A `run: |` +/// or `run: >` block is read as one script, so a `{ … }` group that spans lines keeps its +/// redirection. The block ends at the first line indented no deeper than the `run` key, and a +/// folded block joins its lines as YAML does ([`fold_block`]). fn upper_words(text: &str) -> impl Iterator + '_ { - text.lines().flat_map(|line| { - let line = workflow_code(line); - let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); - let mapping = - start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); - let assignments = line.match_indices('=').filter_map(move |(at, _)| { + let mut units: Vec<(String, bool)> = vec![]; + let mut lines = text.lines().peekable(); + while let Some(line) = lines.next() { + let code = workflow_code(line); + let start = code.trim_start().strip_prefix("- ").unwrap_or(code.trim_start()).trim_start(); + // `start` is a suffix of `code`, which is a prefix of `line`, so this is the key's column. + let key = code.len() - start.len(); + let block = start.strip_prefix("run:").filter(|rest| rest.starts_with(char::is_whitespace)).and_then(|rest| { + let rest = rest.trim(); + let folded = rest.starts_with('>'); + let marks = rest.strip_prefix(['|', '>'])?; + // An indentation indicator gives the content's indentation past the `run` key's column. + let indent = marks.bytes().find(u8::is_ascii_digit).map(|d| key + usize::from(d - b'0')); + marks.bytes().all(|c| matches!(c, b'-' | b'+') || c.is_ascii_digit()).then_some((folded, indent)) + }); + let Some((folded, indent)) = block else { + units.push((line.to_owned(), false)); + continue; + }; + let mut body: Vec<&str> = vec![]; + while let Some(&next) = lines.peek().filter(|l| l.trim().is_empty() || l.len() - l.trim_start().len() > key) { + body.push(next); + lines.next(); + } + let script = if folded { fold_block(&body, indent) } else { body.iter().map(|l| format!("{}\n", l.trim_start())).collect() }; + units.push((script, true)); + } + units.into_iter().flat_map(|(unit, script)| { + let (mapping, shell) = if script { + (None, unit) + } else { + let line = workflow_code(&unit); + let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); + let mapping = start + .split_once(':') + .filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))) + .map(|(name, _)| name.to_owned()); + // The script of a `run:` line, or the line without its list marker, so the first shell + // word is the command's own. + let plain = start.strip_prefix("run:").filter(|rest| rest.starts_with(char::is_whitespace)).unwrap_or(start); + (mapping, workflow_scalar(start).unwrap_or_else(|| plain.to_owned())) + }; + let code = shell_code(&shell); + let line = code.as_str(); + let assignments = line.match_indices('=').filter_map(|(at, _)| { let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); let from = at - name.len(); - let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); + // A command separator or a subshell opener ends the word before it (`true&&NAME=x`). + let word_start = + |p: usize| p == 0 || line.as_bytes().get(p - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b';' | b'&' | b'|' | b'(')); + // Inside quotes, only a quote that opens a whole word right before the name starts + // an assignment, not one inside a value (`m="NAME=x"`). + // A word is an assignment where the shell reads it as one: before the command name + // (`NAME=x cargo test`), or for a command that reads it as one (`export`, `env`) or + // that writes it to `$GITHUB_ENV`, not for one that searches for it (`grep`). + let boundary = match open_quote(line, from) { + None => word_start(from) && (command_name(line, from).is_none() || assigned_by_command(line, from)), + Some(q) => q + 1 == from && word_start(q) && assigned_by_command(line, q), + }; (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>']) && !printed(line, from)).then(|| name.to_owned()) }); - mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) + mapping.into_iter().chain(assignments).collect::>() }) } -/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line -/// that does not write to `$GITHUB_ENV`. +/// The text of a folded (`>`) YAML block scalar from its content lines. A line break between two +/// lines at the block's indentation becomes a space, a line break before blank lines is dropped and +/// each blank line becomes a line break, and lines indented deeper keep their line breaks and their +/// extra indentation (YAML 1.2.2, section 8.1.3). The block's indentation is `explicit`, from an +/// indentation indicator, or else that of its first line that is not blank. +fn fold_block(body: &[&str], explicit: Option) -> String { + let indent = |l: &str| l.len() - l.trim_start().len(); + let base = explicit.unwrap_or_else(|| body.iter().find(|l| !l.trim().is_empty()).map_or(0, |l| indent(l))); + let (mut out, mut prev, mut blanks) = (String::new(), None::, 0usize); + for line in body { + if line.trim().is_empty() { + blanks += 1; + continue; + } + let deeper = indent(line) > base; + let breaks = match prev { + None => blanks, + Some(was_deeper) if was_deeper || deeper => blanks + 1, + Some(_) => blanks, + }; + if breaks == 0 && prev.is_some() { + out.push(' '); + } + out.extend(std::iter::repeat_n('\n', breaks)); + out.push_str(if deeper { &line[base..] } else { line.trim_start() }); + (prev, blanks) = (Some(deeper), 0); + } + out.push('\n'); + out +} + +/// The shell words of `text`, split at whitespace outside quotes. A backslash before a line break +/// continues the line. +fn shell_words(text: &str) -> Vec<&str> { + let (mut out, mut quote, mut escaped, mut start) = (vec![], None, false, None); + for (i, c) in text.char_indices() { + if escaped { + escaped = false; + if c == '\n' + && let Some(s) = start.take().filter(|&s| s + 1 < i) + { + out.push(&text[s..i - 1]); + } + continue; + } + if c == '\\' && quote != Some('\'') { + escaped = true; + start.get_or_insert(i); + continue; + } + if let Some(q) = quote { + if q == c { + quote = None; + } + continue; + } + if c.is_whitespace() { + if let Some(s) = start.take() { + out.push(&text[s..i]); + } + continue; + } + if matches!(c, '\'' | '"') { + quote = Some(c); + } + start.get_or_insert(i); + } + if let Some(s) = start { + out.push(&text[s..]); + } + out +} + +/// Whether a shell word assigns a variable (`name=value`). +fn shell_assignment(word: &str) -> bool { + word.split_once('=').is_some_and(|(name, _)| { + name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') && name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') + }) +} + +/// The command name of the shell command that holds offset `at`, when it starts before `at`: +/// the first word that is not an assignment, a group opener or a keyword such as `then`. +fn command_name(line: &str, at: usize) -> Option<&str> { + let (start, _) = shell_command(line, at); + command_word(&line[start..at]) +} + +/// The first word of `text` that names a command. +fn command_word(text: &str) -> Option<&str> { + const PREFIXES: &[&str] = &["{", "(", "!", "then", "do", "else", "elif", "if", "while", "until", "time", "command", "builtin", "exec"]; + shell_words(text).into_iter().find(|w| !PREFIXES.contains(w) && !shell_assignment(w)) +} + +/// Whether a shell command writes to the environment file: a redirection to `$GITHUB_ENV`, or a +/// pipeline command that takes it as its output file (`tee`, `Out-File`, `Add-Content`, +/// `Set-Content`). An `echo` that only names the path prints it. A later redirection of standard +/// output in the same pipeline command (`>> "$GITHUB_ENV" > setup.log`) replaces the first one. +fn writes_env_file(command: &str) -> bool { + command.match_indices("GITHUB_ENV").any(|(at, name)| { + let before = command[..at].trim_end_matches(['"', '\'', '$', '{']); + let before = before.strip_suffix("env:").unwrap_or(before).trim_end_matches(['"', '\'', '$', '{']).trim_end(); + if let Some(op) = before.strip_suffix('>') { + // Only a redirection of standard output (`>>`, `1>>`, `&>>`) carries what is printed. + let op = op.strip_suffix('>').unwrap_or(op); + let digits = op.len() - op.trim_end_matches(|c: char| c.is_ascii_digit()).len(); + let word = op[..op.len() - digits].is_empty() || op[..op.len() - digits].ends_with(char::is_whitespace); + if digits > 0 && word && &op[op.len() - digits..] != "1" { + return false; + } + return !stdout_redirected(command[at + name.len()..].trim_start_matches(['"', '\'', '}'])); + } + let element = before.rfind('|').map_or(before, |p| &before[p + 1..]); + command_word(element).is_some_and(|w| ["tee", "out-file", "add-content", "set-content"].contains(&w.to_ascii_lowercase().as_str())) + }) +} + +/// Whether `rest`, the text after a redirection's target, redirects standard output again before +/// the pipeline's next command, a command separator (`;`, `&&`, `&`, a line break) or the end of +/// the group that holds it: a `>`, `>>`, `1>`, `&>` or +/// `>&2` outside quotes. A redirection of another descriptor (`2>`, `2>&1`) leaves standard output +/// where it was, and so does one of an enclosing `( … )` or `{ … }` group. +fn stdout_redirected(rest: &str) -> bool { + let b = rest.as_bytes(); + let (mut quote, mut escaped, mut depth) = (None, false, 0usize); + for (i, &c) in b.iter().enumerate() { + if escaped { + escaped = false; + continue; + } + if c == b'\\' && quote != Some(b'\'') { + escaped = true; + continue; + } + if let Some(q) = quote { + if q == c { + quote = None; + } + continue; + } + match c { + b'\'' | b'"' => quote = Some(c), + b'(' | b'{' => depth += 1, + b')' | b'}' if depth == 0 => return false, + b')' | b'}' => depth -= 1, + b'|' => return false, + // A redirection of a later command applies to that command only. + b';' | b'\n' if depth == 0 => return false, + b'&' if depth == 0 && b.get(i + 1) != Some(&b'>') && (i == 0 || !matches!(b[i - 1], b'>' | b'<')) => return false, + b'>' if i == 0 || b[i - 1] != b'>' => { + // A descriptor number counts only when it is a whole word (`2>`, not `a2>`). + let digits = b[..i].iter().rev().take_while(|d| d.is_ascii_digit()).count(); + let from = i - digits; + let fd = if from == 0 || b[from - 1].is_ascii_whitespace() { &rest[from..i] } else { "" }; + if fd.is_empty() || fd == "1" { + return true; + } + } + _ => {} + } + } + false +} + +/// Decodes a quoted YAML `run` value so shell quote checks see the command itself. +fn workflow_scalar(line: &str) -> Option { + let (key, value) = line.split_once(':')?; + if key != "run" || !value.starts_with(char::is_whitespace) { + return None; + } + let value = value.trim(); + if let Some(value) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) { + return Some(value.replace("''", "'")); + } + let value = value.strip_prefix('"')?.strip_suffix('"')?; + let mut out = String::new(); + let mut chars = value.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + out.push(match chars.next()? { + '0' => '\0', + 'a' => '\u{7}', + 'b' => '\u{8}', + 't' | '\t' => '\t', + 'n' => '\n', + 'v' => '\u{b}', + 'f' => '\u{c}', + 'r' => '\r', + 'e' => '\u{1b}', + 'N' => '\u{85}', + '_' => '\u{a0}', + 'L' => '\u{2028}', + 'P' => '\u{2029}', + c @ (' ' | '"' | '/' | '\\') => c, + c @ ('x' | 'u' | 'U') => { + let width = match c { + 'x' => 2, + 'u' => 4, + _ => 8, + }; + let hex: String = chars.by_ref().take(width).collect(); + if hex.len() != width { + return None; + } + char::from_u32(u32::from_str_radix(&hex, 16).ok()?)? + } + _ => return None, + }); + } + Some(out) +} + +/// Whether the text at `from` is an argument of an `echo` or `printf` command, and that command's +/// pipeline does not write to `$GITHUB_ENV` ([`writes_env_file`]). fn printed(line: &str, from: usize) -> bool { - let command = line[..from].rsplit([';', '&', '|']).next().unwrap_or_default().as_bytes(); - let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); - prints && !line.contains("GITHUB_ENV") + let (start, end) = shell_command(line, from); + command_word(&line[start..from]).is_some_and(|w| matches!(w, "echo" | "printf")) && !writes_env_file(&line[start..end]) +} + +/// Whether the shell command that holds the word at `word` reads it as an assignment: an `export`, +/// `env`, `declare`, `local`, `readonly` or `typeset` command, or a pipeline that writes to +/// `$GITHUB_ENV` ([`writes_env_file`]). +fn assigned_by_command(line: &str, word: usize) -> bool { + let (start, end) = shell_command(line, word); + command_word(&line[start..word]).is_some_and(|w| ["export", "env", "declare", "local", "readonly", "typeset"].contains(&w)) + || writes_env_file(&line[start..end]) +} + +/// The command of a shell line that holds offset `at`, as `(start, end)`. It starts after the last +/// `;`, `&`, `|` or line break before `at` outside quotes. Its pipeline ends at the next `;`, `&`, +/// `||` or line break outside quotes, since `|` passes its output on. A command inside a `{ … }` +/// or `( … )` group runs on to the group's redirection (`{ echo A=1; } >> "$GITHUB_ENV"`). A +/// backslash before a line break continues the command, and `&` in a redirection (`>&2`) does not +/// end it. +fn shell_command(line: &str, at: usize) -> (usize, usize) { + let b = line.as_bytes(); + let (mut quote, mut escaped) = (None, false); + let (mut start, mut depth, mut floor) = (0, 0i32, 0i32); + for (i, &c) in b.iter().enumerate() { + if escaped { + escaped = false; + continue; + } + if c == b'\\' && quote != Some(b'\'') { + escaped = true; + continue; + } + if let Some(q) = quote { + if q == c { + quote = None; + } + continue; + } + match c { + b'\'' | b'"' => quote = Some(c), + b'{' | b'(' => depth += 1, + b'}' | b')' => depth -= 1, + _ => {} + } + if i < at { + floor = floor.min(depth); + } + let redirect = c == b'&' && (i.checked_sub(1).is_some_and(|p| matches!(b[p], b'>' | b'<')) || b.get(i + 1) == Some(&b'>')); + let separator = (matches!(c, b';' | b'&' | b'\n') && !redirect) || (c == b'|' && (i < at || b.get(i + 1) == Some(&b'|'))); + if !separator { + continue; + } + if i < at { + start = i + 1; + } else if depth <= floor { + return (start, i); + } + } + (start, b.len()) } fn env_assignment_name(name: &str) -> bool { name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') } -/// Removes comment text outside quotes from a workflow line. -fn workflow_code(line: &str) -> &str { +/// The offset of the quote that is still open at `at` in a workflow line, read as +/// [`workflow_code`] reads quotes. +fn open_quote(line: &str, at: usize) -> Option { let (mut quote, mut escaped) = (None, false); + for (i, c) in line[..at].char_indices() { + if escaped { + escaped = false; + } else if c == '\\' && quote.is_none_or(|(q, _)| q != '\'') { + escaped = true; + } else if quote.is_some_and(|(q, _)| q == c) { + quote = None; + } else if quote.is_none() && matches!(c, '\'' | '"') { + quote = Some((c, i)); + } + } + quote.map(|(_, i)| i) +} + +/// Removes comment text outside quotes from a workflow line. A YAML comment starts at a `#` at the +/// start of the line or after whitespace; `one#two` is plain text. +fn workflow_code(line: &str) -> &str { + let (mut quote, mut escaped, mut prev) = (None, false, None); for (at, c) in line.char_indices() { if escaped { escaped = false; @@ -905,14 +1379,45 @@ fn workflow_code(line: &str) -> &str { } else if quote.is_none() { match c { '\'' | '"' => quote = Some(c), - '#' => return &line[..at], + '#' if prev.is_none_or(char::is_whitespace) => return &line[..at], _ => {} } } + prev = Some(c); } line } +/// Removes comment text outside quotes from a shell script that can hold several lines (a decoded +/// `run` value): each comment ends at its line break, and quotes stay open across line breaks. A +/// comment starts at a `#` that starts a word, so `one#two` stays. +fn shell_code(script: &str) -> String { + let (mut out, mut quote, mut escaped, mut comment) = (String::with_capacity(script.len()), None, false, false); + let mut prev: Option = None; + for c in script.chars() { + if comment { + comment = c != '\n'; + } else if escaped { + escaped = false; + } else if c == '\\' && quote != Some('\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + '\'' | '"' => quote = Some(c), + '#' if prev.is_none_or(|p| p.is_whitespace() || matches!(p, ';' | '&' | '|' | '(' | ')' | '<' | '>')) => comment = true, + _ => {} + } + } + prev = Some(c); + if !comment { + out.push(c); + } + } + out +} + fn set_by_system(name: &str) -> bool { SYSTEM_ENV.contains(&name) || SYSTEM_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) } @@ -1120,7 +1625,7 @@ fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { match ch { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth -= 1, - b'<' if angles > 0 || m[from..j].trim_ascii_end().ends_with(b"::") => angles += 1, + b'<' if angles > 0 || opens_angle(&m[from..j]) => angles += 1, b'>' if angles > 0 => angles -= 1, b',' if depth == 0 && angles == 0 => { out.push((start, j)); @@ -1135,6 +1640,14 @@ fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { out } +/// Whether a `<` after `before` opens generic arguments: a turbofish (`f::`) or a qualified +/// path at the start of an operand (`>::VALUE`). A `<` after an operand is a +/// comparison, and one after another `<` is a shift. +fn opens_angle(before: &[u8]) -> bool { + let before = before.trim_ascii_end(); + before.ends_with(b"::") || matches!(before.last(), None | Some(b'(' | b'[' | b'{' | b',' | b'&' | b'*' | b'!' | b'=' | b';')) +} + /// `b` without whitespace. fn norm(b: &[u8]) -> String { String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() @@ -1210,6 +1723,26 @@ fn tests_in(m: &[u8]) -> Vec { out } +/// The `{` that opens the body of a `fn` whose signature continues at `from`. The body comes after +/// the signature, whose parameters, array types (`[u8; 2]`) and braced const arguments +/// (`Foo<{ N + 1 }>`) can hold `;` and braces. `None` for a declaration without a body. +fn body_open(m: &[u8], from: usize) -> Option { + let mut open = from; + let mut angles = 0usize; + loop { + match m.get(open)? { + b'(' | b'[' => open = matching(m, open)?, + b'<' => angles += 1, + b'>' if m[open - 1] != b'-' => angles = angles.saturating_sub(1), + b'{' if angles > 0 => open = matching(m, open)?, + b'{' => return Some(open), + b';' if angles == 0 => return None, + _ => {} + } + open += 1; + } +} + /// The function an attribute at `attr` (ending at `from`) belongs to. fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { // The attribute's arguments, and the attributes after it, can hold `;` (`#[test_case(1; "one")]`). @@ -1228,10 +1761,7 @@ fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { if name_end == name_start { return None; } - let open = name_end + m[name_end..].iter().position(|&c| c == b'{' || c == b';')?; - if m[open] != b'{' { - return None; - } + let open = body_open(m, name_end)?; let close = matching(m, open)?; // The item starts after the previous item or block opening; comments before it are masked. // Inner attributes (`#![…]`) there belong to the enclosing module or crate. @@ -1291,11 +1821,12 @@ fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(usize, String, bool)> { let mut out = vec![]; let mut i = from; while i < to { - if !(m[i].is_ascii_alphabetic() || m[i] == b'_') || (i > 0 && is_ident(m[i - 1])) { + // Non-ASCII letters (`vérifier`) are part of a name, as in a test's own name. + if !(m[i].is_ascii_alphabetic() || m[i] == b'_' || m[i] >= 0x80) || (i > 0 && (is_ident(m[i - 1]) || m[i - 1] >= 0x80)) { i += 1; continue; } - let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); + let end = i + m[i..to].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); let bang = m.get(end) == Some(&b'!'); let after = skip_ws(m, end + usize::from(bang)); let after = if bang { after } else { skip_turbofish(m, after) }; @@ -1576,14 +2107,16 @@ fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { if is_macro { start = skip_ws(m, start + usize::from(m.get(start) == Some(&b'!'))); } - let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); if end == start { return None; } - let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; - if m[open] != b'{' { - return None; - } + let open = if is_macro { + let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; + (m[open] == b'{').then_some(open)? + } else { + body_open(m, end)? + }; Some((&m[start..end], is_macro, open, matching(m, open)?)) } @@ -1676,6 +2209,8 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { /// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from /// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. +/// A closure or async block bound to `_` (`let _ = async { … };`) is dropped unrun, so its +/// statement is replaced too. fn executed(m: &[u8], tests: &[TestFn]) -> Vec { let mut out = m.to_vec(); for t in tests { @@ -1684,6 +2219,50 @@ fn executed(m: &[u8], tests: &[TestFn]) -> Vec { blank(&mut out, at, close + 1); } } + // Only a `let` statement, not the pattern of an `if let` or `while let`. + let statements = words(m, b"let", t.open, t.close) + .into_iter() + .filter(|&at| m[..at].trim_ascii_end().last().is_some_and(|c| matches!(c, b'{' | b';' | b'}'))); + for at in statements { + let wild = skip_ws(m, at + 3); + let eq = skip_ws(m, wild + 1); + if m.get(wild) != Some(&b'_') + || m.get(wild + 1).copied().is_some_and(is_ident) + || m.get(eq) != Some(&b'=') + || m.get(eq + 1) == Some(&b'=') + { + continue; + } + let mut value = skip_ws(m, eq + 1); + let end = statement_end(m, at); + // Parentheses around the whole value (`(|| { … })`) do not call it; `(|| { … })()` does. + let mut limit = end; + // A tuple (`(|| (), { … })`) evaluates each element, so only one grouped expression is + // unwrapped. + while m.get(value) == Some(&b'(') { + match matching(m, value) { + Some(close) if skip_ws(m, close + 1) == limit && !tuple_parts(&m[value + 1..close]) => { + limit = close; + value = skip_ws(m, value + 1); + } + _ => break, + } + } + let is_async = m[value..].starts_with(b"async") && !m.get(value + 5).copied().is_some_and(is_ident); + if is_async { + value = skip_ws(m, value + 5); + } + if m[value..].starts_with(b"move") && !m.get(value + 4).copied().is_some_and(is_ident) { + value = skip_ws(m, value + 4); + } + // A closure (`async || …` too) is never called. An async block is dropped when it is the + // whole value; `async { … }.await` runs it. + let unrun = m.get(value) == Some(&b'|') + || (is_async && m.get(value) == Some(&b'{') && matching(m, value).is_some_and(|close| skip_ws(m, close + 1) == limit)); + if unrun && end < t.close { + blank(&mut out, at, end + 1); + } + } } out } @@ -1987,6 +2566,15 @@ impl View<'_> { self.file.hit(at, rule, &self.t.name, note) } + /// A hit at `at` whose span runs through the last line of the operand `through`, so a change to + /// any compared operand of a multiline assertion counts; a failure message after it does not. + fn hit_through(&self, at: usize, through: (usize, usize), rule: Rule, note: String) -> Hit { + let mut h = self.hit(at, rule, note); + let end = through.0 + self.file.m[through.0..through.1].trim_ascii_end().len(); + h.last = h.last.max(self.file.lines.of(end.saturating_sub(1))); + h + } + /// A hit for the whole test, on its `fn` line. fn whole(&self, rule: Rule, note: String) -> Hit { let mut h = self.hit(self.t.fn_at, rule, note); @@ -2021,23 +2609,125 @@ const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; /// Calls whose result says how many items a collection has. const SIZE_CHECKS: &[&str] = &[".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"]; +/// A size check of a plain local: its name, where its operand ends, where the local is read, and +/// the count it is compared with ([`compared_count`]). +type SizeCheck = (String, usize, usize, Option<(String, bool)>); + fn all_unguarded(v: &View) -> Vec { let mut body = v.body_without_messages(); strip_all_predicates(&mut body); let locals = bindings(&body); + // Size checks of a plain local (`xs.len()`, `xs.iter().count()`), each with where its operand + // ends and the count it compares with: one guards an `.all(…)` assertion only when no code + // between them may shrink or replace that local, and when that count gives the assertion's + // iterator an item (`.windows(2)` needs two). + // Each also keeps where the local is read, for a check in the assertion that holds `.all(…)`. + let mut direct: Vec = vec![]; let checked = v.asserts.iter().any(|a| { a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { let (from, to) = (from - v.t.open, to - v.t.open); - SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to) + let text = norm(&body[from..to]); + let other = SIZE_CHECKS.iter().any(|g| { + text.match_indices(g).any(|(i, _)| { + let head = &text[..i]; + // An iterator over the local (`xs.iter().count()`) has the local's items. + let mut source = head; + while let Some(s) = [".iter()", ".into_iter()", ".iter_mut()"].iter().find_map(|m| source.strip_suffix(m)) { + source = s; + } + let start = source.bytes().rposition(|c| !is_ident(c)).map_or(0, |p| p + 1); + let receiver = &source[start..]; + let plain = plain_local(receiver) && !source[..start].ends_with(['.', ':']); + // An operand that may shrink the local after reading its size + // (`{ let n = xs.len(); xs.clear(); n }`) guards nothing; a change before the + // read (`{ xs = fetch(); xs.len() }`) is measured by it. + let read = format!("{}{g}", &head[start..]); + let kept = words(&body, receiver.as_bytes(), from, to) + .into_iter() + .filter(|&p| norm(&body[p..to]).starts_with(&read)) + .find(|&p| !may_shrink(&body[..to], receiver.as_bytes(), p + receiver.len())); + if let (true, Some(read_at)) = (plain, kept) { + let count = compared_count(a, &body, v.t.open, (&text[..start], &text[i + g.len()..]), &read); + direct.push((receiver.to_owned(), to, read_at, count)); + } + !plain + }) + }); + other || reads_counted_local(&body, &locals, from, to) }) }); 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) { + let (any_item, item_roots) = first_item_guard(&body, &sizes); + if checked || any_item { return vec![]; } v.asserts .iter() .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) + .filter(|a| { + let at = a.at - v.t.open; + let end = a.args.last().map_or(at, |&(_, to)| to - v.t.open); + let cond = v.first_arg(a); + // The body offset of each byte of `cond`, which has no whitespace. + let offsets: Vec = a + .args + .first() + .map(|&(f, t)| (f..t).filter(|&k| !v.file.m[k].is_ascii_whitespace()).map(|k| k - v.t.open).collect()) + .unwrap_or_default(); + // Each `.all(…)` with the local its receiver starts from, the items it needs, and where + // it is called. An `.all(…)` inside another one's predicate reads an item, not a local. + let mut predicate_end = 0; + let alls: Vec<(Option<&str>, usize, usize)> = cond + .match_indices(".all(") + .filter(|&(i, _)| { + let outer = i >= predicate_end; + if outer { + predicate_end = matching(cond.as_bytes(), i + 4).unwrap_or(cond.len()); + } + outer + }) + .map(|(i, _)| { + let (receiver, need) = receiver_need(&cond[..i], &sizes); + (chain_root(receiver), need, offsets.get(i).copied().unwrap_or(at)) + }) + .collect(); + // A size check guards an `.all(…)` over the same local when it gives enough items. A check + // before the assertion holds while nothing between them shrinks or replaces the local; a + // check inside it, or after it, while nothing between the read and the `.all(…)` changes + // its item count at all (`xs.push(1)` included). + let guards = |root: Option<&str>, need: usize, call: usize| { + // An item read by a numeric index or a first-item unwrap shows that its own local has one. + if root.is_some_and(|r| item_roots.iter().any(|n| n == r)) { + return true; + } + direct.iter().any(|(name, to, read_at, count)| { + // A strict bound past `usize::MAX` (`xs.len() > usize::MAX`) cannot hold, so it + // guards nothing. + let least = match count.as_ref().map(|(c, strict)| (sizes.count(c), strict)) { + Some((Some(n), strict)) => match n.checked_add(usize::from(*strict)) { + Some(least) => least.max(1), + None => return false, + }, + _ => 1, + }; + let unchanged = if *to < at { + !may_shrink(&body[..at], name.as_bytes(), *to) + } else if *to <= end { + let (from, until) = if *read_at < call { (read_at + name.len(), call) } else { (call, *read_at) }; + // A check joined to the `.all(…)` by `||` need not hold for the assertion to + // pass (`xs.len() >= 2 || xs.windows(2).all(valid)`). + !may_change(&body[..until], name.as_bytes(), from, false) && !joined_by_or(&body[from.min(until)..until]) + } else { + !may_change(&body[..*to], name.as_bytes(), end, false) + }; + root.is_none_or(|r| r == name) && least >= need && unchanged + }) + }; + if alls.is_empty() { + return item_roots.is_empty() && !guards(None, 1, at); + } + !alls.iter().all(|&(root, need, call)| root.is_some() && guards(root, need, call)) + }) .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(); @@ -2053,6 +2743,89 @@ fn all_unguarded(v: &View) -> Vec { .collect() } +/// Whether `b` holds a `||` outside the brackets that open inside it, so the code before it and +/// the code after it are alternatives. +fn joined_by_or(b: &[u8]) -> bool { + let mut depth = 0i32; + for (i, &c) in b.iter().enumerate() { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b'|' if depth <= 0 && b.get(i + 1) == Some(&b'|') => return true, + _ => {} + } + } + false +} + +/// The plain local a method chain at the end of `text` starts from: `xs` of `{let ok=xs.windows(2)`, +/// or `None` for a chain that starts from a call, a path or a field. +fn chain_root(text: &str) -> Option<&str> { + let b = text.as_bytes(); + let mut at = b.len(); + while at > 0 { + match b[at - 1] { + b')' | b']' => { + let mut depth = 0usize; + let mut k = at; + while k > 0 { + k -= 1; + match b[k] { + b')' | b']' => depth += 1, + b'(' | b'[' => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + } + if depth != 0 { + return None; + } + at = k; + } + c if name_byte(c) || c == b'.' => at -= 1, + _ => break, + } + } + let chain = &text[at..]; + let n = chain.bytes().take_while(|&c| name_byte(c)).count(); + let root = &chain[..n]; + let called = chain[n..].starts_with('('); + (plain_local(root) && !called && !text[..at].ends_with(':')).then_some(root) +} + +/// The count that the size check `read` (`xs.len()`) is compared with in a guard operand of `a`, +/// given the operand's text `around` the read: the other operand of an equality assertion whose +/// operand is the read alone, or the name or number right of `==`, `>=` or `>` (left of `==`, `<=` +/// or `<`). Only `.len()` and `.count()` give a count. The flag is true for a strict bound (`>`, +/// `<`), where the collection holds at least one item more than the count. +fn compared_count(a: &MacroCall, body: &[u8], open: usize, around: (&str, &str), read: &str) -> Option<(String, bool)> { + if !(read.ends_with(".len()") || read.ends_with(".count()")) { + return None; + } + let (before, after) = around; + if before.is_empty() && after.is_empty() { + return a + .name + .ends_with("_eq") + .then(|| a.args.iter().take(2).map(|&(from, to)| norm(&body[from - open..to - open])).find(|o| o != read))? + .map(|c| (c, false)); + } + let token = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == ':'; + let right = ["==", ">=", ">"] + .iter() + .find_map(|op| after.strip_prefix(op).map(|r| (r, *op == ">"))) + .map(|(r, strict)| (&r[..r.find(|c: char| !token(c)).unwrap_or(r.len())], strict)); + let left = ["==", "<=", "<"] + .iter() + .find_map(|op| before.strip_suffix(op).map(|l| (l, *op == "<"))) + .map(|(l, strict)| (&l[l.rfind(|c: char| !token(c)).map_or(0, |p| p + 1)..], strict)); + right.or(left).map(|(c, strict)| (c.to_owned(), strict)) +} + /// A loop over a whole table (`for x in TABLE`, `for c in Color::ALL`, `assert!(presets().iter().all(…))`) /// whose assertions only check presence, non-emptiness or a round trip. fn census(v: &View, helpers: &HashSet) -> Vec { @@ -2917,7 +3690,7 @@ fn strip_closure_keywords(head: &str) -> (&str, bool) { } /// 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. +/// a method (`other.run()`) or a path (`other::run()`), and not under a later binding of the same name. /// 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 { @@ -2937,7 +3710,8 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as if before.last() == Some(&b'.') || before.ends_with(b"::") || b.get(open) != Some(&b'(') { return false; } - if words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { + let pattern = for_binding(b, name, at).max(closure_binding(b, name, at)).max(arm_binding(b, name, at)); + if pattern.is_some_and(|p| p > bound) || words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { return false; } if !asynchronous { @@ -3469,12 +4243,56 @@ fn strip_all_predicates(body: &mut [u8]) { } } -/// Whether test code accesses a first item in a way that fails on an empty collection. -fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { +/// Where test code accesses an item in a way that fails on an empty collection: a first item, or an +/// index written as a number. The flag is true for an access whose collection is not a plain local +/// (`rows()[0]`), which counts for every collection; the list names the plain locals that such +/// accesses read (`expected` of `expected[1]`), each of which then has an item. +fn first_item_guard(body: &[u8], sizes: &Sizes) -> (bool, Vec) { let compact = norm(body); + let (mut any, mut roots) = (false, vec![]); + let mut add = |head: &str| match chain_root(head) { + Some(root) => roots.push(root.to_owned()), + None => any = true, + }; let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; - let indexed = compact.match_indices("[0]").any(|(at, _)| array_literal_len(&compact[..at + 3], sizes).is_none_or(|n| n == 0)); - indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) + let indexed = compact.match_indices('[').filter(|&(at, _)| { + let digits = compact[at + 1..].bytes().take_while(u8::is_ascii_digit).count(); + let end = at + 1 + digits; + if digits == 0 || compact.as_bytes().get(end) != Some(&b']') { + return false; + } + // `rows()[2].iter().all(…)` runs `.all` over the item: the access checks `rows()`, not what + // `.all` reads. An item iterated for another call (`rows[0].iter().sum()`) still shows that + // `rows` has items. [`strip_all_predicates`] has blanked each `.all(…)` call, so its chain + // ends at the `.` before it. + let b = compact.as_bytes(); + let mut chain = end + 1; + while let Some(&c) = b.get(chain) { + chain = match c { + b'(' | b'[' => match matching(b, chain) { + Some(close) => close + 1, + None => break, + }, + // Turbofish arguments (`.as_chunks::<2>()`) are part of the call. + b'<' if compact[..chain].ends_with("::") => match skip_turbofish(b, chain - 2) { + next if next > chain => next, + _ => break, + }, + c if is_ident(c) || c >= 0x80 || matches!(c, b'.' | b':') => chain + 1, + _ => break, + }; + } + let calls = &compact[end + 1..chain]; + let all_over_item = [".iter()", ".into_iter()", ".iter_mut()", ".windows(", ".chunks(", ".chunks_exact(", ".as_chunks::<", ".as_rchunks::<"] + .iter() + .any(|m| calls.starts_with(m)) + && calls.ends_with('.'); + !all_over_item && array_literal_len(&compact[..=end], sizes).is_none_or(|n| n == 0) + }); + for (at, _) in indexed.chain(unwrapped.iter().flat_map(|g| compact.match_indices(g))) { + add(&compact[..at]); + } + (any || panicking_first_binding(body), roots) } /// Whether a `let Some(…) = ….first() else { panic!(…) }` binding checks for an item. @@ -3575,7 +4393,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { } // 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. + // or a local it passes as a selector (`r.items(active)`) from the binding on. let read = !plain_local(r) && plain_local(pinned) && init(pinned, a.at).is_some_and(|(text, at)| { @@ -3586,6 +4404,7 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { && 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, bound, r) + && selector_locals(r).into_iter().all(|s| s == root || !selector_touched(body, s, bound)) && !gives_alias(&body[..at], root, root_from) }); // The assertion compares the same call the receiver is bound to (`gaps(&word)`), so its @@ -3598,7 +4417,9 @@ fn pinned_source(receiver: &str, body: &[u8], sizes: &Sizes) -> bool { }) } -/// Whether an expression starts a statement of the test body or a plain nested block. +/// Whether an expression starts a statement of the test body or a plain nested block. A block +/// still open at the end of `body` also holds the code that follows `body` (the assertion a caller +/// passes `body` up to), so a statement in it runs whenever that code runs. 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; @@ -3612,12 +4433,15 @@ fn body_level_statement(body: &[u8], mut at: usize) -> bool { 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'[' | b'{' => match matching(body, i) { + Some(close) if close < at => { + statement = body[i] == b'{'; + i = close + 1; + continue; + } + None => statement = body[i] == b'{', + Some(_) => return false, + }, b';' | b'}' => statement = true, c if c.is_ascii_whitespace() => {} _ => statement = false, @@ -3693,12 +4517,58 @@ fn root_local(expr: &str) -> &str { &expr[..end] } +/// Whether a prefix ends in field access or a path separator, rather than a range operator. +fn field_or_path(prefix: &[u8]) -> bool { + let prefix = prefix.trim_ascii_end(); + prefix.ends_with(b"::") || (prefix.ends_with(b".") && !prefix.ends_with(b"..")) +} + +/// Whether code after `from` may change the selector local `name` ([`touched_after`]). A field +/// or a path segment of the same name (`settings.active`, `mode::active`) is another value. +fn selector_touched(body: &[u8], name: &str, from: usize) -> bool { + let mut own = body.to_vec(); + for at in words(body, name.as_bytes(), from, body.len()) { + let before = body[..at].trim_ascii_end(); + if field_or_path(before) { + blank(&mut own, at, at + name.len()); + } + } + touched_after(&own, name, from, name) +} + +/// The plain locals an expression passes as call arguments or indexes after its root +/// (`active` in `r.items(active)`, `i` in `rows[i]`): not method or field names, path segments, +/// called names, closure parameters or `true` and `false`. +fn selector_locals(expr: &str) -> Vec<&str> { + let b = expr.as_bytes(); + let mut out = vec![]; + let mut at = b.iter().take_while(|&&c| name_byte(c)).count(); + while at < b.len() { + if !name_byte(b[at]) { + at += 1; + continue; + } + let start = at; + while at < b.len() && name_byte(b[at]) { + at += 1; + } + let word = &expr[start..at]; + let before = expr[..start].trim_end(); + let after = expr[at..].trim_start(); + let named = field_or_path(before.as_bytes()) || before.ends_with([':', '|']) || after.starts_with(['(', '!', ':', '|']); + if local_name(word) && !named && !matches!(word, "true" | "false" | "as" | "mut") && !out.contains(&word) { + out.push(word); + } + } + out +} + /// 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) { + if !local_name(name) { return true; } words(body, name.as_bytes(), from, body.len()).into_iter().any(|at| { @@ -4030,10 +4900,18 @@ fn item_len(receiver: &str, sizes: &Sizes) -> usize { } /// The receiver without its iterator method and the items it needs for `.all(…)` to see one: -/// `.windows(k)` and `.chunks_exact(k)` need `k`, anything else one. An unknown `k` needs more +/// `.windows(k)`, `.chunks_exact(k)` and the full chunks of `.as_chunks::()` need `k`, +/// anything else one. An unknown `k` needs more /// than any collection has. fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { let r = array_receiver(receiver); + // The full chunks of `.as_chunks::()` (`.0`) and `.as_rchunks::()` (`.1`) need `k`. + for (method, chunks) in [(".as_chunks::<", ">().0"), (".as_rchunks::<", ">().1")] { + let Some(head) = r.strip_suffix(chunks) else { continue }; + let Some(at) = head.rfind(method) else { continue }; + let need = sizes.count(&head[at + method.len()..]).filter(|&k| k > 0).unwrap_or(usize::MAX); + return (array_receiver(&r[..at]), need); + } for (method, exact) in [(".windows(", true), (".chunks_exact(", true), (".chunks(", false)] { let Some(at) = r.rfind(method) else { continue }; let open = at + method.len() - 1; @@ -4055,15 +4933,17 @@ fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { (r, 1) } -/// The length of the non-empty literal an earlier equality assertion compares this plain local -/// receiver with, or 0. For a derived local, its binding must reach the assertion unchanged. +/// The length of the non-empty literal an equality assertion at the level of the test body compares +/// this plain local receiver with, or 0. For a derived local, its binding must reach the assertion +/// unchanged. fn equal_len(receiver: &str, body: &[u8], sizes: &Sizes, binding: Option) -> usize { let name = array_receiver(receiver); if !plain_local(name) { return 0; } let lens = macro_calls(body, 0, body.len()).into_iter().filter_map(|a| { - if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + // Only an assertion that always runs, not one under an `if` or in a closure, pins the length. + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) || !body_level_statement(body, a.at) { return None; } let &(lf, lt) = a.args.first()?; @@ -4092,6 +4972,17 @@ fn plain_local(name: &str) -> bool { !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(is_ident) } +/// Whether `c` is a byte of a name, non-ASCII letters (`数`) included: their UTF-8 bytes are all +/// 0x80 or above. +fn name_byte(c: u8) -> bool { + is_ident(c) || c >= 0x80 +} + +/// [`plain_local`], with non-ASCII letters allowed ([`name_byte`]). +fn local_name(name: &str) -> bool { + !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(name_byte) +} + /// Removes one borrow and a slice view from a compared operand. fn collection_operand(operand: &str) -> &str { let operand = operand.strip_prefix('&').unwrap_or(operand); @@ -4344,6 +5235,23 @@ fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option { None } +/// Whether the text inside parentheses is a tuple: a comma outside brackets, after the parameter +/// list of a leading closure (`|a, b| …`). +fn tuple_parts(inner: &[u8]) -> bool { + let mut at = skip_ws(inner, 0); + for keyword in [&b"async"[..], b"move"] { + if inner[at..].starts_with(keyword) && !inner.get(at + keyword.len()).copied().is_some_and(is_ident) { + at = skip_ws(inner, at + keyword.len()); + } + } + if inner[at..].starts_with(b"||") { + at += 2; + } else if inner.get(at) == Some(&b'|') { + at = find(inner, b"|", at + 1).map_or(inner.len(), |p| p + 1); + } + has_top_level(&inner[at..], b',') +} + /// Whether `c` occurs in `b` outside brackets. fn has_top_level(b: &[u8], c: u8) -> bool { let mut at = 0; @@ -4423,7 +5331,8 @@ fn may_shrink(body: &[u8], name: &[u8], from: usize) -> bool { } /// Whether code after `from` may change the item count of `name`: an unknown method call, -/// an assignment, or a `&mut` borrow. Growth is harmless only for the source collection. +/// an assignment, a `&mut` borrow, or passing it to a call when it holds a `&mut` reference. +/// Growth is harmless only for the source collection. fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool { const PRESERVING: &[&str] = &[ "iter", @@ -4446,6 +5355,8 @@ fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool "windows", "chunks", "chunks_exact", + "as_chunks", + "as_rchunks", "sort", "sort_by", "sort_by_key", @@ -4465,24 +5376,86 @@ fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool "values", ]; const ADDING: &[&str] = &["push", "push_back", "push_front", "insert", "extend"]; + let local = std::str::from_utf8(name).is_ok_and(plain_local); + let mut_ref = binds_mut_ref(body, name); words(body, name, from, body.len()).into_iter().any(|p| { + let prefix = body[..p].trim_ascii_end(); + if local && field_or_path(prefix) { + return false; + } let after = &body[skip_ws(body, p + name.len())..]; - let assigned = (after.starts_with(b"=") && !after.starts_with(b"==") && !after.starts_with(b"=>")) - || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| after.starts_with(op.as_bytes())); let before = body[from..p].trim_ascii_end(); let borrowed = before.strip_suffix(b"mut").is_some_and(|b| b.trim_ascii_end().ends_with(b"&")); - let called = if after.first() == Some(&b'.') { - let start = skip_ws(after, 1); - let end = start + after[start..].iter().copied().take_while(|&c| is_ident(c)).count(); - let rest = &after[skip_ws(after, end)..]; - let method = &after[start..end]; + let mut start = p; + let mut end = skip_ws(body, p + name.len()); + while let Some(open) = enclosing_open(body, start) { + let callee = body[..open].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'>')); + if body[open] != b'(' || callee || skip_ws(body, open + 1) != start || matching(body, open) != Some(end) { + break; + } + start = open; + end = skip_ws(body, end + 1); + } + let method_call = &body[end..]; + let plain_assign = |rest: &[u8]| rest.starts_with(b"=") && !rest.starts_with(b"==") && !rest.starts_with(b"=>"); + // A destructuring assignment (`(xs, _) = …`) replaces each local named as an element of + // the tuple or array to the left of its `=`. + let destructured = after.first().is_some_and(|c| matches!(c, b',' | b')' | b']')) && { + let mut at = p; + let mut target = false; + while let Some(open) = enclosing_open(body, at) { + let callee = body[..open].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'>' | b'!')); + let Some(close) = matching(body, open).filter(|_| matches!(body[open], b'(' | b'[') && !callee) else { break }; + if plain_assign(&body[skip_ws(body, close + 1)..]) { + target = true; + break; + } + at = open; + } + target + }; + let assigned = plain_assign(method_call) + || destructured + || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| method_call.starts_with(op.as_bytes())); + let called = if method_call.first() == Some(&b'.') { + let start = skip_ws(method_call, 1); + let end = start + method_call[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + let rest = &method_call[skip_ws(method_call, end)..]; + let method = &method_call[start..end]; (rest.starts_with(b"(") || rest.starts_with(b"::<")) && !PRESERVING.iter().any(|m| method == m.as_bytes()) && !(allow_growth && ADDING.iter().any(|m| method == m.as_bytes())) } else { false }; - assigned || borrowed || called + // A local that already holds a `&mut` reborrows it when passed to a function or method + // (`std::mem::take(xs)`, `std::mem::take((xs))`), which can change it; a macro such as + // `assert_eq!` only reads it. The grouped argument's outer bounds find the call. + let outer_before = body[..start].trim_ascii_end(); + let passed = mut_ref + && (outer_before.ends_with(b"(") || outer_before.ends_with(b",")) + && matches!(body.get(end), Some(b')' | b',')) + && enclosing_open(body, start).is_some_and(|open| { + body[open] == b'(' && body[..open].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'}' | b'>')) + }); + assigned || borrowed || called || passed + }) +} + +/// Whether `body` has a `let` that binds `name` to a mutable reference (`let xs = &mut v;`, +/// `let xs: &mut Vec = …;`). +fn binds_mut_ref(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + name.len(); + if !body[start..].starts_with(name) || body.get(end).copied().is_some_and(is_ident) { + return false; + } + let rest = norm(&body[end..statement_end(body, end)]); + rest.starts_with("=&mut") || rest.starts_with(":&mut") }) } @@ -4654,6 +5627,10 @@ fn bindings(body: &[u8]) -> Vec { fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { words(body, &b.name, from, to).into_iter().any(|p| { + let prefix = body[..p].trim_ascii_end(); + if field_or_path(prefix) { + return false; + } let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); reaching .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) @@ -4726,18 +5703,47 @@ fn exit_status_only(v: &View) -> Option { strip_stream_configuration(&mut body); let reads = ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); - let status_only = |a: &MacroCall| { - a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { - let c = norm(&v.file.m[from..to]); - c.contains(".success()") || c.contains(".code()") - }) - }; + let status_only = + |a: &MacroCall| a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| status_only_condition(&norm(&v.file.m[from..to]))); if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { return None; } Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) } +/// Whether a whitespace-free condition can hold when only exit statuses are checked: one of its +/// `||` alternatives has only `&&` operands that check `.success()` or `.code()`. A parenthesized +/// operand is classified the same way, operand by operand. +fn status_only_condition(c: &str) -> bool { + let c = unparenthesized(c); + let mut start = 0; + top_level_at(c, "||").into_iter().chain([c.len()]).any(|end| { + if end < start { + return false; + } + let alternative = c.get(start..end); + start = end.saturating_add(2); + alternative.is_some_and(|alternative| { + let mut start = 0; + top_level_at(alternative, "&&").into_iter().chain([alternative.len()]).all(|end| { + if end < start { + return true; + } + let operand = alternative.get(start..end); + start = end.saturating_add(2); + operand.is_some_and(|operand| { + let inner = unparenthesized(operand); + if inner.len() < operand.len() { + status_only_condition(inner) + } else { + operand.contains(".success()") || operand.contains(".code()") + } + }) + }) + }) + }) +} + /// Blanks the names of builder calls that set a process's streams (`.stdout(…)`, whatever the /// argument) in whitespace-free text. Reads of the output fields (`out.stdout`) stay. fn strip_stream_configuration(body: &mut [u8]) { @@ -5301,7 +6307,7 @@ fn counted_while(m: &[u8], head: &[u8], open: usize, close: usize) -> bool { /// body calls a function or method other than [`TIME_CALLS`] and [`PASS_THROUGH_CALLS`] (a /// flag's `load`, a `poll`, a progress read). A macro such as `println!`, a call inside the /// arguments of `stringify!`, of a [`LOG_MACROS`] macro or of the sleep itself, a nested `fn` name -/// and `Duration::new` do not count. A closure passed directly to a `thread::spawn` call whose +/// and the calls in its body, and `Duration::new` do not count. A closure passed directly to a `thread::spawn` call whose /// handle is dropped runs beside the test, which does not wait for it. In `while n < bound` with /// `n += 1`, `n -= 1`, `n = n + 1` or `n = n - 1` in the body, the loop counts its own passes, so /// only calls in the body count. @@ -5343,16 +6349,56 @@ fn polls_or_releases(m: &[u8], at: usize, imports: Imports) -> bool { let b = before(p); b.ends_with(b"fn") && !b.len().checked_sub(3).is_some_and(|j| is_ident(b[j])) }; + // A nested `fn` item runs only where something calls it, so its signature and body do not poll. + let items: Vec<(usize, usize)> = words(m, b"fn", from, close).into_iter().filter_map(|kw| fn_item_span(m, kw, close)).collect(); found.iter().any(|&(p, ref name, method)| { !name.ends_with('!') && !TIME_CALLS.contains(&name.as_str()) && !PASS_THROUGH_CALLS.contains(&name.as_str()) && !skipped.iter().any(|&(o, c)| o < p && p < c) + && !items.iter().any(|&(o, c)| o < p && p < c) && !(name == "new" && !method && duration_new(p)) && !(!method && declared(p)) }) } +/// The span of the `fn` item whose keyword is at `kw`, from the keyword to the brace that closes +/// its body, when that brace comes before `to`: the name, any generic parameters (``), +/// the parameter list, the return type and the body. `None` for a `fn` pointer type (`fn(u8)`) or a +/// declaration without a body. +fn fn_item_span(m: &[u8], kw: usize, to: usize) -> Option<(usize, usize)> { + let name = skip_ws(m, kw + 2); + let name_end = name + m[name..to].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); + if name_end == name { + return None; + } + let mut i = skip_ws(m, name_end); + if m.get(i) == Some(&b'<') { + let mut depth = 0usize; + while i < to { + match m[i] { + b'<' => depth += 1, + b'>' if m[i - 1] != b'-' => { + depth -= 1; + if depth == 0 { + break; + } + } + b'(' | b'[' | b'{' => i = matching(m, i)?, + _ => {} + } + i += 1; + } + i = skip_ws(m, i + 1); + } + if m.get(i) != Some(&b'(') { + return None; + } + let open = body_open(m, matching(m, i)? + 1).filter(|&open| open < to)?; + let close = matching(m, open)?; + (close < to).then_some((kw, close)) +} + /// The start of the name of the `spawn(…)` call that takes the closure whose head is `m[start..open]` /// as its argument directly (`spawn(|| {`, `spawn(move || {`), not through another call such as /// `spawn(prepare(|| {`. @@ -5907,13 +6953,21 @@ fn mirrors(v: &View) -> Vec { let (la, ra) = (head_args(v.file, code, lr)?, head_args(v.file, code, rr)?); let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); - (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + (!entries).then(|| v.hit_through(a.at, rr, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) }) .collect() } -/// Methods that only read a value the test built itself. -const FIXTURE_READS: &[&str] = &["len", "is_empty", "clone", "to_string", "to_owned", "as_str", "as_ref", "as_slice", "to_vec", "into"]; +/// Methods that inspect a fixture container without running its elements' code. +const FIXTURE_READS: &[&str] = &["len", "is_empty", "as_str", "as_ref", "as_slice"]; + +/// Methods that can run element code and are inert only when the fixture holds no user values. +/// `into` is not one: its target can be any type with a `From` impl. +const FIXTURE_CONVERSIONS: &[&str] = &["clone", "to_string", "to_owned", "to_vec"]; + +/// Capitalized names from the standard library that an operand may build or read without reaching +/// code under test. +const STD_TYPES: &[&str] = &["Some", "None", "Ok", "Err", "Box", "String", "Vec", "Option", "Result"]; /// Lowercase names that are types or keywords, not locals. const PLAIN_NAMES: &[&str] = &[ @@ -5925,26 +6979,47 @@ fn screaming_or_camel(name: &str) -> bool { name.as_bytes().first().is_some_and(u8::is_ascii_uppercase) } +/// Whether a name is a capitalized type, struct or enum of the code under test: `Input`, `Kind`, not +/// an all-capitals constant (`MAX_ZOOM`) or one of [`STD_TYPES`]. +fn user_type(name: &str) -> bool { + screaming_or_camel(name) && name.bytes().any(|c| c.is_ascii_lowercase()) && !STD_TYPES.contains(&name) +} + +/// Looks up a local at a position: for a local whose reaching binding is inert there, whether its +/// value is a [`user_value`], its initializer and the position of its binding. +type LocalAt<'a> = dyn Fn(&str, usize) -> Option<(bool, String, usize)> + 'a; + /// Whether a (whitespace-free, masked) operand reads only literals, constants, enum variants and the -/// test's own locals bound to such values: `Some(true)` when it reads such a local, `Some(false)` -/// when it reads none, `None` when it calls or reads anything else. -fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { +/// test's own locals bound to such values: `Some((reads_local, user))`, where `reads_local` says +/// whether it reads such a local and `user` whether its value is one of a [`user_type`] +/// ([`user_value`]); `None` when it calls or reads anything else. A method on a user value can run +/// its own implementation. A [`FIXTURE_READS`] method on a container of user values is inert, but +/// a [`FIXTURE_CONVERSIONS`] method on that container can run element code. +/// Arithmetic and bitwise operators on user values can also run their implementations. +/// `local` gives, for a local whose reaching binding is inert at a position, its `user`, initializer +/// and binding position. +fn inert(op: &str, pos: usize, local: &LocalAt) -> Option<(bool, bool)> { let b = op.as_bytes(); + // Non-ASCII letters (`数`) are part of a name; their UTF-8 bytes are all 0x80 or above. + let ident = |c: u8| is_ident(c) || c >= 0x80; let mut reads_local = false; // Where the path that ends at the current name starts: `Vec` in `Vec::::new`. let mut path_start = 0; let mut i = 0; while i < b.len() { - if !is_ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && is_ident(b[i - 1])) { + if fixture_operator_runs(op, i, pos, local) { + return None; + } + if !ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && ident(b[i - 1])) { // Number suffixes (`1.0f32`, `2_u8`) are part of the literal. if b[i].is_ascii_digit() { - i += b[i..].iter().take_while(|&&c| is_ident(c)).count(); + i += b[i..].iter().take_while(|&&c| ident(c)).count(); continue; } i += 1; continue; } - let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let end = i + b[i..].iter().take_while(|&&c| ident(c)).count(); let name = &op[i..end]; // Turbofish arguments name types only, and the `(` after them makes a call of `name`. let rest = skip_turbofish(b, end); @@ -5955,8 +7030,15 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { path_start = i; } if method { - if after.starts_with('(') && !FIXTURE_READS.contains(&name) { - return None; + if after.starts_with('(') { + let receiver = &op[receiver_start(b, i - 1)..i - 1]; + // An element indexed out of a local (`xs[0].len()`) is a user value when the local holds one. + let user = indexed_local(receiver).map_or_else(|| user_value(receiver, pos, local), |base| holds_user_value(base, pos, local)); + let inert_read = FIXTURE_READS.contains(&name) && !user; + let inert_conversion = FIXTURE_CONVERSIONS.contains(&name) && !holds_user_value(receiver, pos, local); + if !inert_read && !inert_conversion { + return None; + } } } else if after.starts_with("::") || PLAIN_NAMES.contains(&name) { } else if after.starts_with('!') && !after.starts_with("!=") { @@ -5970,7 +7052,7 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { let path = without_turbofish(&op[path_start..end]); ["Box::new", "String::from", "Vec::new"].iter().any(|p| path.ends_with(p)) }) - || (!path_tail && screaming_or_camel(name)); + || screaming_or_camel(name); if !builder { return None; } @@ -5979,14 +7061,244 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { } else if path_tail { return None; } else { - match local(name) { - Some(true) => reads_local = true, - _ => return None, - } + reads_local = true; + local(name, pos)?; } i = rest; } - Some(reads_local) + Some((reads_local, user_value(op, pos, local))) +} + +/// The local an element is indexed out of (`xs` of `xs[0]` and `&rows[1][2]`), or `None`. +fn indexed_local(expr: &str) -> Option<&str> { + let expr = expr.trim_start_matches(['&', '*']); + let b = expr.as_bytes(); + // Names follow [`inert`]'s rules, so `数` of `数[0]` is a local. + let n = b.iter().take_while(|&&c| name_byte(c)).count(); + let mut at = n; + if at == b.len() { + return None; + } + while at < b.len() { + if b[at] != b'[' { + return None; + } + at = matching(b, at)? + 1; + } + local_name(&expr[..n]).then(|| &expr[..n]) +} + +/// Whether the operator at `at` can call an implementation on a user value. Comparisons, logical +/// operators, borrows and ranges do not count. Operands stop at other operators or separators, so +/// an unrelated user value in the assertion does not make literal arithmetic behavioral. +fn fixture_operator_runs(op: &str, at: usize, pos: usize, local: &LocalAt) -> bool { + let b = op.as_bytes(); + let c = b[at]; + if !matches!(c, b'+' | b'-' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^' | b'<' | b'>' | b'!') { + return false; + } + let previous = at.checked_sub(1).and_then(|i| b.get(i)).copied(); + let next = b.get(at + 1).copied(); + if next == Some(b'=') || (matches!(c, b'&' | b'|') && (next == Some(c) || previous == Some(c))) { + return false; + } + let width = if matches!(c, b'<' | b'>') { + if next != Some(c) || previous == Some(c) || b.get(at + 2) == Some(&b'=') { + return false; + } + 2 + } else { + 1 + }; + let binary = previous.is_some_and(|p| is_ident(p) || p >= 0x80 || matches!(p, b')' | b']' | b'}' | b'"' | b'\'')); + if (!binary && !matches!(c, b'-' | b'!')) || (binary && c == b'!') { + return false; + } + if binary && holds_user_value(&op[receiver_start(b, at)..at], pos, local) { + return true; + } + let from = at + width; + let mut end = from; + // Prefix borrows and dereferences belong to the right operand, not another binary operator. + while matches!(b.get(end), Some(b'&' | b'*')) { + end += 1; + } + while end < b.len() { + match b[end] { + b'(' | b'[' | b'{' => { + let Some(close) = matching(b, end) else { return false }; + end = close + 1; + } + b'.' if b.get(end + 1) == Some(&b'.') => break, + b'!' if matches!(b.get(end + 1), Some(b'(' | b'[' | b'{')) => end += 1, + c if is_ident(c) || c >= 0x80 || matches!(c, b'.' | b':') => end += 1, + _ => break, + } + } + holds_user_value(&op[from..end], pos, local) +} + +/// Where the receiver of the method call whose `.` is at `dot` starts in a whitespace-free operand: +/// back over names, paths, field and method accesses, bracketed groups, macro names and string +/// literals. +fn receiver_start(op: &[u8], dot: usize) -> usize { + let ident = |c: u8| is_ident(c) || c >= 0x80; + let mut j = dot; + while j > 0 { + let c = op[j - 1]; + if matches!(c, b')' | b']' | b'}') { + let mut depth = 0usize; + let mut k = j; + while k > 0 { + k -= 1; + match op[k] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + } + j = k; + } else if ident(c) { + while j > 0 && ident(op[j - 1]) { + j -= 1; + } + } else if c == b'"' { + j = op[..j - 1].iter().rposition(|&q| q == b'"').unwrap_or(0); + } else if (c == b'.' && !(j >= 2 && op[j - 2] == b'.')) || (c == b'!' && j >= 2 && ident(op[j - 2])) { + j -= 1; + } else if c == b':' && j >= 2 && op[j - 2] == b':' { + j -= 2; + } else { + break; + } + } + j +} + +/// Whether a whitespace-free expression is a value of a [`user_type`]: it starts with such a name +/// (`Input { n: 5 }`, `model::Input(5)`, `Kind::A`), or with a local whose reaching binding is one (`local`). +/// A literal, a macro such as `vec!` and a standard builder such as `Some(…)` are not. A field read +/// (`input.n`, `pair.0`) is the value the struct literal or constructor it reads gives that field, +/// and not a user value when the test does not show it. +fn user_value(expr: &str, pos: usize, local: &LocalAt) -> bool { + let expr = expr.trim_start_matches(['&', '*']); + if let Some((base, field)) = last_field(expr) { + return field_value(base, field, pos, local).is_some_and(|(v, at)| user_value(&v, at, local)); + } + if expr.starts_with('(') { + return matching(expr.as_bytes(), 0) == Some(expr.len() - 1) && user_value(&expr[1..expr.len() - 1], pos, local); + } + let mut expr = expr; + loop { + let n = expr.bytes().take_while(|&c| is_ident(c) || c >= 0x80).count(); + if n == 0 || !expr.as_bytes()[0].is_ascii_lowercase() || !expr[n..].starts_with("::") { + break; + } + expr = &expr[n + 2..]; + } + let n = expr.bytes().take_while(|&c| is_ident(c) || c >= 0x80).count(); + if n == 0 || expr.as_bytes()[0].is_ascii_digit() { + return false; + } + let (name, after) = expr.split_at(n); + if user_type(name) { + return true; + } + if after.starts_with(['(', '!', ':']) || screaming_or_camel(name) || PLAIN_NAMES.contains(&name) { + return false; + } + local(name, pos).is_some_and(|(user, _, _)| user) +} + +/// Whether a fixture value contains a user value, including nested containers and local aliases. +fn holds_user_value(expr: &str, pos: usize, local: &LocalAt) -> bool { + let expr = expr.trim_start_matches(['&', '*']); + if let Some(receiver) = [".as_slice()", ".as_ref()", ".clone()", ".to_vec()", ".to_owned()"].iter().find_map(|suffix| expr.strip_suffix(suffix)) { + return holds_user_value(receiver, pos, local); + } + if let Some((base, field)) = last_field(expr) { + return field_value(base, field, pos, local).is_some_and(|(v, at)| holds_user_value(&v, at, local)); + } + // Non-ASCII letters (`数`) are part of a name, as in [`inert`]. + if !expr.is_empty() && !expr.as_bytes()[0].is_ascii_digit() && expr.bytes().all(|c| is_ident(c) || c >= 0x80) { + return user_value(expr, pos, local) || local(expr, pos).is_some_and(|(_, init, at)| holds_user_value(&init, at, local)); + } + let b = expr.as_bytes(); + let Some(open) = b.iter().position(|c| matches!(c, b'(' | b'[' | b'{')) else { return user_value(expr, pos, local) }; + let Some(close) = matching(b, open) else { return false }; + // An element indexed out of a local (`xs[0]`, `数[0]`, `rows[1][2]`) is a user value when the + // local's value holds one. + if b[open] == b'[' + && let Some(name) = indexed_local(expr) + { + return holds_user_value(name, pos, local); + } + // Only a whole container exposes its elements, not the result of a method such as `len`. + if close + 1 != b.len() || expr[..open].bytes().any(|c| !is_ident(c) && !matches!(c, b':' | b'!')) { + return false; + } + if user_value(expr, pos, local) { + return true; + } + split_args(b, open + 1, close).into_iter().any(|(from, to)| { + let arg = &expr[from..to]; + // A repeated array or vector contains the value before its top-level semicolon. + let end = top_level_at(arg, ";").first().copied().unwrap_or(arg.len()); + holds_user_value(&arg[..end], pos, local) + }) +} + +/// The base and the field of a whitespace-free expression that ends with a field read: `input` and +/// `n` of `input.n`, `pair` and `0` of `pair.0`. Not a range (`0..n`). +fn last_field(expr: &str) -> Option<(&str, &str)> { + let n = expr.bytes().rev().take_while(|&c| is_ident(c) || c >= 0x80).count(); + let dot = expr.len().checked_sub(n + 1)?; + (n > 0 && expr.as_bytes()[dot] == b'.' && dot > 0 && expr.as_bytes()[dot - 1] != b'.').then(|| (&expr[..dot], &expr[dot + 1..])) +} + +/// The expression a struct literal or tuple constructor gives `field` when `base` (a local, a field +/// read or the literal itself) is one: `5` for `input.n` after `let input = Input { n: 5 };`. +/// Local aliases resolve at their own binding positions. The expression comes with the position +/// where its names are resolved. +fn field_value(base: &str, field: &str, pos: usize, local: &LocalAt) -> Option<(String, usize)> { + let base = base.trim_start_matches(['&', '*']); + let (value, at) = if let Some((b, f)) = last_field(base) { + field_value(b, f, pos, local)? + } else if plain_local(base) && base.as_bytes()[0].is_ascii_lowercase() { + let (_, init, at) = local(base, pos)?; + return field_value(&init, field, at, local); + } else { + (base.to_owned(), pos) + }; + let v = value.as_bytes(); + let open = v.iter().take_while(|&&c| is_ident(c) || c == b':').count(); + // A tuple literal (`(5, Kind::A)`) has no name before its parenthesis. + let tuple = open == 0 && v.first() == Some(&b'('); + if (open == 0 && !tuple) || !matches!(v.get(open), Some(b'{' | b'(')) || matching(v, open) != Some(v.len() - 1) { + return None; + } + let args = split_args(v, open + 1, v.len() - 1); + // Parentheses around one expression without a comma only group it. + if tuple && args.len() < 2 && !value[..v.len() - 1].trim_end().ends_with(',') { + return None; + } + let text = |&(a, b): &(usize, usize)| value[a..b].to_owned(); + if v[open] == b'(' { + return args.get(field.parse::().ok()?).map(|arg| (text(arg), at)); + } + args.iter() + .map(text) + .find_map(|arg| match arg.split_once(':') { + Some((name, rest)) if name == field && !rest.starts_with(':') => Some(rest.to_owned()), + None if arg == field => Some(arg), + _ => None, + }) + .map(|value| (value, at)) } /// `s` with every `::<…>` turbofish removed: `Vec::::new` becomes `Vec::new`. @@ -6012,15 +7324,7 @@ fn without_turbofish(s: &str) -> String { fn reaching_init(body: &[u8], name: &str, before: usize) -> Option> { let found = let_init(body, name, before); // A `for` pattern binds its names inside the loop body only, to values the loop produces. - let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| { - // `in` is found as a word outside the pattern's brackets, so a line break around it still - // ends the pattern, and the braces of `for Row { n } in …` are not the loop body. - let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false }; - let Some((open, close)) = block_after(body, kw + 2) else { return false }; - // Words stay apart, so `mut n` binds `n`. - let pattern = norm_words(&body[at + 3..kw]); - open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() - }); + let loop_at = for_binding(body, name, before); // A match arm's pattern binds its names inside that arm only, and a closure's parameters // inside its body only. let inner = loop_at.max(arm_binding(body, name, before)).max(closure_binding(body, name, before)); @@ -6031,6 +7335,20 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option { + words(body, b"for", 0, before).into_iter().rev().find(|&at| { + // `in` is found as a word outside the pattern's brackets, so a line break around it still + // ends the pattern, and the braces of `for Row { n } in …` are not the loop body. + let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false }; + // A block expression as the iterator (`for n in { … } { … }`) comes before the loop body. + let iter = skip_ws(body, kw + 2); + let iter = if body.get(iter) == Some(&b'{') { matching(body, iter).map_or(iter, |close| close + 1) } else { iter }; + let Some((open, close)) = block_after(body, iter) else { return false }; + open < before && before < close && pattern_binds(body, name.as_bytes(), at + 3, kw) + }) +} + /// The offset of the parameter list of the innermost closure whose parameters bind `name` and whose /// body holds `before`: `for_each(|n| assert_eq!(n, 1))` binds `n`. fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { @@ -6122,14 +7440,7 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { if guard >= before { continue; } - let pattern = norm_words(&body[start..guard]); - 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)) { + if !pattern_binds(body, name.as_bytes(), start, guard) { continue; } // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. @@ -6168,7 +7479,7 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u let start = skip_ws(body, at + 3); let is_mut = body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace); let n0 = if is_mut { skip_ws(body, start + 3) } else { start }; - let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c)).count(); + let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); let head = body[..at].trim_ascii_end(); let keyword = [&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); @@ -6269,15 +7580,15 @@ fn block_close(body: &[u8], at: usize) -> usize { } /// `inert` for an operand of the test at `pos`, resolving locals through their initializers. -fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option { - let local = |name: &str| -> Option { +fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option<(bool, bool)> { + let local = |name: &str, before: usize| -> Option<(bool, String, usize)> { if depth > 8 { return None; } - let (init, at) = reaching_init(body, name, pos)??; - inert_at(body, &init, at, depth + 1).map(|_| true) + let (init, at) = reaching_init(body, name, before)??; + inert_at(body, &init, at, depth + 1).map(|(_, user)| (user, init, at)) }; - inert(op, &local) + inert(op, pos, &local) } /// `constant-echo` and `fixture-only`: every assertion of the test reads only constants and @@ -6298,7 +7609,7 @@ fn echoes(v: &View) -> Option { } for &(from, to) in a.args.iter().take(n) { let op = norm(&body[from - v.t.open..to - v.t.open]); - reads_local |= inert_at(&body, &op, from - v.t.open, 0)?; + reads_local |= inert_at(&body, &op, from - v.t.open, 0)?.0; } } Some(if reads_local { @@ -6558,10 +7869,15 @@ fn cfg_spans(m: &[u8], src: &[u8]) -> Vec { 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), - _ => continue, + let Some(stop) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + // A function's signature can hold `;` (`-> [u8; 2]`), so its body is found as `fn_after` finds it. + let open = match words(m, b"fn", after, stop).first() { + Some(&kw) => body_open(m, kw + 2), + None => (m[stop] == b'{').then_some(stop), + }; + match open.and_then(|open| matching(m, open)) { + Some(close) => (at, close), + None => continue, } }; out.push(CfgSpan { pred, at, end, span }); @@ -6851,7 +8167,8 @@ fn path_arg(arg: &str) -> Option { } /// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and -/// path. +/// path. A nested `cfg_attr` adds its condition to the enclosing ones: +/// `cfg_attr(test, cfg_attr(unix, path = "p.rs"))` gives `all(test,unix)`. fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { let mut out = vec![]; for at in words(m, b"cfg_attr", from, to) { @@ -6861,16 +8178,30 @@ 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 = 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; - for cut in cuts[1..].iter().copied().chain([text.len()]) { - let arg = text.get(start..cut).unwrap_or(""); - if let Some(rel) = path_arg(arg) { - out.push((text[..first].to_owned(), rel)); - } - start = cut + 1; + out.extend(cfg_attr_path_args(&text, None)); + } + out +} + +/// The `path = "…"` arguments of the whitespace-free arguments `text` of a `cfg_attr(…)`, each with +/// its condition joined to the enclosing ones (`outer`). +fn cfg_attr_path_args(text: &str, outer: Option<&str>) -> Vec<(String, String)> { + let cuts = attr_commas(text); + let Some(&first) = cuts.first() else { return vec![] }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut out = vec![]; + 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(rel) = path_arg(arg) { + out.push((cond.clone(), rel)); + } else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) { + out.extend(cfg_attr_path_args(n, Some(&cond))); } + start = cut + 1; } out } @@ -7202,17 +8533,17 @@ fn exact_pixels(v: &View) -> Vec { .iter() .filter_map(|a| { let arg = |i: usize| a.args.get(i).map(|&(f, t)| norm(&v.file.m[f..t])); - let (l, r) = if a.name.ends_with("_eq") { - (arg(0)?, arg(1)?) + let ((l, r), last) = if a.name.ends_with("_eq") { + ((arg(0)?, arg(1)?), *a.args.get(1)?) } else if PLAIN_ASSERTS.contains(&a.name.as_str()) { let cond = arg(0)?; let at = *top_level_at(&cond, "==").first()?; - (cond[..at].to_owned(), cond[at + 2..].to_owned()) + ((cond[..at].to_owned(), cond[at + 2..].to_owned()), *a.args.first()?) } else { 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))) + pixel.then(|| v.hit_through(a.at, last, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) }) .collect() } @@ -7234,12 +8565,113 @@ mod tests { lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect() } + /// A new directory under the system temporary directory, created for this guard alone and + /// removed when the guard is dropped, including when an assertion fails. + struct TempRepo(tempfile::TempDir); + + impl TempRepo { + fn new(name: &str) -> Self { + Self(tempfile::Builder::new().prefix(&format!("test-lint-{name}-")).tempdir().unwrap()) + } + } + + impl std::ops::Deref for TempRepo { + type Target = Path; + + fn deref(&self) -> &Path { + self.0.path() + } + } + + #[test] + fn a_direct_length_guard_counts_the_items_each_view_needs() { + let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + let chunked = good.replace("xs.iter().all(|x| *x > 0)", "xs.as_chunks::<2>().0.iter().all(|[a, b]| a == b)"); + let short_chunks = chunked.replace("assert_eq!(xs.len(), 3);", "assert_eq!(xs.len(), 1);"); + assert_eq!(hits(&short_chunks), [(5, "all-unguarded")], "one item makes no chunk of two"); + for view in ["xs.windows(2).all(|w| w[0] < w[1])", "xs.chunks_exact(2).all(|c| c[0] < c[1])"] { + let short = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!(xs.len(), 1);").replace("xs.iter().all(|x| *x > 0)", view); + assert_eq!(hits(&short), [(5, "all-unguarded")], "{view} after a length of one"); + let long = short.replace("assert_eq!(xs.len(), 1);", "assert!(xs.len() >= 2);"); + assert_eq!(hits(&long), [], "{view} after a length of at least two"); + let joined = format!("#[test]\nfn t() {{\n let xs = f();\n assert!(xs.len() >= 2 && {view});\n}}\n"); + assert_eq!(hits(&joined), [], "{view} in the same condition as a length of at least two"); + let reversed = joined.replace("xs.len() >= 2", "2 <= xs.len()"); + assert_eq!(hits(&reversed), [], "{view} after a reversed comparison"); + let strict = short.replace("assert_eq!(xs.len(), 1);", "assert!(xs.len() > 1);"); + assert_eq!(hits(&strict), [], "{view} after a length of more than one"); + let strict_reversed = short.replace("assert_eq!(xs.len(), 1);", "assert!(1 < xs.len());"); + assert_eq!(hits(&strict_reversed), [], "{view} after a reversed strict comparison"); + let strict_short = short.replace("assert_eq!(xs.len(), 1);", "assert!(xs.len() > 0);"); + assert_eq!(hits(&strict_short), [(5, "all-unguarded")], "{view} after a length of more than zero"); + let unbounded = joined.replace("xs.len() >= 2", "xs.len() > 0xffff_ffff_ffff_ffffusize"); + assert_eq!(hits(&unbounded), [(4, "all-unguarded")], "{view} after a strict bound past the largest length"); + } + let counted = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!(xs.iter().count(), 3);"); + assert_eq!(hits(&counted), [], "a count of the local's iterator"); + let counted_cleared = counted.replace(" assert!(xs", " xs.clear();\n assert!(xs"); + assert_eq!(hits(&counted_cleared), [(6, "all-unguarded")], "a count of the local's iterator before a clear"); + } + #[test] fn all_needs_a_non_empty_guard() { let bad = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; assert_eq!(hits(bad), [(4, "all-unguarded")]); let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; assert_eq!(hits(good), []); + let cleared = good.replace(" assert!(xs", " xs.clear();\n assert!(xs"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "a length check of a collection cleared after it"); + let field = good.replace(" assert!(xs", " other.xs.clear();\n assert!(xs"); + assert_eq!(hits(&field), [], "a field cleared after checking the local's length"); + let path = good.replace(" assert!(xs", " other:: xs.clear();\n assert!(xs"); + assert_eq!(hits(&path), [], "a path cleared after checking the local's length"); + let saved = good.replace("assert_eq!(xs.len(), 3);", "let n = xs.len(); assert_eq!(n, 3); other.xs.clear();"); + assert_eq!(hits(&saved), [], "a field cleared after checking the local's saved length"); + let count = good.replace("assert_eq!(xs.len(), 3);", "let n = xs.len(); assert_eq!(n, 3);"); + assert_eq!(hits(&count), [], "an assertion on the saved length"); + let range = count.replace("assert_eq!(n, 3)", "assert_eq!(0..n, 0..3)"); + assert_eq!(hits(&range), [], "a range equality reads the saved length"); + let inclusive = range.replace("0..", "0..="); + assert_eq!(hits(&inclusive), [], "an inclusive range equality reads the saved length"); + let drained = good.replace(" assert!(xs", " let _ = 0..xs.drain(..).count();\n assert!(xs"); + assert_eq!(hits(&drained), [(6, "all-unguarded")], "a range operand drains the collection after its length check"); + let count_field = count.replace("assert_eq!(n, 3)", "assert_eq!(other.n, 3)"); + assert_eq!(hits(&count_field), [(5, "all-unguarded")], "a field is not the saved length"); + let spaced_count_field = count_field.replace("other.n", "other. n"); + assert_eq!(hits(&spaced_count_field), [(5, "all-unguarded")], "whitespace before the field name"); + let count_path = count.replace("assert_eq!(n, 3)", "assert_eq!(other::n, 3)"); + assert_eq!(hits(&count_path), [(5, "all-unguarded")], "a path is not the saved length"); + let spaced_count_path = count_path.replace("other::n", "other:: n"); + assert_eq!(hits(&spaced_count_path), [(5, "all-unguarded")], "whitespace before the path segment"); + let replaced = good.replace(" assert!(xs", " xs = g();\n assert!(xs"); + assert_eq!(hits(&replaced), [(6, "all-unguarded")], "a length check of a collection replaced after it"); + let sorted = good.replace(" assert!(xs", " xs.sort();\n assert!(xs"); + assert_eq!(hits(&sorted), [], "a call that keeps every item"); + let cleaned = good.replace("> 0));\n", "> 0));\n xs.clear();\n"); + assert_eq!(hits(&cleaned), [], "a collection cleared after the assertion it guards"); + let between = good.replace("> 0));\n", "> 0));\n xs.clear();\n assert!(xs.iter().all(|x| *x > 1));\n"); + assert_eq!(hits(&between), [(7, "all-unguarded")], "only the assertion after the clear"); + } + + #[test] + fn a_later_or_inner_length_check_guards_all_while_the_collection_holds() { + let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + let later = "#[test]\nfn t() {\n let mut xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n assert_eq!(xs.len(), 3);\n}\n"; + assert_eq!(hits(later), [], "a later length check with nothing between"); + let later_pushed = later.replace(" assert_eq!(xs.len()", " xs.push(1);\n assert_eq!(xs.len()"); + assert_eq!(hits(&later_pushed), [(4, "all-unguarded")], "a later length check after a push"); + let later_replaced = later.replace(" assert_eq!(xs.len()", " xs = g();\n assert_eq!(xs.len()"); + assert_eq!(hits(&later_replaced), [(4, "all-unguarded")], "a later length check after a replacement"); + let inside = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!({ let n = xs.len(); xs.clear(); n }, 3);"); + assert_eq!(hits(&inside), [(5, "all-unguarded")], "an operand that clears the collection after reading its length"); + let field_inside = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!({ let n = xs.len(); other.xs.clear(); n }, 3);"); + assert_eq!(hits(&field_inside), [], "an operand that clears a field after reading the local's length"); + let spaced_field = field_inside.replace("other.xs", "other. xs"); + assert_eq!(hits(&spaced_field), [], "whitespace before the field name"); + let refreshed = good.replace("assert_eq!(xs.len(), 3);", "assert_eq!({ xs = g(); xs.len() }, 3);"); + assert_eq!(hits(&refreshed), [], "an operand that replaces the collection before reading its length"); + let chunked = good.replace("xs.iter().all(|x| *x > 0)", "xs.as_chunks::<2>().0.iter().all(|[a, b]| a == b)"); + assert_eq!(hits(&chunked), [], "a turbofish view in the assertion itself"); let inner = "#[test]\nfn t() {\n assert!(rows().iter().all(|r| r.len() == 3));\n}\n"; assert_eq!(hits(inner), [(3, "all-unguarded")], "a length inside the predicate is about each item"); let none = "#[test]\nfn t() {\n assert!(warnings().iter().all(|w| !w.contains(\"lost\")), \"no warning\");\n}\n"; @@ -7252,6 +8684,20 @@ mod tests { assert_eq!(hits(mixed), [(3, "all-unguarded")]); } + #[test] + fn mutation_checks_distinguish_locals_from_fields() { + assert!(!may_change(b"other. xs = next();", b"xs", 0, false)); + assert!(!may_change(b"other:: xs = next();", b"xs", 0, false)); + assert!(may_change(b"xs = next();", b"xs", 0, false)); + assert!(!may_change(b"use_it(&mut other.xs);", b"xs", 0, false)); + assert!(may_change(b"use_it(&mut xs);", b"xs", 0, false)); + assert!(!may_change(b"other.xs.push(1);", b"xs", 0, false)); + assert!(may_change(b"xs.push(1);", b"xs", 0, false)); + assert!(may_change(b"let _ = 0..xs.drain(..);", b"xs", 0, false)); + assert!(may_change(b"let _ = 0..=xs.drain(..).count();", b"xs", 0, false)); + assert!(may_shrink(b"holder.other.xs.clear();", b"other.xs", 0)); + } + #[test] fn census_round_trips_look_up_the_entry() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -8046,8 +9492,15 @@ mod tests { #[test] fn all_guards_accept_first_item_access_that_fails_when_empty() { - for expr in ["xs[0]", "xs.first().unwrap()", "xs.first().expect(\"item\")", "xs.iter().next().unwrap()", "xs.iter().next().expect(\"item\")"] - { + for expr in [ + "xs[0]", + "xs[1]", + "xs[12]", + "xs.first().unwrap()", + "xs.first().expect(\"item\")", + "xs.iter().next().unwrap()", + "xs.iter().next().expect(\"item\")", + ] { let good = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); assert_eq!(hits(&good), [], "{expr} fails when empty"); let inner = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| {expr} > 0));\n}}\n"); @@ -8057,6 +9510,18 @@ mod tests { } let literal = "#[test]\nfn t() {\n let _ = [0];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; assert_eq!(hits(literal), [(4, "all-unguarded")], "an array literal does not access an item"); + let other = literal.replace("[0]", "[3]"); + assert_eq!(hits(&other), [(4, "all-unguarded")], "an array literal of another number does not access an item"); + let range = "#[test]\nfn t() {\n let _ = &xs[1..];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(range), [(4, "all-unguarded")], "a slice range is not an item access"); + let item = "#[test]\nfn t() {\n assert!(rows()[0].iter().all(|r| r.ok));\n}\n"; + assert_eq!(hits(item), [(3, "all-unguarded")], "indexing the collection `.all` reads checks only the outer one"); + for view in ["iter_mut()", "windows(2)", "chunks(2)"] { + let inner = item.replace("iter()", view); + assert_eq!(hits(&inner), [(3, "all-unguarded")], "an item read through {view}"); + } + let summed = "#[test]\nfn t() {\n let sum: u8 = rows[0].iter().sum();\n assert_eq!(sum, 6);\n assert!(rows.iter().all(|r| r.len() == 3));\n}\n"; + assert_eq!(hits(summed), [], "an item iterated for another call still shows that the outer collection has items"); } #[test] @@ -8067,6 +9532,12 @@ mod tests { assert_eq!(hits(bad), [(4, "all-unguarded")]); } + #[test] + fn a_first_callback_call_guards_the_callback_collection() { + let src = "#[test]\nfn t() {\n let callbacks = callbacks();\n callbacks[0]();\n assert!(callbacks.iter().all(|f| f() > 0));\n}\n"; + assert_eq!(only("all-unguarded", src), []); + } + #[test] fn all_hits_count_changes_anywhere_in_their_test() { let src = "#[should_panic]\n#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\nfn other() {}\n"; @@ -8080,7 +9551,7 @@ mod tests { } assert!(!touches(&found[0], Some(&[7].into_iter().collect())), "another function is outside the test"); let diff = "diff --git a/crates/x/src/tests.rs b/crates/x/src/tests.rs\n--- a/crates/x/src/tests.rs\n+++ b/crates/x/src/tests.rs\n@@ -5 +4,0 @@\n- assert!(!xs.is_empty());\n"; - let changed = parse_diff(diff); + let changed = parse_diff(diff, &|_, _| false); assert!(touches(&found[0], changed["crates/x/src/tests.rs"].as_ref()), "removing a guard changes the test"); } @@ -8116,8 +9587,32 @@ mod tests { fn functions_declared_in_a_test_count_only_when_called() { let unused = "#[test]\nfn t() {\n fn unused() {\n assert_eq!(1, 1);\n }\n assert!(parse(\"x\").is_ok());\n}\n"; assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); + let array_return = + unused.replace("fn unused() {\n assert_eq!(1, 1);", "fn unused() -> [u8; 1] {\n assert_eq!(1, 1);\n [1]"); + assert_eq!(hits(&array_return), [(2, "only-weak")], "a declared function with an array return type"); let macro_only = "#[test]\nfn t() {\n macro_rules! check {\n () => { assert_eq!(1, 1) };\n }\n f();\n}\n"; assert_eq!(hits(macro_only), [(2, "no-assertion")], "a declared macro's assertion does not run"); + for dropped in [ + "let _ = async { assert_eq!(f(), 1); };", + "let _ = async move { assert_eq!(f(), 1); };", + "let _ = || assert_eq!(f(), 1);", + "let _ = move |x| assert_eq!(x, 1);", + "let _ = async || assert_eq!(f(), 1);", + "let _ = async move |x| assert_eq!(x, 1);", + "let _ = (|| { assert_eq!(f(), 1); });", + "let _ = ((async { assert_eq!(f(), 1); }));", + ] { + let src = format!("#[test]\nfn t() {{\n {dropped}\n}}\n"); + assert_eq!(hits(&src), [(2, "no-assertion")], "{dropped}"); + } + let kept = "#[test]\nfn t() {\n let check = || assert_eq!(f(), 1);\n check();\n}\n"; + assert_eq!(hits(kept), [], "a named closure can be called"); + let awaited = "#[test]\nfn t() {\n let _ = async { assert_eq!(f(), 1); }.await;\n}\n"; + assert_eq!(hits(awaited), [], "an awaited block runs"); + let invoked = "#[test]\nfn t() {\n let _ = (|| { assert_eq!(f(), 1); })();\n}\n"; + assert_eq!(hits(invoked), [], "a grouped closure that is called runs"); + let conditional = "#[test]\nfn t() {\n if let _ = || () {\n assert_eq!(f(), 1);\n };\n}\n"; + assert_eq!(hits(conditional), [], "an `if let` pattern is not a statement"); let called = unused.replace(" assert!(parse", " unused();\n assert!(parse"); let files = [("crates/x/src/tests.rs".to_owned(), called.clone())]; let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; @@ -8183,6 +9678,26 @@ mod tests { assert_eq!(hits(good), []); } + #[test] + fn process_status_checks_require_every_boolean_operand_to_check_status() { + let good = "#[test]\nfn t() {\n let status = Command::new(\"cp\").arg(src).arg(&destination).status().unwrap();\n assert!(status.success() && destination.exists());\n}\n"; + assert_eq!(hits(good), []); + let borrowed = good.replace("status.success() && destination.exists()", "status.success() && &actual == &expected"); + assert_eq!(hits(&borrowed), []); + for condition in [ + "status.success() && status.code() == Some(0)", + "status.success()", + "status.success() || destination.exists()", + "status.success() && (status.code() == Some(0) || destination.exists())", + ] { + let bad = good.replace("status.success() && destination.exists()", condition); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{condition}"); + } + let grouped = + good.replace("status.success() && destination.exists()", "status.success() && (destination.exists() && status.code() == Some(0))"); + assert_eq!(hits(&grouped), [], "a grouped conjunction that checks the destination"); + } + #[test] fn process_status_checks_accept_every_comparison_assertion() { for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { @@ -8290,7 +9805,7 @@ mod tests { #[test] fn assertion_arguments_keep_turbofish_groups_and_split_comparisons() { - for operand in ["f::()", "f::>()", "f :: ()"] { + for operand in ["f::()", "f::>()", "f :: ()", "

>::VALUE", "&

>::get()"] { let src = format!("{operand}, expected, message"); let m = mask(&src); let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| src[from..to].trim()).collect(); @@ -8300,6 +9815,11 @@ mod tests { let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| comparison[from..to].trim()).collect(); assert_eq!(args, ["a < b", &format!("{operand} > c"), "message"], "comparisons around {operand}"); } + let shift = "a << b, c"; + let m = mask(shift); + assert_eq!(split_args(&m, 0, m.len()).len(), 2, "a shift opens no generic arguments"); + let qualified = "#[test]\nfn t() {\n assert_eq!(>::VALUE, read_value());\n}\n"; + assert_eq!(only("constant-echo", qualified), [], "the second operand is a computed value, not a message"); } #[test] @@ -8524,7 +10044,7 @@ mod tests { #[test] fn changed_lines_come_from_the_new_side_of_each_hunk() { let diff = "diff --git a/crates/x/src/a.rs b/crates/x/src/a.rs\nindex 1..2 100644\n--- a/crates/x/src/a.rs\n+++ b/crates/x/src/a.rs\n@@ -3,0 +4,2 @@ fn f() {\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,2 +21,0 @@\n-e\ndiff --git a/crates/x/src/n.rs b/crates/x/src/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/crates/x/src/n.rs\n@@ -0,0 +1,3 @@\n"; - let got = parse_diff(diff); + let got = parse_diff(diff, &|_, _| false); 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); @@ -8541,7 +10061,7 @@ mod tests { assert_eq!(found.len(), 2); let old = anchor + 1; let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -{old} +{anchor},0 @@\n-#[should_panic]\n"); - let changed = parse_diff(&diff); + let changed = parse_diff(&diff, &|_, _| false); let expected = if anchor == 0 { vec![1] } else { vec![anchor, anchor + 1] }; assert_eq!(changed[path], Some(expected.into_iter().collect())); assert_eq!(found[0].rule, Rule::NoAssertion); @@ -8620,6 +10140,7 @@ mod tests { " run: MY_SAMPLES=value cargo test", " echo \"MY_SAMPLES=value\" >> \"$GITHUB_ENV\"", " echo 'MY_SAMPLES=value' >> \"$GITHUB_ENV\"", + " echo \"MY_SAMPLES=fixtures\" | tee -a \"$GITHUB_ENV\"", " MY_SAMPLES=value # OTHER_SAMPLES=value", " MY_SAMPLES=\"#value\"", " MY_SAMPLES=", @@ -8633,6 +10154,61 @@ mod tests { assert_eq!(upper_words(reads).collect::>(), Vec::::new()); } + #[test] + fn powershell_environment_file_writes_set_workflow_variables() { + for line in [ + " echo \"MY_SAMPLES=fixtures\" >> $env:GITHUB_ENV", + " echo \"MY_SAMPLES=fixtures\" >> \"$env:GITHUB_ENV\"", + " echo \"MY_SAMPLES=fixtures\" >> ${env:GITHUB_ENV}", + " echo \"MY_SAMPLES=fixtures\" >> \"${env:GITHUB_ENV}\"", + " \"MY_SAMPLES=fixtures\" | Out-File -FilePath $env:GITHUB_ENV -Append", + " echo \"MY_SAMPLES=fixtures\" | Out-File -Append -FilePath \"$env:GITHUB_ENV\"", + " Add-Content -Path $env:GITHUB_ENV -Value \"MY_SAMPLES=fixtures\"", + " \"MY_SAMPLES=fixtures\" | Add-Content -Path ${env:GITHUB_ENV}", + " \"MY_SAMPLES=fixtures\" | out-file -filepath $env:GITHUB_ENV -append", + " \"MY_SAMPLES=fixtures\" | OUT-FILE -FILEPATH $env:GITHUB_ENV -APPEND", + " add-content -path $env:GITHUB_ENV -value \"MY_SAMPLES=fixtures\"", + " AdD-CoNtEnT -pAtH $env:GITHUB_ENV -vAlUe \"MY_SAMPLES=fixtures\"", + ] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn a_comment_in_a_decoded_run_script_ends_at_its_line_break() { + for line in + ["run: \"echo starting # setup\\nexport MY_SAMPLES=fixtures\\ncargo test\"", "run: \"echo starting\\nMY_SAMPLES=fixtures cargo test\""] + { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + let quoted = "run: \"export msg=\\\"hello\\n# world\\\"\\nMY_SAMPLES=fixtures cargo test\""; + assert_eq!(upper_words(quoted).collect::>(), ["MY_SAMPLES"], "a `#` inside a quoted value that spans lines"); + let commented = "run: \"echo starting # MY_SAMPLES=fixtures\\ncargo test\""; + assert_eq!(upper_words(commented).collect::>(), Vec::::new()); + let continued = "run: \"echo \\\\\\nMY_SAMPLES=fixtures\""; + assert_eq!(upper_words(continued).collect::>(), Vec::::new(), "a continued `echo` prints the text"); + } + + #[test] + fn quoted_yaml_scalars_are_decoded_before_shell_assignments() { + for line in [ + "run: 'export MY_SAMPLES=fixtures; cargo test'", + "- run: \"export MY_SAMPLES=fixtures; cargo test\"", + "run: 'export MY_SAMPLES=fixtures; echo ''done'''", + "run: \"export MY_SAMPLES=fixtures; echo \\\"done\\\"\"", + ] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + for line in [ + "run: 'message=\"MY_SAMPLES=fixtures\"'", + "run: \"message=\\\"MY_SAMPLES=fixtures\\\"\"", + "name: 'Test with MY_SAMPLES=fixtures'", + "- name: \"Test with MY_SAMPLES=fixtures\"", + ] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + } + #[test] fn workflow_mentions_do_not_suppress_unset_gates() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; @@ -8653,18 +10229,73 @@ mod tests { { assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); } - for line in [" echo hi; MY_SAMPLES=x cargo test", " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\""] { + for line in [ + " echo hi; MY_SAMPLES=x cargo test", + " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\"", + " printf '%s; ' x; MY_SAMPLES=x cargo test", + " { echo MY_SAMPLES=x; echo OTHER=1; } >> \"$GITHUB_ENV\"", + ] { + assert!(upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } + for line in [ + " printf '%s; ' MY_SAMPLES=fixtures", + " printf \"%s | \" MY_SAMPLES=fixtures", + "run: \"echo MY_SAMPLES=fixtures\\necho OTHER=1 >> \\\"$GITHUB_ENV\\\"\"", + " echo MY_SAMPLES=fixtures; echo OTHER=1 >> \"$GITHUB_ENV\"", + ] { + assert!(!upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } + } + + #[test] + fn quoted_search_patterns_set_no_workflow_variable() { + for line in [" grep \"MY_SAMPLES=fixtures\" settings.txt", "run: grep 'MY_SAMPLES=fixtures' settings.txt; export OTHER=1"] { + assert!(!upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } + } + + #[test] + fn a_hash_inside_a_shell_word_starts_no_comment() { + for line in ["run: \"export note=one#two; MY_SAMPLES=fixtures cargo test\"", "run: export note=one#two; MY_SAMPLES=fixtures cargo test"] { assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); } + for line in ["run: \"export note=one #MY_SAMPLES=fixtures\"", "run: export note=one;#MY_SAMPLES=fixtures"] { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + } + + #[test] + fn quoted_assignment_command_arguments_set_workflow_variables() { + for line in [ + "run: export \"MY_SAMPLES=fixtures\"", + "run: export 'MY_SAMPLES=fixtures'", + "run: env \"MY_SAMPLES=fixtures\" cargo test", + "run: declare -x \"MY_SAMPLES=x\"", + "run: typeset -x \"MY_SAMPLES=x\"", + "run: local \"MY_SAMPLES=fixtures\"", + "run: readonly 'MY_SAMPLES=fixtures'", + "run: true; export \"MY_SAMPLES=fixtures\"", + "run: if true; then export \"MY_SAMPLES=fixtures\"; fi", + "run: while c; do env \"MY_SAMPLES=x\" cmd; done", + "run: ! command env \"MY_SAMPLES=x\" cmd", + "run: true && env \"MY_SAMPLES=fixtures\" cargo test", + "run: true | env \"MY_SAMPLES=fixtures\" cargo test", + "run: export OTHER='a;b&c|d' \"MY_SAMPLES=fixtures\"", + "run: 'export \"MY_SAMPLES=fixtures\"'", + "- run: \"export 'MY_SAMPLES=fixtures'\"", + ] { + assert!(upper_words(line).any(|name| name == "MY_SAMPLES"), "{line}"); + } } #[test] fn patch_labels_are_decoded_before_filtering() { let diff = "diff --git a/crates/x/tests/two words.rs b/crates/x/tests/two words.rs\n--- a/crates/x/tests/two words.rs\t\n+++ b/crates/x/tests/two words.rs\t\n@@ -1 +1 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/q\\\"t.rs\" \"b/crates/x/tests/q\\\"t.rs\"\n--- \"a/crates/x/tests/q\\\"t.rs\"\n+++ \"b/crates/x/tests/q\\\"t.rs\"\n@@ -2 +2 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/caf\\303\\251.rs\" \"b/crates/x/tests/caf\\303\\251.rs\"\n--- \"a/crates/x/tests/caf\\303\\251.rs\"\n+++ \"b/crates/x/tests/caf\\303\\251.rs\"\n@@ -3 +3 @@\n-a\n+b\n"; - let got = parse_diff(diff); + let got = parse_diff(diff, &|_, _| false); assert_eq!(got.get("crates/x/tests/two words.rs"), Some(&Some([1].into_iter().collect())), "{got:?}"); assert_eq!(got.get("crates/x/tests/q\"t.rs"), Some(&Some([2].into_iter().collect())), "{got:?}"); assert_eq!(got.get("crates/x/tests/caf\u{e9}.rs"), Some(&Some([3].into_iter().collect())), "{got:?}"); + assert_eq!(got.len(), 3, "{got:?}"); assert!(got.keys().all(|p| is_scanned(p)), "{got:?}"); } @@ -8678,6 +10309,20 @@ mod tests { assert_eq!(hits(inner), [(9, "no-assertion")], "#[should_panic] before #[test] still belongs to the test"); } + #[test] + fn signature_delimiters_do_not_hide_test_bodies() { + let array = "#[test_case([1, 2])]\nfn t(xs: [u8; 2]) {}\n"; + assert_eq!(hits(array), [(2, "no-assertion")], "array parameter"); + let result = "#[test]\nfn t() -> Result<[u8; 2], ()> {\n Ok([1, 2])\n}\n"; + assert_eq!(hits(result), [(2, "no-assertion")], "array type in generic arguments"); + let array_result = "#[test]\nfn t() -> [u8; 2] {\n [1, 2]\n}\n"; + assert_eq!(hits(array_result), [(2, "no-assertion")], "array return type"); + let braced = "#[test]\nfn t() -> Foo<{ assert!(true); 2 }> {}\n"; + assert_eq!(hits(braced), [(2, "no-assertion")], "braced const argument"); + let arrow = "#[test]\nfn t u8>() {}\n"; + assert_eq!(hits(arrow), [(2, "no-assertion")], "arrow inside generics"); + } + #[test] fn helpers_with_a_shared_name_count_only_when_each_asserts() { let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; @@ -8860,6 +10505,15 @@ mod tests { assert_eq!(lint_file("crates/x/src/tests.rs", src, &ctx()).iter().map(|h| (h.line, h.test.as_str())).collect::>(), [(2, "échec")]); } + #[test] + fn helpers_with_non_ascii_names_count_as_checks() { + let src = "fn vérifier(a: u8) {\n assert_eq!(a, 1);\n}\n#[test]\nfn t() {\n vérifier(f());\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(helpers["crates/x"].contains("vérifier"), "{helpers:?}"); + let ctx = Ctx { helpers, ..Ctx::default() }; + assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); + } + #[test] fn block_comment_allows_need_a_reason_before_the_closing_delimiter() { let bare = "#[test]\nfn t() {\n thread::sleep(D); /* test-lint: allow sleep */\n assert_eq!(f(), 1);\n}\n"; @@ -8891,6 +10545,16 @@ mod tests { assert_eq!(hits(&cleared), [(7, "all-unguarded")]); } + #[test] + fn a_count_stops_guarding_when_its_grouped_collection_changes() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + for call in ["(xs).clear();", "((xs)).clear();"] { + let changed = src.replace(" assert!(xs", &format!(" {call}\n assert!(xs")); + assert_eq!(only("all-unguarded", &changed), [(7, "all-unguarded")], "{call}"); + } + } + #[test] fn checks_in_failure_messages_do_not_end_only_weak() { let src = "#[test]\nfn t() {\n assert!(parse(input).is_ok(), \"{:?}\", probe().unwrap_err());\n}\n"; @@ -8966,6 +10630,15 @@ mod tests { assert_eq!(only("mirror", tails), [(3, "mirror")], "different arithmetic on each side still derives one from the other"); } + #[test] + fn echoes_recognize_non_ascii_identifiers() { + let src = "#[test]\nfn t() {\n let 数 = compute();\n assert_eq!(数, 42);\n}\n"; + assert_eq!(only("constant-echo", src), []); + assert_eq!(only("fixture-only", src), []); + let fixture = "#[test]\nfn t() {\n let 数 = 42;\n assert_eq!(数, 42);\n}\n"; + assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); + } + #[test] fn echoes_check_only_constants_or_the_fixture() { let constant = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert!(Kind::A != Kind::B);\n}\n"; @@ -9038,6 +10711,8 @@ mod tests { fn never_run_tests_are_compiled_out_on_every_ci_target() { let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", mac), [(3, "never-run")]); + let array_return = mac.replace("fn t() {", "fn t() -> Result<(), [u8; 2]> {"); + assert_eq!(only("never-run", &array_return), [(3, "never-run")], "a return type that holds `;`"); let module = "#[cfg(all(test, windows))]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; assert_eq!(hits_in("crates/x/src/lib.rs", module, &ctx()).into_iter().filter(|h| h.1 == "never-run").count(), 1); let file = "#![cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; @@ -9241,6 +10916,19 @@ mod tests { } } + #[test] + fn a_report_only_base_hit_does_not_hide_a_newly_failing_gate() { + let path = "crates/x/src/child.rs"; + let src = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n#[cfg(target_os = \"netbsd\")]\n#[test]\nfn u() {\n assert_eq!(f(), 1);\n}\n"; + let gated = |pred: &str| Ctx { module_cfgs: [(path.to_owned(), vec![pred.to_owned()])].into_iter().collect(), ..ctx() }; + let base = lint_file(path, src, &gated("target_os=\"macos\"")); + let now = lint_file(path, src, &gated("target_os=\"netbsd\"")); + let base_off: Vec<(&str, bool)> = base.iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test.as_str(), h.report_only)).collect(); + assert_eq!(base_off, [("t", true), ("u", false)]); + let off: Vec<&str> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.test.as_str()).collect(); + assert_eq!(off, ["t"], "the report-only hit becomes failing; the failing hit stays off"); + } + #[test] fn a_namesake_already_off_does_not_hide_a_newly_off_test() { let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; @@ -9422,8 +11110,7 @@ mod tests { #[test] fn path_override_discovery_accepts_attribute_whitespace_in_both_trees() { - 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-path-{}-{unique}", std::process::id())); + let root = TempRepo::new("path"); std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); git(&root, &["init", "--quiet"]).unwrap(); let files = [ @@ -9449,13 +11136,28 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in(child, test, &ctx), [(2, "never-run")], "the discovered gates apply: {revision:?}"); } - std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn verbatim_base_blobs_preserve_literal_line_numbers_after_blank_lines() { + let root = TempRepo::new("verbatim"); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let path = "crates/x/src/tests.rs"; + let src = "\n\n#[test]\nfn t() {\n let s = \"a\n// b\n\";\n}\n"; + std::fs::write(root.join(path), src).unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + let read = read_git_blob_verbatim(&root, &base, path, MAX_FILE).unwrap(); + assert_eq!(read, src); + assert_eq!(lines_in_literals(&read), [6, 7].into_iter().collect()); + assert_eq!(read_git_blob_verbatim(&root, &base, path, 8), None); + assert_eq!(read_git_blob_verbatim(&root, &base, "missing.rs", MAX_FILE), None); } #[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())); + let root = TempRepo::new("blob"); 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. @@ -9486,13 +11188,11 @@ mod tests { 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(); - let root = std::env::temp_dir().join(format!("test-lint-roots-{}-{unique}", std::process::id())); + let root = TempRepo::new("roots"); std::fs::create_dir_all(root.join("crates/x/tests/common")).unwrap(); git(&root, &["init", "--quiet"]).unwrap(); std::fs::write(root.join("crates/x/tests/smoke.rs"), "mod common;\n").unwrap(); @@ -9507,7 +11207,6 @@ mod tests { let routes = with_root_routes(Overrides::new(), &then); let parents: Vec<&str> = routes.get(shared).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); assert_eq!(parents, ["crates/x/tests/smoke.rs"], "the deleted root loaded it at the base"); - std::fs::remove_dir_all(root).unwrap(); } #[test] @@ -9528,12 +11227,20 @@ mod tests { let platform = "crates/x/src/platform.rs".to_owned(); let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides); assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere"); + let mut nested = files.clone(); + nested.insert( + "crates/x/src/lib.rs", + "#[cfg_attr(test, cfg_attr(unix, path = \"live.rs\"))]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n", + ); + let read = |p: &str| nested.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(nested.iter().map(|(p, s)| (*p, *s))); + let nested_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&live, test, &nested_ctx), [], "test builds on Linux load live.rs through a nested cfg_attr path"); } #[test] fn changed_lines_lists_both_paths_of_an_exact_rename() { - 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-rename-{}-{unique}", std::process::id())); + let root = TempRepo::new("rename"); std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap(); git(&root, &["init", "--quiet"]).unwrap(); let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n"; @@ -9546,7 +11253,19 @@ mod tests { let changed = changed_lines(&root, &base).unwrap(); assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted"); assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added"); - std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn changed_lines_reads_a_rust_file_git_takes_for_binary() { + let root = TempRepo::new("binary"); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + std::fs::write(root.join("crates/x/src/lib.rs"), "fn a() {}\nconst Z: &str = \"\0\";\nfn b() {}\n").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::write(root.join("crates/x/src/lib.rs"), "fn a() {}\nconst Z: &str = \"\0\";\nfn c() {}\n").unwrap(); + let changed = changed_lines(&root, &base).unwrap(); + assert_eq!(changed.get("crates/x/src/lib.rs"), Some(&Some([3].into_iter().collect())), "the changed third line"); } #[test] @@ -9747,7 +11466,7 @@ mod tests { #[test] fn deleted_files_are_kept_as_changed() { let diff = "diff --git a/crates/x/src/bin/tool.rs b/crates/x/src/bin/tool.rs\ndeleted file mode 100644\n--- a/crates/x/src/bin/tool.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-#[path = \"../shared.rs\"]\n-mod shared;\n"; - let got = parse_diff(diff); + let got = parse_diff(diff, &|_, _| false); assert_eq!(got.get("crates/x/src/bin/tool.rs"), Some(&None), "{got:?}"); let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); let seeds: Vec = got.keys().cloned().collect(); @@ -9849,6 +11568,36 @@ mod tests { assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); } + #[test] + fn exact_pixels_count_changes_through_the_second_operand() { + let src = "use egui::Rect;\n#[test]\nfn t() {\n assert_eq!(\n button_rect.width(),\n 120.0,\n \"width\"\n );\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::ExactPixel).collect(); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!((hit.line, hit.first, hit.last), (4, 4, 6)); + for line in [4, 5, 6] { + assert!(touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + for line in [3, 7, 8] { + assert!(!touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + let plain = + "use egui::Rect;\n#[test]\nfn t() {\n assert!(\n button_rect.width()\n == 120.0,\n \"width\"\n );\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", plain, &ctx()).into_iter().filter(|h| h.rule == Rule::ExactPixel).collect(); + assert_eq!(found.iter().map(|h| (h.line, h.last)).collect::>(), [(4, 6)], "a plain assertion's condition"); + } + + #[test] + fn mirrors_count_changes_through_the_second_operand() { + let src = "#[test]\nfn t() {\n assert_eq!(\n scale(p, 2.0),\n scale(p, 1.0) * 2.0,\n \"comparison\"\n );\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::Mirror).collect(); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!((hit.first, hit.last), (3, 5)); + assert!(touches(hit, Some(&[5].into_iter().collect())), "a change to the second operand"); + assert!(!touches(hit, Some(&[6].into_iter().collect())), "a change to the message"); + } + #[test] 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"; @@ -9916,6 +11665,8 @@ mod tests { assert_eq!(only("fixture-only", looped), []); let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n"; assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); + let braced = "#[test]\nfn t() {\n let n = 0;\n for n in { [compute()] } {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", braced), [], "a block expression as the iterator"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); let mutable = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; @@ -9954,6 +11705,12 @@ mod tests { assert_eq!(cfg_attr_paths(&mask(escaped), escaped.as_bytes(), 0, escaped.len()), [("unix".to_owned(), "a.rs".to_owned())]); let raw_escape = "#[cfg_attr(unix, path = r\"\\x61.rs\")]\nmod x;\n"; assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]); + let nested_path = "#[cfg_attr(test, cfg_attr(unix, path = \"a.rs\"))]\nmod x;\n"; + assert_eq!( + cfg_attr_paths(&mask(nested_path), nested_path.as_bytes(), 0, nested_path.len()), + [("all(test,unix)".to_owned(), "a.rs".to_owned())], + "a path inside a nested cfg_attr" + ); } #[test] @@ -11122,6 +12879,22 @@ mod tests { 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"); + let local = "#[test]\nfn t() {\n let mut active = true;\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(local), [], "an unchanged local selector"); + let changed = local.replace(" assert!(r.items(active)", " active = false;\n assert!(r.items(active)"); + assert_eq!(hits(&changed), [(7, "all-unguarded")], "a local selector changed after the snapshot"); + let accented = local.replace("active", "sélection"); + assert_eq!(hits(&accented), [], "an unchanged selector name with non-ASCII letters"); + let accented_changed = changed.replace("active", "sélection"); + assert_eq!(hits(&accented_changed), [(7, "all-unguarded")], "a selector name with non-ASCII letters changed after the snapshot"); + let passed = local.replace(" assert!(r.items(active)", " toggle(&mut active);\n assert!(r.items(active)"); + assert_eq!(hits(&passed), [(7, "all-unguarded")], "a local selector lent mutably after the snapshot"); + let field = local.replace(" assert!(r.items(active)", " settings.active = false;\n assert!(r.items(active)"); + assert_eq!(hits(&field), [], "a field of the same name"); + let range = local.replace("let mut active = true;", "let mut n = 3;").replace("items(active)", "items(0..n)"); + assert_eq!(hits(&range), [], "an unchanged range selector"); + let changed_range = range.replace(" assert!(r.items", " n = 0;\n assert!(r.items"); + assert_eq!(hits(&changed_range), [(7, "all-unguarded")], "a range selector changed after the snapshot"); } #[test] @@ -11282,4 +13055,528 @@ mod tests { let ctx = Ctx { module_cfgs: [(child.to_owned(), vec!["any()".to_owned()])].into_iter().collect(), ..ctx() }; assert_eq!(hits_in(child, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx), [(2, "never-run")]); } + + #[test] + fn deleting_only_comments_or_blank_lines_changes_no_test() { + let path = "crates/x/src/tests.rs"; + let found = lint_file(path, "#[test]\nfn t() {}\n#[test]\nfn other() {}\n", &ctx()); + assert_eq!(found[0].test, "t"); + let diff = |deleted: &str| format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -3,2 +2,0 @@\n{deleted}"); + let changed = |deleted: &str| parse_diff(&diff(deleted), &|_, _| false); + for deleted in ["-// a note after the test\n", "-\n- // and a blank line\n"] { + assert!(!touches(&found[0], changed(deleted)[path].as_ref()), "{deleted:?}"); + } + for deleted in ["- assert_eq!(f(), 1);\n", "-// test-lint: allow no-assertion checked by hand\n", "-/* x\n", "-// note\n-x();\n"] { + assert!(touches(&found[0], changed(deleted)[path].as_ref()), "{deleted:?}"); + } + let base = "#[test]\nfn t() {\n let s = \"a\n// b\n\";\n let r = r#\"\n\n\"#;\n}\n// after\n"; + assert_eq!(lines_in_literals(base), [4, 5, 7, 8].into_iter().collect()); + let in_base = |p: &str, line: usize| p == path && lines_in_literals(base).contains(&line); + let in_string = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -4 +3,0 @@\n-// b\n"); + assert_eq!(parse_diff(&in_string, &in_base)[path], Some([3, 4].into_iter().collect()), "a line of a string literal"); + let after = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -10 +9,0 @@\n-// after\n"); + assert_eq!(parse_diff(&after, &in_base)[path], Some(BTreeSet::new()), "a comment outside every literal"); + } + + #[test] + fn deleting_a_skip_comment_inside_a_test_exposes_the_return() { + let path = "crates/x/src/tests.rs"; + let base = "#[test]\nfn t() {\n if unavailable() {\n // The fixture is optional.\n return;\n }\n assert_eq!(f(), 1);\n}\n// after\n"; + let src = base.replace(" // The fixture is optional.\n", ""); + assert_eq!(only("early-return", base), []); + assert_eq!(only("early-return", &src), [(4, "early-return")]); + let lines = lines_affecting_tests(base); + let can_change_test = |p: &str, line: usize| p == path && lines.contains(&line); + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -4 +3,0 @@\n- // The fixture is optional.\n"); + let changed = parse_diff(&diff, &can_change_test); + assert_eq!(changed[path], Some([3, 4].into_iter().collect())); + let found = lint_file(path, &src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::EarlyReturn).unwrap(); + assert!(touches(hit, changed[path].as_ref())); + let blank = base.replace(" // The fixture is optional.", ""); + let blank_lines = lines_affecting_tests(&blank); + let diff = diff.replace("- // The fixture is optional.", "-"); + assert_eq!(parse_diff(&diff, &|_, line| blank_lines.contains(&line))[path], Some([3, 4].into_iter().collect())); + let after = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -9 +8,0 @@\n-// after\n"); + assert_eq!(parse_diff(&after, &can_change_test)[path], Some(BTreeSet::new())); + } + + #[test] + fn deleting_a_skip_comment_exposes_a_return_after_blank_lines() { + let path = "crates/x/src/tests.rs"; + let base = "#[test]\nfn t() {\n if unavailable() {\n // The fixture is optional.\n\n\n return;\n }\n assert_eq!(f(), 1);\n}\n"; + let src = base.replace(" // The fixture is optional.\n", ""); + assert_eq!(only("early-return", &src), [(6, "early-return")]); + let lines = lines_affecting_tests(base); + let can_change_test = |p: &str, line: usize| p == path && lines.contains(&line); + let code_after = |p: &str, line: usize| if p == path { next_code_line(&src, line) } else { line }; + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -4 +3,0 @@\n- // The fixture is optional.\n"); + let changed = parse_diff_in(&diff, &can_change_test, &code_after); + let found = lint_file(path, &src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::EarlyReturn).unwrap(); + assert!(touches(hit, changed[path].as_ref()), "{changed:?}"); + let spaced = base.replace("\n\n return;", "\n /* spacer */\n\n return;"); + let src = spaced.replace(" // The fixture is optional.\n", ""); + let lines = lines_affecting_tests(&spaced); + let can_change_test = |p: &str, line: usize| p == path && lines.contains(&line); + let code_after = |p: &str, line: usize| if p == path { next_code_line(&src, line) } else { line }; + let changed = parse_diff_in(&diff, &can_change_test, &code_after); + let found = lint_file(path, &src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::EarlyReturn).unwrap(); + assert!(touches(hit, changed[path].as_ref()), "a block comment before the return: {changed:?}"); + let note = "#[test]\nfn t() {}\n// a note\n\n\nfn helper() {}\n"; + let after = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -3 +2,0 @@\n-// a note\n"); + let kept = note.replace("// a note\n", ""); + let code_after = |_: &str, line: usize| next_code_line(&kept, line); + assert_eq!(parse_diff_in(&after, &|_, _| false, &code_after)[path], Some(BTreeSet::new()), "a comment outside every test"); + let replaced = base.replace(" // The fixture is optional.", ""); + let replacement = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -4 +4 @@\n- // The fixture is optional.\n+\n"); + let code_after = |p: &str, line: usize| if p == path { next_code_line(&replaced, line) } else { line }; + let changed = parse_diff_in(&replacement, &can_change_test, &code_after); + let found = lint_file(path, &replaced, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::EarlyReturn).unwrap(); + assert!(touches(hit, changed[path].as_ref()), "a skip comment replaced by a blank line: {changed:?}"); + let import = "fn helper() {}\nuse x::y;\n\n\n#[test]\nfn t() {}\n"; + let kept = import.replace("use x::y;\n", ""); + let removed = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -2 +1,0 @@\n-use x::y;\n"); + let code_after = |_: &str, line: usize| next_code_line(&kept, line); + let changed = parse_diff_in(&removed, &|_, _| true, &code_after); + let found = lint_file(path, &kept, &ctx()); + assert_eq!(found[0].rule, Rule::NoAssertion); + assert!(!touches(&found[0], changed[path].as_ref()), "an import deleted before blank lines: {changed:?}"); + } + + #[test] + fn a_grouped_run_block_writes_to_the_environment_file() { + let block = "run: |\n {\n echo \"MY_SAMPLES=fixtures\"\n } >> \"$GITHUB_ENV\"\n"; + assert_eq!(upper_words(block).collect::>(), ["MY_SAMPLES"]); + let printed = "run: |\n echo \"MY_SAMPLES=fixtures\"\n echo OTHER=1 >> \"$GITHUB_ENV\"\n"; + assert!(!upper_words(printed).any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn a_folded_run_block_is_one_command_line() { + let folded = "- run: >-\n echo\n MY_SAMPLES=fixtures\n"; + assert!(!upper_words(folded).any(|n| n == "MY_SAMPLES"), "an echo argument after folding"); + let separate = "- run: >-\n echo hi\n\n MY_SAMPLES=fixtures cargo test\n"; + assert_eq!(upper_words(separate).collect::>(), ["MY_SAMPLES"], "a blank line keeps the break"); + let deeper = "- run: >\n echo hi\n MY_SAMPLES=fixtures cargo test\n"; + assert_eq!(upper_words(deeper).collect::>(), ["MY_SAMPLES"], "a deeper line keeps its break"); + assert_eq!(fold_block(&[" a", " b", "", " c", " d", " e"], None), "a b\nc\n d\ne\n"); + let explicit = "- run: >2-\n echo hi\n MY_SAMPLES=fixtures cargo test\n"; + assert_eq!(upper_words(explicit).collect::>(), ["MY_SAMPLES"], "an indentation indicator sets the indentation"); + } + + #[test] + fn an_assignment_follows_a_separator_without_a_space() { + assert_eq!(upper_words("run: true&&MY_SAMPLES=fixtures cargo test\n").collect::>(), ["MY_SAMPLES"]); + assert!(!upper_words("run: echo \"a&&MY_SAMPLES=fixtures\"\n").any(|n| n == "MY_SAMPLES"), "inside quotes"); + } + + #[test] + fn only_a_stdout_redirection_writes_to_the_environment_file() { + assert!(!writes_env_file("echo \"MY_SAMPLES=fixtures\" 2>> \"$GITHUB_ENV\"")); + assert!(writes_env_file("echo \"MY_SAMPLES=fixtures\" 1>> \"$GITHUB_ENV\"")); + assert!(writes_env_file("echo \"MY_SAMPLES=fixtures\" &>> \"$GITHUB_ENV\"")); + let group = "run: { echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\"; echo done > setup.log; }\n"; + assert_eq!(upper_words(group).collect::>(), ["MY_SAMPLES"], "a redirection of the next command"); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" && echo done > setup.log")); + assert!(!writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" > a.log; echo done"), "the same command"); + } + + #[test] + fn a_literal_run_block_ends_at_the_next_step_key() { + let step = "- run: |\n cargo test\n env:\n MY_SAMPLES: fixtures\n"; + assert_eq!(upper_words(step).collect::>(), ["MY_SAMPLES"]); + let nested = "- run: |\n cargo test\n MY_SAMPLES: fixtures\n"; + assert!(!upper_words(nested).any(|n| n == "MY_SAMPLES"), "a line of the script"); + } + + #[test] + fn a_later_stdout_redirection_replaces_the_environment_file() { + assert!(writes_env_file("echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\"")); + assert!(!writes_env_file("echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\" > setup.log")); + assert!(!writes_env_file("echo MY_SAMPLES=fixtures >> ${GITHUB_ENV} >&2")); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" 2> err.log")); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" 2>&1")); + assert!(writes_env_file("echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\" | cat > out.log")); + assert!(writes_env_file("{ echo MY_SAMPLES=fixtures >> \"$GITHUB_ENV\"; } > out.log")); + let block = "run: echo \"MY_SAMPLES=fixtures\" >> \"$GITHUB_ENV\" > setup.log\n"; + assert!(!upper_words(block).any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn an_unquoted_search_pattern_sets_no_variable() { + assert!(!upper_words("run: grep MY_SAMPLES=fixtures settings.txt").any(|n| n == "MY_SAMPLES")); + assert!(upper_words("run: A=1 MY_SAMPLES=fixtures cargo test").any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn the_print_exemption_reads_the_command_name() { + assert!(upper_words("run: export NOTE='echo' \"MY_SAMPLES=fixtures\"; cargo test").any(|n| n == "MY_SAMPLES")); + assert!(upper_words("run: export NOTE=echo MY_SAMPLES=fixtures; cargo test").any(|n| n == "MY_SAMPLES")); + } + + #[test] + fn printing_the_environment_file_path_writes_nothing_to_it() { + for line in + [" echo \"MY_SAMPLES=fixtures\" \"$GITHUB_ENV\"", " echo MY_SAMPLES=fixtures $GITHUB_ENV", " echo \"MY_SAMPLES=x\" ${GITHUB_ENV}"] + { + assert!(!upper_words(line).any(|n| n == "MY_SAMPLES"), "{line}"); + } + } + + #[test] + fn a_discarded_tuple_runs_its_elements() { + let src = "#[test]\nfn t() {\n let _ = (|| (), { assert_eq!(f(), 1); });\n}\n"; + assert_eq!(only("no-assertion", src), []); + } + + #[test] + fn a_change_between_a_size_read_and_all_in_one_assertion_voids_the_guard() { + let mutated = + "#[test]\nfn t() {\n let mut xs = f();\n assert!({ let ok = xs.iter().all(|x| valid(x)); xs.push(1); ok } && xs.len() == 1);\n}\n"; + assert_eq!(only("all-unguarded", mutated), [(4, "all-unguarded")]); + } + + #[test] + fn a_length_guard_covers_only_its_own_collection() { + let other = "#[test]\nfn t() {\n let xs = f();\n let ys = g();\n assert_eq!(xs.len(), 2);\n assert!(ys.windows(2).all(|w| w[0] < w[1]));\n}\n"; + assert_eq!(only("all-unguarded", other), [(6, "all-unguarded")]); + assert_eq!(only("all-unguarded", &other.replace("ys.windows", "xs.windows")), []); + } + + #[test] + fn a_size_check_joined_by_or_guards_no_all() { + let joined = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.len() >= 2 || xs.windows(2).all(|w| w[0] < w[1]));\n}\n"; + assert_eq!(only("all-unguarded", joined), [(4, "all-unguarded")]); + assert_eq!(only("all-unguarded", &joined.replace("||", "&&")), []); + } + + #[test] + fn an_index_guards_only_the_collection_it_reads() { + let other = "#[test]\nfn t() {\n let expected = f();\n let actual = g();\n let _ = expected[1];\n assert!(actual.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(only("all-unguarded", other), [(6, "all-unguarded")]); + assert_eq!(only("all-unguarded", &other.replace("expected[1]", "actual[1]")), []); + } + + #[test] + fn an_index_does_not_guard_full_chunks_of_its_item() { + let chunks = "#[test]\nfn t() {\n assert!(rows()[1].as_chunks::<2>().0.iter().all(|[a, b]| a == b));\n}\n"; + assert_eq!(only("all-unguarded", chunks), [(3, "all-unguarded")]); + } + + #[test] + fn a_selector_name_may_have_no_ascii_letters() { + let local = "#[test]\nfn t() {\n let mut active = true;\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"; + let changed = local.replace(" assert!(r.items(active)", " active = false;\n assert!(r.items(active)"); + assert_eq!(hits(&changed.replace("active", "选")), [(7, "all-unguarded")], "a selector changed after the snapshot"); + assert_eq!(hits(&local.replace("active", "选")), [], "an unchanged selector"); + } + + #[test] + fn an_indexed_local_may_have_no_ascii_letters() { + let indexed = "#[test]\nfn t() {\n let 数 = [Input { n: 5 }];\n assert_eq!(数[0].len(), 5);\n}\n"; + assert_eq!(only("fixture-only", indexed), []); + let whole = indexed.replace("数[0].len()", "数.len()"); + assert_eq!(only("fixture-only", &whole), only("fixture-only", &whole.replace('数', "xs"))); + } + + #[test] + fn assignment_text_inside_a_quoted_value_sets_no_variable() { + for line in [" message=\"MY_SAMPLES=fixtures\"", " echo \"A=1 MY_SAMPLES=2\" >> \"$GITHUB_ENV\""] { + assert!(!upper_words(line).any(|n| n == "MY_SAMPLES"), "{line}"); + } + assert_eq!(upper_words(" message=\"x\" MY_SAMPLES=y cargo test").collect::>(), ["MY_SAMPLES"]); + } + + #[test] + fn a_path_call_of_the_same_name_does_not_call_the_closure() { + 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 = || app.run(c); other::run(); assert!(menu(c).is_some());"), [(2, "census")]); + assert_eq!(census("let run = || app.run(c); run(); assert!(menu(c).is_some());"), []); + } + + #[test] + fn pattern_bindings_shadow_calls_of_a_stored_closure() { + let source = |body: &str| format!("let run = || app.run(c); {body}"); + for body in ["for run in [|| ()] { run(); }", "consume(|run| { run(); });", "match value { Some(run) => { run(); } _ => {} }"] { + let code = mask(&source(body)); + assert_eq!(closure_calls(&code, "run", 0, 23, code.len(), false), Vec::::new(), "{body}"); + } + for body in ["for run in [|| ()] { run(); } run();", "for other in [|| ()] { run(); }"] { + let code = mask(&source(body)); + let calls = closure_calls(&code, "run", 0, 23, code.len(), false); + assert_eq!(calls.len(), 1, "{body}"); + assert_eq!(&code[calls[0]..calls[0] + 5], b"run()", "{body}"); + } + let src = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = || app.run(c);\n for run in [|| ()] { run(); }\n assert!(menu(c).is_some());\n }\n}\n"; + assert_eq!(only("census", src), [(2, "census")]); + } + + #[test] + fn struct_field_labels_preserve_outer_closure_calls_and_initializers() { + for body in [ + "for Row { run: other } in rows { run(); }", + "consume(|Row { run: other }| { run(); });", + "match value { Row { run: other } => { run(); } }", + ] { + let code = mask(&format!("let run = || app.run(c); {body}")); + let calls = closure_calls(&code, "run", 0, 23, code.len(), false); + assert_eq!(calls.len(), 1, "{body}"); + assert_eq!(&code[calls[0]..calls[0] + 5], b"run()", "{body}"); + assert!(reaching_init(&code, "run", calls[0]).flatten().is_some(), "{body}"); + } + for body in [ + "for Row { run } in rows { run(); }", + "for Row { x: run } in rows { run(); }", + "consume(|Row { run }| { run(); });", + "consume(|Row { x: run }| { run(); });", + "match value { Row { run } => { run(); } }", + "match value { Row { x: run } => { run(); } }", + ] { + let code = mask(&format!("let run = || app.run(c); {body}")); + assert_eq!(closure_calls(&code, "run", 0, 23, code.len(), false), Vec::::new(), "{body}"); + let at = code.windows(5).rposition(|word| word == b"run()").unwrap(); + assert_eq!(reaching_init(&code, "run", at), Some(None), "{body}"); + } + } + + #[test] + fn a_conditional_equality_does_not_guard_all() { + let src = "#[test]\nfn t() {\n assert_eq!(xs, [1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let conditional = src.replace(" assert_eq!(xs, [1]);", " if check_first { assert_eq!(xs, [1]); }"); + assert_eq!(only("all-unguarded", &conditional), [(4, "all-unguarded")]); + let same_branch = + "#[test]\nfn t() {\n if check_first {\n assert_eq!(xs, [1]);\n assert!(xs.iter().all(|x| *x > 0));\n }\n}\n"; + assert_eq!(hits(same_branch), [], "the equality runs whenever the assertion in its branch does"); + } + + #[test] + fn a_count_stops_guarding_when_a_mutable_reference_is_passed_on() { + let src = + "#[test]\nfn t() {\n let xs = &mut f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let taken = src.replace(" assert!(xs", " std::mem::take(xs);\n assert!(xs"); + assert_eq!(hits(&taken), [(7, "all-unguarded")]); + let printed = src.replace(" assert!(xs", " println!(\"{:?}\", xs);\n assert!(xs"); + assert_eq!(hits(&printed), [], "a macro only reads it"); + } + + #[test] + fn a_grouped_read_preserves_a_mutable_references_count_guard() { + let src = + "#[test]\nfn t() {\n let xs = &mut f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + for read in ["(xs).len();", "(a, xs);", "println!(\"{:?}\", xs);"] { + let grouped = src.replace(" assert!(xs", &format!(" {read}\n assert!(xs")); + assert_eq!(only("all-unguarded", &grouped), [], "{read}"); + } + for call in + ["std::mem::take(xs);", "consume(a, xs);", "consumer.consume(xs);", "(consumer)(xs);", "std::mem::take((xs));", "consume(a, ((xs)));"] + { + let passed = src.replace(" assert!(xs", &format!(" {call}\n assert!(xs")); + assert_eq!(only("all-unguarded", &passed), [(7, "all-unguarded")], "{call}"); + } + } + + #[test] + fn assigning_a_grouped_collection_invalidates_its_count_guard() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(only("all-unguarded", src), []); + for change in ["(xs) = vec![];", "((xs)) = vec![];", "(xs, _) = (vec![], 0);", "[_, (xs, _)] = [x, (vec![], 0)];"] { + let changed = src.replace(" assert!(xs", &format!(" {change}\n assert!(xs")); + assert_eq!(only("all-unguarded", &changed), [(7, "all-unguarded")], "{change}"); + } + for read in ["(xs).len();", "let pair = (&xs, 0);", "assert_eq!((&xs, 0), (&ys, 0));"] { + let read = src.replace(" assert!(xs", &format!(" {read}\n assert!(xs")); + assert_eq!(only("all-unguarded", &read), [], "{read}"); + } + } + + #[test] + fn calls_in_a_nested_fn_body_do_not_poll() { + for item in [ + "fn unused() {\n probe();\n }", + "fn unused(f: F) -> u8 {\n probe()\n }", + "fn unused() -> [u8; 1] {\n [probe()]\n }", + "fn vérifier() {\n probe();\n }", + ] { + let src = format!( + "fn wait() {{\n let t0 = Instant::now();\n while t0.elapsed() < D {{\n {item}\n thread::sleep(D);\n }}\n}}\n" + ); + assert_eq!(hits(&src).iter().filter(|h| h.1 == "sleep").count(), 1, "{src}"); + } + let direct = + "fn wait() {\n let t0 = Instant::now();\n while t0.elapsed() < D {\n probe();\n thread::sleep(D);\n }\n}\n"; + assert_eq!(hits(direct).iter().filter(|h| h.1 == "sleep").count(), 0); + let called = direct.replace("probe();", "fn vérifier() { probe(); }\n vérifier();"); + assert_eq!(hits(&called).iter().filter(|h| h.1 == "sleep").count(), 0, "a call to a non-ASCII nested fn polls"); + } + + #[test] + fn conversions_of_types_the_test_names_are_not_fixture_reads() { + for src in [ + "#[test]\nfn t() {\n let result = Input { n: 5 }.to_string();\n assert_eq!(result, \"5\");\n}\n", + "#[test]\nfn t() {\n let input = Input { n: 5 };\n let shown = input.to_string();\n assert_eq!(shown, \"5\");\n}\n", + "#[test]\nfn t() {\n let shown = Kind::A.to_string();\n assert_eq!(shown, \"a\");\n}\n", + "#[test]\nfn t() {\n let c: u8 = 5.into();\n assert_eq!(c, 5);\n}\n", + "#[test]\nfn t() {\n let pair = Pair(5, Kind::A);\n assert_eq!(pair.1.to_string(), \"a\");\n}\n", + "#[test]\nfn t() {\n let pair = (5, Kind::A);\n assert_eq!(pair.1.to_string(), \"a\");\n}\n", + "#[test]\nfn t() {\n let xs = [Input { n: 5 }];\n assert_eq!(xs[0].len(), 5);\n}\n", + "#[test]\nfn t() {\n let xs = [[Input { n: 5 }]];\n assert_eq!(xs[0][0].len(), 5);\n}\n", + ] { + assert_eq!(only("fixture-only", src), [], "{src}"); + } + for src in [ + "#[test]\nfn t() {\n let name = \"x\".to_string();\n assert_eq!(name, \"x\");\n}\n", + "#[test]\nfn t() {\n let xs = vec![Input { n: 5 }];\n assert_eq!(xs.len(), 1);\n}\n", + "#[test]\nfn t() {\n let xs = [[1, 2]];\n assert_eq!(xs[0].len(), 2);\n}\n", + "#[test]\nfn t() {\n let input = Input { n: 5 };\n assert_eq!(input.n.to_string(), \"5\");\n}\n", + "#[test]\nfn t() {\n let pair = Pair(5, Kind::A);\n assert_eq!(pair.0.to_string(), \"5\");\n}\n", + "#[test]\nfn t() {\n let pair = (5, Kind::A);\n assert_eq!(pair.0.to_string(), \"5\");\n}\n", + ] { + assert_eq!(only("fixture-only", src), [(2, "fixture-only")], "{src}"); + } + } + + #[test] + fn operators_on_user_values_are_not_fixture_reads() { + for expr in [ + "Amount(2) + Amount(3)", + "2 * Amount(3)", + "Amount(3) % 2", + "Amount(2) << 1", + "1 >> Amount(2)", + "Amount(2) & Amount(3)", + "Amount(2) | Amount(3)", + "Amount(2) ^ Amount(3)", + "-Amount(2)", + "!Amount(2)", + "Some(Amount(2) + Amount(3))", + "2 + vec![Amount(3)]", + ] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, Amount(5));\n}}\n"); + assert_eq!(only("constant-echo", &src), [], "{expr}"); + } + for expr in ["a + a", "a - a", "a / 2", "-a", "!a", "row.0 + a", "(a) + a", "&a + &a"] { + let src = format!("#[test]\nfn t() {{\n let a = Amount(2);\n let row = Row(a);\n assert_eq!({expr}, Amount(4));\n}}\n"); + assert_eq!(only("fixture-only", &src), [], "{expr}"); + } + let computed = "#[test]\nfn t() {\n let a = Amount(2);\n let actual = a + a;\n assert_eq!(actual, Amount(4));\n}\n"; + assert_eq!(only("fixture-only", computed), []); + let indexed = "#[test]\nfn t() {\n let xs = [Amount(2), Amount(3)];\n assert_eq!(xs[0] + xs[1], Amount(5));\n}\n"; + assert_eq!(only("fixture-only", indexed), [], "an indexed element of a user-value array"); + let primitive = indexed.replace("Amount(2), Amount(3)", "2, 3"); + assert_eq!(only("fixture-only", &primitive), [(2, "fixture-only")], "an indexed element of a primitive array"); + } + + #[test] + fn literal_operators_and_user_value_borrows_remain_inert() { + for expr in ["2 + 3", "MAX * 2", "!2", "-2", "Amount(2) == Amount(3)", "&Amount(2)", "Amount(2)..Amount(3)", "(Amount(2), 2 + 3)"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, EXPECTED);\n}}\n"); + assert_eq!(only("constant-echo", &src), [(2, "constant-echo")], "{expr}"); + } + for expr in ["&a", "a == a", "a != a", "a < a", "a >= a", "a..a", "row.0 + 2", "xs.len() + 2"] { + let src = format!( + "#[test]\nfn t() {{\n let a = Amount(2);\n let row = Row(2);\n let xs = vec![a];\n assert_eq!({expr}, EXPECTED);\n}}\n" + ); + assert_eq!(only("fixture-only", &src), [(2, "fixture-only")], "{expr}"); + } + } + + #[test] + fn container_conversions_can_test_element_implementations() { + for (init, field) in + [("vec![Input { n: 5 }]", "[0].n"), ("vec![Some(Input { n: 5 })]", "[0].as_ref().unwrap().n"), ("vec![vec![Input { n: 5 }]]", "[0][0].n")] + { + let src = format!("#[test]\nfn t() {{\n let xs = {init};\n let cloned = xs.clone();\n assert_eq!(cloned{field}, 6);\n}}\n"); + assert_eq!(only("fixture-only", &src), [], "{init}"); + } + let alias = "#[test]\nfn t() {\n let input = Input { n: 5 };\n let xs = vec![input; 2];\n let alias = xs;\n assert_eq!(alias.to_vec()[0].n, 6);\n}\n"; + assert_eq!(only("fixture-only", alias), []); + let view = alias.replace("alias.to_vec()", "alias.as_slice().to_vec()"); + assert_eq!(only("fixture-only", &view), []); + let non_ascii = "#[test]\nfn t() {\n let 数 = vec![Input { n: 5 }];\n assert_eq!(数.clone()[0].n, 6);\n}\n"; + assert_eq!(only("fixture-only", non_ascii), [], "a non-ASCII container local"); + let primitive = "#[test]\nfn t() {\n let 数 = vec![5];\n assert_eq!(数.clone()[0], 6);\n}\n"; + assert_eq!(only("fixture-only", primitive), [(2, "fixture-only")], "a non-ASCII local of primitive values"); + let element = "#[test]\nfn t() {\n let 数 = [Input { n: 5 }];\n assert_eq!(数[0].clone().n, 6);\n}\n"; + assert_eq!(only("fixture-only", element), [], "a clone of an element of a non-ASCII local"); + let primitive_element = "#[test]\nfn t() {\n let 数 = [5];\n assert_eq!(数[0].clone(), 6);\n}\n"; + assert_eq!(only("fixture-only", primitive_element), [(2, "fixture-only")], "a clone of a primitive element"); + for expr in ["vec![Input { n: 5 }].len()", "vec![5].clone().len()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, 1);\n}}\n"); + assert_eq!(only("constant-echo", &src), [(2, "constant-echo")], "{expr}"); + } + } + + #[test] + fn conversions_of_container_method_results_do_not_inspect_elements() { + let local = |name: &str, _: usize| match name { + "xs" => Some((false, "vec![Input{n:5}]".to_owned(), 0)), + "row" => Some((true, "Row{items:vec![Input{n:5}]}".to_owned(), 0)), + _ => None, + }; + for receiver in [ + "vec![Input{n:5}].len()", + "[Input{n:5}].is_empty()", + "(Input{n:5},).type_id()", + "Some(Input{n:5}).is_some()", + "xs.len()", + "row.items.is_empty()", + "vec![Input{n:5}].as_slice().len()", + ] { + assert!(!holds_user_value(receiver, 0, &local), "{receiver}"); + } + for expr in ["vec![Input { n: 5 }].len().to_string()", "vec![Input { n: 5 }].is_empty().to_string()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({expr}, \"1\");\n}}\n"); + assert_eq!(only("constant-echo", &src), [(2, "constant-echo")], "{expr}"); + } + for receiver in [ + "vec![Input{n:5}]", + "[Input{n:5}]", + "(Input{n:5},)", + "Some(Input{n:5})", + "xs", + "row.items", + "vec![Input{n:5}].as_slice().as_ref().clone().to_vec().to_owned()", + ] { + assert!(holds_user_value(receiver, 0, &local), "{receiver}"); + } + } + + #[test] + fn qualified_user_types_and_their_fields_keep_their_value_kind() { + for init in ["Input { n: 5 }", "model::Input { n: 5 }", "outer::model::Input { n: 5 }", "model::Input(5)"] { + let src = format!("#[test]\nfn t() {{\n let input = {init};\n assert_eq!(input.to_string(), \"5\");\n}}\n"); + assert_eq!(only("fixture-only", &src), [], "{init}"); + } + for (init, field) in [("model::Input { n: 5 }", "n"), ("model::Input(5)", "0")] { + let src = format!("#[test]\nfn t() {{\n let input = {init};\n assert_eq!(input.{field}.to_string(), \"5\");\n}}\n"); + assert_eq!(only("fixture-only", &src), [(2, "fixture-only")], "{init}"); + let user = src.replacen('5', "model::Kind::A", 1); + assert_eq!(only("fixture-only", &user), [], "{init}"); + } + } + + #[test] + fn field_initializers_resolve_names_before_their_binding() { + let src = "#[test]\nfn t() {\n let input = Input { n: 5 };\n let input = Input { n: input.n };\n assert_eq!(input.n.to_string(), \"5\");\n}\n"; + assert_eq!(only("fixture-only", src), [(2, "fixture-only")]); + let user_field = src.replace("n: 5", "n: Kind::A"); + assert_eq!(only("fixture-only", &user_field), [], "the earlier field holds a user type"); + let aliased = src.replace( + " assert_eq!(input.n", + " let alias = input;\n let alias = alias;\n let input = Input { n: Kind::A };\n assert_eq!(alias.n", + ); + assert_eq!(only("fixture-only", &aliased), [(2, "fixture-only")], "the alias resolves before the later binding"); + let user_alias = user_field.replace( + " assert_eq!(input.n", + " let alias = input;\n let alias = alias;\n let input = Input { n: 5 };\n assert_eq!(alias.n", + ); + assert_eq!(only("fixture-only", &user_alias), [], "the aliased field holds a user type"); + } }