From 3e6a21b93b3c5f71e8f72fec44fd82e4cb3965cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:01:48 -0800 Subject: [PATCH 1/8] xtask: test-lint leaves out census loops that run each entry through a computation A loop over a whole table whose body passes the entry to a call together with other state (a command run, a file written, a render, a parse of other input) checks behavior for each entry, so the census rule no longer reports it. A lookup, a call on the entry alone, literal arguments and calls in a failure message still count as a census. The census count from test-lint --all drops from 42 to 37: the cutting add-on dialog table, the quick pen toolbar clicks, the white spot ink overprint output, the plug-in proposal loads and the unit parse property test are no longer reported. --- xtask/src/test_lint.rs | 144 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 142 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..b1fc00dc12 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -45,7 +45,9 @@ //! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of //! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`, //! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or -//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. A loop that +//! passes the entry to a call together with other state (a command run, a file written, a +//! render) is a table of behavior cases and is not reported; //! * `mirror`: `assert_eq!(f(a), f(b) …)`, where the expected side derives its value from a //! second call of the same function (same path) with arithmetic, so a fault in `f` moves both //! sides; builders and conversions (`new`, `from`, `to_string` …) are left out; @@ -1447,7 +1449,10 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let Some(close) = matching(m, open) else { continue }; let pattern = String::from_utf8_lossy(&m[at + 3..kw]); let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&'); - if whole_table(&norm(&m[kw + 2..open])) && weak_in(open, close, var) { + if whole_table(&norm(&m[kw + 2..open])) + && weak_in(open, close, var) + && !feeds_entry(&unmessaged, &pattern, open + 1 - v.t.open, close - v.t.open) + { return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; } } @@ -1460,6 +1465,113 @@ fn census(v: &View, helpers: &HashSet) -> Vec { vec![] } +/// Calls that read or look up a value rather than compute one, so passing the entry to one of them +/// together with other state does not make the loop a behavior table. +const LOOKUPS: &[&str] = &[ + "contains", + "contains_key", + "starts_with", + "ends_with", + "get", + "get_mut", + "iter", + "into_iter", + "any", + "find", + "position", + "binary_search", + "eq", + "ne", + "find_map", +]; + +/// The lowercase names a `for` or `let` pattern binds. +fn pattern_names(pattern: &str) -> impl Iterator + '_ { + pattern + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) + .map(str::to_owned) +} + +/// Whether the body `b[from..to]` of a loop whose pattern is `pattern` feeds the entry into a +/// computation with other inputs: a call (not one of [`LOOKUPS`], nor a macro) whose receiver and +/// arguments include a value read from the entry and another value that is not a literal, such as +/// `app.run("…", json!({"id": id}))`, `export(&doc, &Options { level, .. })` or `check(SCHEMA, ¶ms)` +/// with `params` bound from the entry inside the loop. Such a loop runs, renders or writes something +/// for each entry, so it is a table of behavior cases. A call that takes the entry alone (`menu(c)`, +/// `Kind::from_id(k.id())`) is still a lookup. +fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { + let mut derived: Vec = pattern_names(pattern).collect(); + let reads = |s: &[u8], names: &[String]| { + let s = String::from_utf8_lossy(s); + names.iter().any(|n| reads_ident(&s, n)) + }; + // Names bound inside the loop from the entry count as the entry. + for at in words(b, b"let", from, to) { + let Some(eq) = + (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + else { + continue; + }; + let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); + if reads(&b[eq + 1..end], &derived) { + let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + derived.extend(names); + } + } + let literal = |s: &[u8]| { + let s = norm(s); + let s = s.trim_start_matches(['&', '*']); + // String, byte and raw literals keep their prefix after masking (`r"…"`, `b'…'`, `br#"…"#`). + let s = match s.find(['"', '\'']) { + Some(q) if q <= 3 && s[..q].bytes().all(|c| matches!(c, b'b' | b'c' | b'r' | b'#')) => &s[q..], + _ => s, + }; + // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. + s.is_empty() + || s.starts_with(['"', '\'', '-', '|']) + || s.starts_with("move|") + || s.starts_with(|c: char| c.is_ascii_digit()) + || matches!(s, "true" | "false" | "None") + }; + (from..to).filter(|&i| b[i] == b'(' && i > from && is_ident(b[i - 1])).any(|open| { + let mut start = open; + while start > from && is_ident(b[start - 1]) { + start -= 1; + } + let name = String::from_utf8_lossy(&b[start..open]); + if LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() { + return false; + } + let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; + let args = split_args(b, open + 1, close); + let mut inputs = args.clone(); + if start > from && b[start - 1] == b'.' { + // The receiver: the chain of names, calls and indexing before the dot. + let mut r = start - 1; + while r > from { + match b[r - 1] { + c if is_ident(c) || c == b'.' => r -= 1, + // A chain rustfmt splits over lines continues with a `.` after the line break. + c if c.is_ascii_whitespace() && b[r..start].iter().find(|c| !c.is_ascii_whitespace()) == Some(&b'.') => r -= 1, + b')' | b']' => match (from..r - 1).rev().find(|&o| matching(b, o) == Some(r - 1)) { + Some(o) => r = o, + None => break, + }, + _ => break, + } + } + inputs.push((r, start - 1)); + } + let fed = inputs.iter().any(|&(f, t)| reads(&b[f..t], &derived)); + // A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only + // another argument (`u.parse(&text)`) makes it a computation. + let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs }; + let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(&b[f..t], &derived)); + fed && other + }) +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -3783,6 +3895,34 @@ mod tests { assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip"); } + #[test] + fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let run = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app.session.execute(CMD, &json!({\"way\": k})).is_ok());\n }\n}\n"; + assert_eq!(census(run), [], "a command run for each entry"); + let split = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app\n .run(k)\n .is_ok());\n }\n}\n"; + assert_eq!(census(split), [], "a chain split over lines keeps its receiver"); + let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n"; + assert_eq!(census(rendered), [], "a file written for each entry"); + let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(check_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; + assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema"); + let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n"; + assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census"); + let alone = "#[test]\nfn t() {\n for c in COMMANDS {\n let m = menu(c);\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(alone), [(2, "census")], "a call on the entry alone is a lookup"); + let constant = + "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c, 2, \"x\", r\"y\", b'z', br#\"w\"#).is_some());\n }\n}\n"; + assert_eq!(census(constant), [(2, "census")], "literal arguments are not other inputs"); + let message = "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some(), \"{}\", app.describe(c));\n }\n}\n"; + assert_eq!(census(message), [(2, "census")], "a call in a failure message runs only after a failure"); + let closure = "#[test]\nfn t() {\n let tree = tree();\n for p in PLACES {\n let m = tree.iter().find(|t| t == p).map(|(_, items)| items.len());\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(closure), [(2, "census")], "a closure passed along a lookup is not another input"); + let registry = "#[test]\nfn t() {\n let registry = registry();\n for k in Kind::ALL {\n assert_eq!(registry.lookup(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip"); + let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n"; + assert_eq!(census(parsed), [], "parsing other input with each entry computes a result"); + } + #[test] fn census_loops_over_whole_tables_are_reported() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); From e0b51eb78235703e1c2940f2d2e5cdf6a88b516c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:33:34 -0800 Subject: [PATCH 2/8] xtask: census exemption does not count a call that an || can skip A call to the right of an || at its own nesting level may never run, so `menu(c).is_some() || app.run(c).is_ok()` is still reported as a census. The right side of &&, an || inside an earlier group or a sibling element, and the pipes of a zero-argument, move or async closure do not skip the call. --- xtask/src/test_lint.rs | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index b1fc00dc12..a9fd4b1be4 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1543,6 +1543,43 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { if LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() { return false; } + // A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`); the + // right side of `&&` has to run for an assertion to pass. + let stmt = (from..start).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(from, |i| i + 1); + // Only an `||` at the call's own nesting level or an enclosing one counts, not one inside + // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; + // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. + // Sibling elements and assignments also end the expression that can skip the call. + let mut depth = 0usize; + let mut after_or = false; + for i in (stmt + 1..start).rev() { + match b[i] { + b')' | b']' => depth += 1, + b'(' | b'[' => depth = depth.saturating_sub(1), + _ => {} + } + if depth == 0 + && (b[i] == b',' || (b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))) + { + break; + } + if depth == 0 && b[i] == b'|' && b[i - 1] == b'|' { + let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); + let prefix = &b[stmt..end]; + let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); + let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); + if !moved + && !asynchronous + && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + { + after_or = true; + break; + } + } + } + if after_or { + return false; + } let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; let args = split_args(b, open + 1, close); let mut inputs = args.clone(); @@ -3921,6 +3958,20 @@ mod tests { assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip"); let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n"; assert_eq!(census(parsed), [], "parsing other input with each entry computes a result"); + let skipped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() || app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(skipped), [(2, "census")], "a call after || may never run"); + let joined = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(joined), [], "a call after && runs whenever the assertion passes"); + let grouped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!((menu(c).is_some() || other(c).is_some()) && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(grouped), [], "an || inside an earlier group does not skip the call"); + let deferred = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(deferred), [], "a zero-argument closure feeds the entry into a computation"); + let moved = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = move || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(moved), [], "a move closure feeds the entry into a computation"); + let deferred_async = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = async || app.run(c);\n assert!(block_on(run()).is_ok());\n }\n}\n"; + assert_eq!(census(deferred_async), [], "an async closure feeds the entry into a computation"); + let sibling = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let result = (flag || other, app.run(c));\n assert!(result.1.is_ok());\n }\n}\n"; + assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } #[test] From 03bddf6a2afa7824ac73409a319996858689ba7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:01:53 -0800 Subject: [PATCH 3/8] xtask: fix test-lint false hits and misses in census, gates and source reads census: - an asserting helper after || no longer keeps a loop out of the census - a let that rebinds the entry name to another value shadows it until its block ends; a rebinding from the entry ends the shadow - a call in a let-bound closure that the loop never calls does not count - calls with a turbofish (app.run::(c)) are read as computations - -offset is another input; only a minus before a number is a literal - a block on the right of || can be skipped; a finished if before the call does not skip it - a round trip can read the entry as the receiver (k.parse()) - a field label in a pattern does not bind the label's name never-run and module routes: - base hits match the same test by name and line - a parent too large to read at the base is reported as an incomplete comparison instead of an absent declaration; its size is checked before git show reads it, and each base file is read once - a removed route counts as a change to its child, including routes in deleted or renamed-away parents - cfg string values are decoded (\x, \u{}, escapes); an escape that is not decoded leaves the predicate unknown - every line of a multiline cfg attribute counts as a change - a tests folder inside src is a module, not a Cargo target root - #[path] accepts raw strings, and its targets are found from the declaring file, inside inline modules too, and followed transitively - every route at every depth of inline modules is kept, each with its own parents' gates; a crate root also loaded by #[path] still runs as its own target; a build script is not a test route - mod name; matches only the file it loads by default reads-source: - only path-taking calls count (fs::, an alias of std::fs, or an imported read_to_string), not Read::read_to_string or reader methods - whitespace inside a path literal is kept - a literal substituted into format! is not taken as the file name mirror and exact-pixel hits run through the compared operands, so a change to the expected side on a later line counts. A rect width in arithmetic is not reported as a hard-coded width. --- xtask/src/test_lint.rs | 1194 +++++++++++++++++++++++++++++++++++----- 1 file changed, 1046 insertions(+), 148 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index cc24470436..1a7731430a 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -81,7 +81,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. -use std::cell::OnceCell; +use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -272,20 +272,143 @@ fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap, base: Option<&Gates>, changed: &BTreeMap>>) -> bool { + gate_changed(current, changed) || base.is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent))) +} + +/// Whether the `never-run` hit `hit` is new against the hits of the same source with the base's +/// module gates: no base hit is for the same test at the same line. +fn newly_off(base: &[Hit], hit: &Hit) -> bool { + !base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +} + +/// A file as `git show` gave it at the base. +#[derive(Debug, PartialEq)] +enum BaseSource { + /// The path does not exist at the base. + Absent, + /// The file exists but is larger than [`MAX_FILE`], so it is not analyzed. + TooLarge, + Text(String), +} + +fn base_source(shown: Option) -> BaseSource { + match shown { + None => BaseSource::Absent, + Some(s) if s.len() as u64 > MAX_FILE => BaseSource::TooLarge, + Some(s) => BaseSource::Text(s), + } +} + +/// For each file a `#[path = "…"]` declaration loads, the files that declare it. +fn path_edges(files: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + // Cargo compiles a build script but never runs it as a test target. + for parent in files.iter().filter(|p| p.ends_with(".rs") && !p.ends_with("/build.rs") && p.as_str() != "build.rs") { + let Some(src) = read(parent) else { continue }; + if !src.contains("path") { + continue; + } + let m = mask(&src); + for at in words(&m, b"mod", 0, m.len()) { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + continue; + } + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + let target = path_target(parent, &inline_mods(&m, at), &rel); + let parents = out.entry(target).or_default(); + if !parents.contains(parent) { + parents.push(parent.clone()); + } + } + } + } + out +} + +/// The union of two [`path_edges`] maps. +fn merge_edges(a: &HashMap>, b: HashMap>) -> HashMap> { + let mut out = a.clone(); + for (target, parents) in b { + let entry = out.entry(target).or_default(); + for p in parents { + if !entry.contains(&p) { + entry.push(p); + } + } + } + out +} + +/// `edges` without the declarations made in `files`. +fn edges_without(edges: &HashMap>, files: &[String]) -> HashMap> { + edges + .iter() + .map(|(t, ps)| (t.clone(), ps.iter().filter(|p| !files.contains(p)).cloned().collect::>())) + .filter(|(_, ps)| !ps.is_empty()) + .collect() +} + +/// The files loaded through `#[path]` declarations, followed transitively from the changed files +/// `present` and the module directories `module_dirs`, and the module directories of those files. +fn path_loaded(edges: &HashMap>, present: &[String], module_dirs: &[String]) -> (BTreeSet, Vec) { + let (mut files, mut dirs): (BTreeSet, Vec) = (present.iter().cloned().collect(), module_dirs.to_vec()); + loop { + let more: Vec = edges + .iter() + .filter(|(t, ps)| !files.contains(*t) && ps.iter().any(|p| files.contains(p) || dirs.iter().any(|d| p.starts_with(d.as_str())))) + .map(|(t, _)| t.clone()) + .collect(); + if more.is_empty() { + break; + } + for t in more { + dirs.push(module_directory(&t)); + files.insert(t); + } + } + (files.into_iter().filter(|f| !present.contains(f)).collect(), dirs.split_off(module_dirs.len())) +} + /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. fn read_small(root: &Path, path: &str) -> Option { let full = root.join(path); (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } +/// The directory holding the modules a file declares, with a trailing `/`: the file's own directory +/// for `mod.rs`, `lib.rs` and `main.rs`, else the file's path without `.rs`. +fn module_directory(path: &str) -> String { + let (dir, file) = path.rsplit_once('/').unwrap_or(("", path)); + if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", path.trim_end_matches(".rs")) } +} + +/// The paths in `git … -z` output, which separates them with NUL and leaves them unquoted. +fn nul_paths(out: &str) -> Vec { + out.split('\0').filter(|p| !p.is_empty()).map(str::to_owned).collect() +} + +/// The `git` arguments that list files deleted since `base`. Without rename detection, the old path +/// of a renamed file is listed too. +fn deleted_diff_args(base: &str) -> [&str; 6] { + ["diff", "--name-only", "-z", "--diff-filter=D", "--no-renames", base] +} + pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let opts = Options::parse(args)?; let repo = crate::repo_files(root)?; let ci_env = ci_env(root, &repo)?; let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); + // `#[path]` declarations load files outside the declaring module's directory. + let edges = path_edges(&files, &|p| read_small(root, p)); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + let module_cfgs = module_gates_with(&files, &|p| read_small(root, p), &edges).into_iter().map(|(p, g)| (p, g.preds)).collect(); let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); @@ -293,48 +416,111 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } let base = resolve_base(root, opts.base)?; let changed = changed_lines(root, &base)?; - let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + let mut changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + // A deleted parent can have given the only CI route to a module; its routes exist only at the base. + let deleted: Vec = nul_paths(&git(root, &deleted_diff_args(&base))?).into_iter().filter(|p| is_scanned(p)).collect(); + for d in &deleted { + changed.entry(d.clone()).or_insert(None); + } let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn // their tests off without a change to them. - let module_dirs: Vec = present - .iter() - .map(|p| { - let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); - if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } - }) - .collect(); - let below: Vec = - files.iter().filter(|p| !changed.contains_key(*p) && module_dirs.iter().any(|d| p.starts_with(d.as_str()))).cloned().collect(); + let module_dirs: Vec = present.iter().chain(&deleted).map(|p| module_directory(p)).collect(); + // Files read at the base, for the gates the parent declarations gave there. A parent too large + // to read at the base leaves the comparison incomplete, which is reported instead of counted. + let too_large = RefCell::new(BTreeSet::new()); + let shown: RefCell>> = RefCell::new(HashMap::new()); + let read_base_once = |p: &str| { + let spec = format!("{base}:{p}"); + let size = git(root, &["cat-file", "-s", &spec]).ok().and_then(|s| s.trim().parse::().ok()); + let s = match size { + None => None, + Some(n) if n > MAX_FILE => { + too_large.borrow_mut().insert(p.to_owned()); + None + } + Some(_) => match base_source(git(root, &["show", &spec]).ok()) { + BaseSource::Text(s) => Some(s), + BaseSource::TooLarge => { + too_large.borrow_mut().insert(p.to_owned()); + None + } + BaseSource::Absent => None, + }, + }; + shown.borrow_mut().insert(p.to_owned(), s.clone()); + s + }; + let read_base = |p: &str| { + let cached = shown.borrow().get(p).cloned(); + cached.unwrap_or_else(|| read_base_once(p)) + }; + // A `#[path]` route removed from a changed file exists only at the base. + let changed_files: Vec = changed.keys().cloned().collect(); + let base_edges = merge_edges(&edges_without(&edges, &changed_files), path_edges(&changed_files, &read_base)); + let all_edges = merge_edges(&edges, base_edges.clone()); + // A deleted parent's base routes lead to files as well. + let seeds: Vec = present.iter().chain(&deleted).cloned().collect(); + let by_path = path_loaded(&all_edges, &seeds, &module_dirs); + let loaded = |p: &String| module_dirs.iter().chain(&by_path.1).any(|d| p.starts_with(d.as_str())) || by_path.0.contains(p); + let below: Vec = files.iter().filter(|p| !changed.contains_key(*p) && loaded(p)).cloned().collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); - let gates = module_gates(&gated, &|p| read_small(root, p)); + let gates = module_gates_with(&gated, &|p| read_small(root, p), &edges); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; - // The gates the parent declarations gave at the base: a parent edit counts against a child's - // test only when the test ran in CI before it. - let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + // A parent edit counts against a child's test only when the test ran in CI at the base. + let base_gates = module_gates_with(&gated, &read_base, &base_edges); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); + let route_changed = |path: &str| routes_changed(gates.get(path), base_gates.get(path), &changed); + // A base file too large to read may have declared the module even when no route names it: any + // such file in a directory above the module leaves the comparison incomplete. + let incomplete = |path: &str| { + let large = too_large.borrow(); + gates.get(path).into_iter().chain(base_gates.get(path)).flat_map(|g| &g.sources).any(|(p, _)| large.contains(p)) + || large.iter().any(|p| path.starts_with(&format!("{}/", p.rsplit_once('/').map_or("", |(d, _)| d)))) + }; let (mut counted, mut older) = (vec![], 0usize); + let child_hits = |path: &str, src: &str, hits: Vec, counted: &mut Vec| -> usize { + let base_hits = lint_file(path, src, &base_ctx); + let (mut new, mut skipped) = (vec![], 0usize); + for hit in hits { + if !newly_off(&base_hits, &hit) { + skipped += 1; + } else if incomplete(path) { + eprintln!("test-lint: {path}:{}: a parent module is larger than {MAX_FILE} bytes at {base}; not compared", hit.line); + skipped += 1; + } else { + new.push(hit); + } + } + counted.extend(new); + skipped + }; for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = route_changed(&path); + let mut by_parent = vec![]; for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) - || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) - { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { counted.push(hit); + } else if hit.rule == Rule::NeverRun && parent_changed { + by_parent.push(hit); } else { older += 1; } } + if !by_parent.is_empty() { + older += child_hits(&path, &src, by_parent, &mut counted); + } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + for path in below.iter().filter(|p| route_changed(p)) { let Some(src) = read_small(root, path) else { continue }; - counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); + let off: Vec = lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + if !off.is_empty() { + child_hits(path, &src, off, &mut counted); + } } finish(&counted, older, present.len(), &base) } @@ -991,6 +1177,11 @@ const COMMON: &[&str] = &[ /// The names called in `m[from..to]`: functions (`name(`, also through a path), methods /// (`.name(`), including calls with turbofish arguments, and macros (`name!`). fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + calls_at(m, from, to).into_iter().map(|(name, method, _)| (name, method)).collect() +} + +/// [`calls`] with the offset where each name starts. +fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(String, bool, usize)> { let m = &m[..to]; let mut out = vec![]; let mut i = from; @@ -1007,7 +1198,7 @@ fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { let name = String::from_utf8_lossy(&m[i..end]).into_owned(); let method = i > 0 && m[i - 1] == b'.'; if !KEYWORDS.contains(&name.as_str()) { - out.push((if bang { format!("{name}!") } else { name }, method)); + out.push((if bang { format!("{name}!") } else { name }, method, i)); } } i = end; @@ -1434,7 +1625,12 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let weak_in = |from: usize, to: usize, var: &str| { let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); let body = &unmessaged[from - v.t.open..to - v.t.open]; - helpers_in(from, to).is_empty() + // A helper counts only where it runs whenever the assertions pass, not after an `||`. + let (f, t) = (from + 1 - v.t.open, to - v.t.open); + let helper_runs = calls_at(&unmessaged, f, t).into_iter().any(|(n, method, at)| { + !(n.ends_with('!') && is_assert_macro(&n)) && is_helper_call(&n, method, helpers) && runs_with_assertion(&unmessaged, f, t, at) + }); + !helper_runs && !rejects(body) && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) @@ -1485,10 +1681,21 @@ const LOOKUPS: &[&str] = &[ "find_map", ]; -/// The lowercase names a `for` or `let` pattern binds. +/// The lowercase names a `for` or `let` pattern binds. A field label (`Row { c: other }`) binds +/// the name after it. fn pattern_names(pattern: &str) -> impl Iterator + '_ { + let b = pattern.as_bytes(); pattern - .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .match_indices(|c: char| c.is_ascii_alphanumeric() || c == '_') + .filter(move |&(at, _)| at == 0 || !is_ident(b[at - 1])) + .map(move |(at, _)| (at, at + b[at..].iter().take_while(|&&c| is_ident(c)).count())) + .filter(move |&(at, end)| { + // Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`). + let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count(); + let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count(); + !in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':') + }) + .map(move |(at, end)| &pattern[at..end]) .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) .map(str::to_owned) } @@ -1502,9 +1709,11 @@ fn pattern_names(pattern: &str) -> impl Iterator + '_ { /// `Kind::from_id(k.id())`) is still a lookup. fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let mut derived: Vec = pattern_names(pattern).collect(); - let reads = |s: &[u8], names: &[String]| { - let s = String::from_utf8_lossy(s); - names.iter().any(|n| reads_ident(&s, n)) + // Where a `let` that does not read the entry rebinds one of its names: from the end of that + // statement to the end of its block, the name holds another value. + let mut shadows: Vec<(String, usize, usize)> = vec![]; + let live = |f: usize, t: usize, names: &[String], shadows: &[(String, usize, usize)]| { + names.iter().any(|n| words(b, n.as_bytes(), f, t).into_iter().any(|at| !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z))) }; // Names bound inside the loop from the entry count as the entry. for at in words(b, b"let", from, to) { @@ -1514,11 +1723,25 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { continue; }; let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); - if reads(&b[eq + 1..end], &derived) { - let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + if live(eq + 1, end, &derived, &shadows) { + // Rebinding from the entry suspends earlier shadows until this block ends. + let until = block_close(b, at).min(to); + let mut resumed = vec![]; + for s in shadows.iter_mut().filter(|s| names.contains(&s.0) && s.1 <= at && at < s.2) { + if until < s.2 { + resumed.push((s.0.clone(), until, s.2)); + } + s.2 = end; + } + shadows.extend(resumed); derived.extend(names); + } else { + let until = block_close(b, at).min(to); + shadows.extend(names.into_iter().filter(|n| derived.contains(n)).map(|n| (n, end, until))); } } + let reads = |f: usize, t: usize| live(f, t, &derived, &shadows); let literal = |s: &[u8]| { let s = norm(s); let s = s.trim_start_matches(['&', '*']); @@ -1528,56 +1751,21 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { _ => s, }; // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. + // A minus sign makes a literal only in front of a number (`-2`, not `-offset`). + let s = s.strip_prefix('-').unwrap_or(s); s.is_empty() - || s.starts_with(['"', '\'', '-', '|']) + || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || s.starts_with(|c: char| c.is_ascii_digit()) || matches!(s, "true" | "false" | "None") }; - (from..to).filter(|&i| b[i] == b'(' && i > from && is_ident(b[i - 1])).any(|open| { - let mut start = open; + (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { + let mut start = name_end; while start > from && is_ident(b[start - 1]) { start -= 1; } - let name = String::from_utf8_lossy(&b[start..open]); - if LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() { - return false; - } - // A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`); the - // right side of `&&` has to run for an assertion to pass. - let stmt = (from..start).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(from, |i| i + 1); - // Only an `||` at the call's own nesting level or an enclosing one counts, not one inside - // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; - // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. - // Sibling elements and assignments also end the expression that can skip the call. - let mut depth = 0usize; - let mut after_or = false; - for i in (stmt + 1..start).rev() { - match b[i] { - b')' | b']' => depth += 1, - b'(' | b'[' => depth = depth.saturating_sub(1), - _ => {} - } - if depth == 0 - && (b[i] == b',' || (b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))) - { - break; - } - if depth == 0 && b[i] == b'|' && b[i - 1] == b'|' { - let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); - let prefix = &b[stmt..end]; - let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); - let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); - if !moved - && !asynchronous - && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) - { - after_or = true; - break; - } - } - } - if after_or { + let name = String::from_utf8_lossy(&b[start..name_end]); + if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) { return false; } let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; @@ -1600,15 +1788,122 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { } inputs.push((r, start - 1)); } - let fed = inputs.iter().any(|&(f, t)| reads(&b[f..t], &derived)); + let fed = inputs.iter().any(|&(f, t)| reads(f, t)); // A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only // another argument (`u.parse(&text)`) makes it a computation. let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs }; - let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(&b[f..t], &derived)); + let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(f, t)); fed && other }) } +/// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the +/// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. +fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { + let before = open; + if before > from && is_ident(b[before - 1]) { + return Some(before); + } + if before == from || b[before - 1] != b'>' { + return None; + } + let mut depth = 0usize; + for i in (from..before).rev() { + match b[i] { + b'>' if i == 0 || b[i - 1] != b'-' => depth += 1, + b'<' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + let head = b[from..i].trim_ascii_end(); + let end = head.strip_suffix(b"::")?.trim_ascii_end().len(); + return (end > 0 && is_ident(b[from + end - 1])).then_some(from + end); + } + } + b';' | b'{' | b'}' => return None, + _ => {} + } + } + None +} + +/// Whether a call starting at `start` in the loop body `b[from..to]` runs whenever the loop's +/// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`, +/// also with a block as the right operand); the right side of `&&` has to run. A call inside a +/// zero-argument closure bound with `let` runs only when the loop calls that closure. +fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { + // The statement starts after a `;` or an unmatched brace, except for the `{` of a block that is + // the operand of `||` or `&&`. + let mut stmt = from; + let mut braces = 0usize; + for i in (from..start).rev() { + match b[i] { + // A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`) + // unless an operator joins the call's expression to it. + b'}' if braces == 0 && { + let after = b[i + 1..start].trim_ascii_start(); + !(after.starts_with(b"||") || after.starts_with(b"&&") || after.starts_with(b".") || after.starts_with(b"?")) + } => + { + stmt = i + 1; + break; + } + b'}' => braces += 1, + b'{' if braces > 0 => braces -= 1, + b'{' => { + let before = b[from..i].trim_ascii_end(); + if !(before.ends_with(b"||") || before.ends_with(b"&&")) { + stmt = i + 1; + break; + } + } + b';' if braces == 0 => { + stmt = i + 1; + break; + } + _ => {} + } + } + // Only an `||` at the call's own nesting level or an enclosing one counts, not one inside + // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; + // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. + // Sibling elements and assignments also end the expression that can skip the call. + let mut depth = 0usize; + let mut closure = None; + for i in (stmt + 1..start).rev() { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => depth = depth.saturating_sub(1), + _ => {} + } + if depth == 0 + && (b[i] == b',' || (b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))) + { + break; + } + if depth == 0 && b[i] == b'|' && b[i - 1] == b'|' { + let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); + let prefix = &b[stmt..end]; + let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); + let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); + if !moved + && !asynchronous + && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + { + return false; + } + closure = Some(stmt + prefix.len()); + } + } + // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. + let Some(end) = closure else { return true }; + let head = String::from_utf8_lossy(&b[stmt..end]); + let head = head.trim(); + let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true }; + let Some(name) = pattern_names(binding).last() else { return true }; + words(b, name.as_bytes(), end, to).into_iter().any(|at| b.get(skip_ws(b, at + name.len())) == Some(&b'(')) +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -1849,7 +2144,11 @@ fn round_trip_call(op: &str, var: &str) -> bool { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',']) - && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) + && matching(op.as_bytes(), open).is_some_and(|close| { + // The entry is read in the arguments (`Kind::from_id(k.id())`) or is the receiver (`k.parse()`). + let receiver = op[..at].strip_suffix('.').is_some_and(|r| reads_ident(r, var)); + only_unwraps(&op[close + 1..]) && (receiver || reads_ident(&op[open + 1..close], var)) + }) }) }) } @@ -3145,11 +3444,56 @@ fn reads_source_hits(file: &File) -> Vec { (&b"ends_with"[..], "keeps files ending in .rs"), (&b"read_to_string"[..], "reads a .rs file as text"), ]; + // A bare `read_to_string(…)` reads a path only where a `use` brings in `fs::read_to_string`. + let uses: Vec = + words(m, b"use", 0, m.len()).into_iter().map(|u| String::from_utf8_lossy(&m[u..statement_end(m, u)]).into_owned()).collect(); + let fs_imported = uses.iter().map(|u| norm(u.as_bytes())).any(|item| { + item.contains("fs::read_to_string") + || item.contains("fs::*") + || item.split_once("fs::{").is_some_and(|(_, list)| !words(list.as_bytes(), b"read_to_string", 0, list.len()).is_empty()) + }); + // Names `std::fs` is imported under (`use std::fs as filesystem;`). + let fs_aliases: Vec = uses + .iter() + .flat_map(|u| { + let b = u.as_bytes(); + words(b, b"as", 0, b.len()).into_iter().filter_map(move |at| { + let path = norm(&b[..at]); + let self_fs = path.ends_with("self") + && b[..at] + .iter() + .enumerate() + .rev() + .find(|&(i, &c)| c == b'{' && matching(b, i).is_some_and(|end| end > at)) + .is_some_and(|(open, _)| norm(&b[..open]).ends_with("fs::")); + let alias = b[at + 2..].trim_ascii_start(); + (path.ends_with("fs") || self_fs) + .then(|| String::from_utf8_lossy(&alias[..alias.iter().take_while(|&&c| is_ident(c)).count()]).into_owned()) + }) + }) + .filter(|a| !a.is_empty()) + .collect(); for (word, note) in words_and_notes { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { + if word == b"read_to_string" { + // `fs::read_to_string(path)` takes a path; `Read::read_to_string(&mut r, &mut buf)` and + // `reader.read_to_string(&mut buf)` take an output buffer. + let before = m[..at].trim_ascii_end(); + let path_call = match before.strip_suffix(b"::").map(<[u8]>::trim_ascii_end) { + Some(p) => ["fs"] + .into_iter() + .chain(fs_aliases.iter().map(String::as_str)) + .any(|q| p.ends_with(q.as_bytes()) && !p[..p.len() - q.len()].last().copied().is_some_and(is_ident)), + None => fs_imported && !before.ends_with(b".") && !before.ends_with(b"fn"), + }; + if !path_call { + continue; + } + } let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let arg = norm(&code[open + 1..close]); + // Whitespace inside a literal is part of the path (`"sample.r s"`). + let arg = norm_outside_literals(&code[open + 1..close], &m[open + 1..close]); // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); @@ -3157,7 +3501,9 @@ fn reads_source_hits(file: &File) -> Vec { b"ends_with" => literal == "\".rs\"", // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + // A literal inside `format!` is a value substituted into another path, so the file + // read is not known. + b"read_to_string" => path_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3171,6 +3517,47 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// `code` without the whitespace outside string literals; `m` is its masked text, where a literal's +/// quotes stay and its contents are blanked. +fn norm_outside_literals(code: &[u8], m: &[u8]) -> String { + let mut inside = false; + let kept: Vec = code + .iter() + .zip(m) + .filter_map(|(&c, &mc)| { + if mc == b'"' { + inside = !inside; + } + (inside || !c.is_ascii_whitespace()).then_some(c) + }) + .collect(); + String::from_utf8_lossy(&kept).into_owned() +} + +/// The literal that names the end of the path a (whitespace-free) argument reads: its last string +/// literal ([`last_literal`]), or, when that literal is a value substituted into a `format!`, the +/// format string itself (`format!("{}.json", "snapshot.rs")` reads a `.json` file). +fn path_literal(arg: &str) -> Option<&str> { + let close_q = arg.rfind('"')?; + let open_q = arg[..close_q].rfind('"')?; + for (f, _) in arg.match_indices("format!(") { + let open = f + "format!".len(); + let Some(close) = matching(arg.as_bytes(), open) else { continue }; + if !(open < open_q && close_q < close) { + continue; + } + let &(a, b) = split_args(arg.as_bytes(), open + 1, close).first()?; + if a <= open_q && close_q < b { + return Some(&arg[open_q..=close_q]); + } + // A format string that ends with a placeholder ends with the substituted value + // (`format!("{}/{}", root, "src/lib.rs")`). + let format_string = last_literal(&arg[a..b])?; + return Some(if format_string.ends_with("}\"") { &arg[open_q..=close_q] } else { format_string }); + } + Some(&arg[open_q..=close_q]) +} + /// The last string literal in a (whitespace-free) expression, quotes included. fn last_literal(arg: &str) -> Option<&str> { let close = arg.rfind('"')?; @@ -3246,8 +3633,12 @@ fn mirrors(v: &View) -> Vec { // compared as they are check that two inputs agree, which is a real check. let derived = ["+", "-", "*", "/"].iter().any(|op| !top_level_at(r, op).is_empty()); let last = name.rsplit("::").next().unwrap_or(name); - (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)) - .then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)).then(|| { + let mut h = v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name)); + // The span runs through the second operand, not the failure message. + h.last = h.last.max(v.file.lines.of(a.args[1].1)); + h + }) }) .collect() } @@ -3332,6 +3723,8 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), @@ -3339,6 +3732,59 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option` of the innermost `match` arm around `before` whose pattern binds `name`. +fn match_arm_binding(body: &[u8], name: &str, before: usize) -> Option { + let mut best = None; + for at in words(body, b"match", 0, before) { + let Some((open, close)) = let_body(body, at + 5) else { continue }; + if !(open < before && before < close) { + continue; + } + let (mut depth, mut start, mut i) = (0usize, open + 1, open + 1); + while i < close { + match body[i] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + b',' if depth == 0 => start = i + 1, + b'=' if depth == 0 && body.get(i + 1) == Some(&b'>') => { + let arrow = i; + let value = skip_ws(body, arrow + 2); + let end = if body.get(value) == Some(&b'{') { + matching(body, value).unwrap_or(close) + } else { + let mut d = 0usize; + (value..close) + .find(|&j| { + match body[j] { + b'(' | b'[' | b'{' => d += 1, + b')' | b']' | b'}' => d = d.saturating_sub(1), + _ => {} + } + d == 0 && body[j] == b',' + }) + .unwrap_or(close) + }; + let pattern = &body[start..arrow]; + let guard = words(pattern, b"if", 0, pattern.len()).first().copied().unwrap_or(pattern.len()); + // A field label (`Row { n: actual }`) is not a binding of `n`. + let binds = words(&pattern[..guard], name.as_bytes(), 0, guard).into_iter().any(|w| { + let next = skip_ws(pattern, w + name.len()); + pattern.get(next) != Some(&b':') || pattern.get(next + 1) == Some(&b':') + }); + if arrow < before && before <= end && binds { + best = best.max(Some(arrow)); + } + start = end + 1; + i = end; + } + _ => {} + } + i += 1; + } + } + best +} + /// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { let mut found = None; @@ -3494,20 +3940,62 @@ fn cfg_value(p: &str, t: &Target) -> Option { if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { return cfg_value(arg, t).map(|v| !v); } - // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. - let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + let (key, value) = p.split_once('=').map_or((p, None), |(k, v)| (k, Some(cfg_string(v)))); + // A value that cannot be decoded matches no known target, so the predicate is unknown. + let value = || value.clone().flatten(); match key { "test" => Some(true), "unix" => Some(t.family == "unix"), "windows" => Some(t.family == "windows"), - "target_os" => Some(t.os == value), - "target_family" => Some(t.family == value), - "target_arch" => Some(t.arch == value), - "target_pointer_width" => Some(value == "64"), + "target_os" => value().map(|v| t.os == v), + "target_family" => value().map(|v| t.family == v), + "target_arch" => value().map(|v| t.arch == v), + "target_pointer_width" => value().map(|v| v == "64"), _ => None, } } +/// The value of an ordinary or raw string literal in a (whitespace-free) `cfg` predicate: +/// `"linux"`, `"lin\x75x"`, `r"linux"`, `r#"linux"#`. Raw contents are kept as written; `None` for +/// an escape this does not decode. +fn cfg_string(lit: &str) -> Option { + if let Some(raw) = lit.strip_prefix('r') { + let hashes = raw.len() - raw.trim_start_matches('#').len(); + let inner = raw.get(hashes..raw.len().checked_sub(hashes)?)?; + return inner.strip_prefix('"')?.strip_suffix('"').map(str::to_owned); + } + let inner = lit.strip_prefix('"')?.strip_suffix('"')?; + let mut out = String::new(); + let mut chars = inner.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next()? { + 'n' => out.push('\n'), + 't' => out.push('\t'), + 'r' => out.push('\r'), + '0' => out.push('\0'), + c @ ('\\' | '"' | '\'') => out.push(c), + 'x' => { + let hex: String = chars.by_ref().take(2).collect(); + let v = u8::from_str_radix(&hex, 16).ok().filter(|v| *v <= 0x7f)?; + out.push(char::from(v)); + } + 'u' => { + let rest = chars.as_str().strip_prefix('{')?; + let close = rest.find('}')?; + let v = u32::from_str_radix(&rest[..close].replace('_', ""), 16).ok().and_then(char::from_u32)?; + out.push(v); + chars = rest[close + 1..].chars(); + } + _ => return None, + } + } + Some(out) +} + /// A `cfg` attribute found by [`cfg_attrs`]. struct CfgAttr { pred: String, @@ -3582,8 +4070,8 @@ fn pred_text(src: &[u8]) -> String { } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the -/// offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { @@ -3599,7 +4087,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - out.push((pred, at)); + out.push((pred, at, end)); } } out @@ -3610,7 +4098,9 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { /// `examples`). fn module_parent(path: &str) -> Option<(&str, Vec)> { let (dir, file) = path.rsplit_once('/')?; - let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); + // Cargo's target directories sit next to `src`; a `tests` folder inside `src` is a module. + let in_src = format!("/{dir}/").contains("/src/"); + let root_dir = !in_src && ["/tests", "/benches", "/examples"].iter().any(|d| format!("/{dir}").ends_with(d)); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } @@ -3628,6 +4118,16 @@ struct Loaded<'a> { chain: &'a [String], } +/// The file a `#[path = "rel"]` declaration in `parent` loads: relative to `parent`'s directory, or, +/// inside the inline modules `chain`, to their directory under `parent`'s module. +fn path_target(parent: &str, chain: &[String], rel: &str) -> String { + let mut base = if chain.is_empty() { parent.rsplit_once('/').map_or("", |(d, _)| d).to_owned() } else { module_directory(parent) }; + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + /// The `cfg` predicates under which `src`, the file `parent`, loads `want`: those on the /// `mod ;` declarations that load it (by name, or through a `#[path]` override) and on the /// items, inline modules and file around them, with the 1-based lines of those declarations and @@ -3647,19 +4147,21 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => { - // A `#[path]` outside inline modules is relative to the file's directory; inside them, - // to the inline modules' directory under the file's module. + Some(rel) => path_target(parent, want.chain, &rel) == want.path, + None => { + // The default file of `mod name;`: `name.rs` or `name/mod.rs` under the declaring + // module's directory and the inline modules around the declaration. let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { + if !mod_rs { base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); } for seg in want.chain { base = join_path(&base, seg); } - join_path(&base, &rel) == want.path + let name = String::from_utf8_lossy(&m[start..end]); + &m[start..end] == want.name.as_bytes() + && [format!("{name}.rs"), format!("{name}/mod.rs")].iter().any(|f| join_path(&base, f) == want.path) } - None => &m[start..end] == want.name.as_bytes(), }; if !loads { continue; @@ -3667,11 +4169,12 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); at_lines.push(lines.of(at)); - at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); + // Every line of a multiline attribute counts. + at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); - for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + for (p, a, end) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); - at_lines.push(lines.of(a)); + at_lines.extend(lines.of(a)..=lines.of(end)); } each.push(preds); } @@ -3688,11 +4191,16 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { words(m, b"path", from, to).into_iter().find_map(|at| { let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); let eq = skip_ws(m, at + 4); - let q = skip_ws(m, eq + 1); + // An ordinary or raw string: `"x.rs"`, `r"x.rs"`, `r#"x.rs"#`. + let open = skip_ws(m, eq + 1); + let raw = m.get(open) == Some(&b'r'); + let hashes = if raw { m[open + 1..].iter().take_while(|&&c| c == b'#').count() } else { 0 }; + let q = if raw { open + 1 + hashes } else { open }; if !attr || m.get(eq) != Some(&b'=') || m.get(q) != Some(&b'"') { return None; } - let close = find(m, b"\"", q + 1)?; + let closing: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let close = find(m, &closing, q + 1)?; Some(String::from_utf8_lossy(&src[q + 1..close]).into_owned()) }) } @@ -3731,6 +4239,7 @@ fn inline_mods(m: &[u8], at: usize) -> Vec { /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. +#[cfg(test)] fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() } @@ -3744,49 +4253,19 @@ struct Gates { } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that -/// may declare its module and, when none does, in the files above them through inline modules +/// may declare its module and in the files above them through inline modules /// (`mod platform { mod child; }` loads `platform/child.rs`). +#[cfg(test)] fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { + module_gates_with(paths, read, &HashMap::new()) +} + +/// [`module_gates`], also looking up each file in the files `edges` ([`path_edges`]) names as +/// declaring it through `#[path]`. +fn module_gates_with(paths: &[String], read: &dyn Fn(&str) -> Option, edges: &HashMap>) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } + let gates = file_gates(path, read, edges, 0); if !gates.preds.is_empty() { out.insert(path.clone(), gates); } @@ -3794,12 +4273,83 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> Hash out } +/// The [`Gates`] of one file: each route that loads it (a declaring file, at any depth of inline +/// modules) contributes that declaration's predicates and its parent's own gates. Several routes +/// join into one `any(all(…), …)`, so the tests are off only when every route leaves them out. +fn file_gates(at: &str, read: &dyn Fn(&str) -> Option, edges: &HashMap>, depth: usize) -> Gates { + let mut gates = Gates::default(); + if depth >= 16 { + return gates; + } + let declared_by = edges.get(at).cloned().unwrap_or_default(); + // A crate root that a `#[path]` declaration also loads still runs as its own target. + let root = module_parent(at).is_none(); + let (name, mut candidates) = match module_parent(at) { + Some((n, c)) => (n.to_owned(), c), + None if !declared_by.is_empty() => (at.rsplit_once('/').map_or(at, |(_, f)| f).trim_end_matches(".rs").to_owned(), vec![]), + None => return gates, + }; + for d in &declared_by { + if !candidates.contains(d) { + candidates.push(d.clone()); + } + } + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let mut module_dir = if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }; + let mut chain: Vec = vec![]; + let mut found = vec![]; + for _ in 0..4 { + let want = Loaded { path: at, name: &name, chain: &chain }; + found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + let Some(dir) = module_dir.take() else { break }; + let Some((up, seg)) = dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = Some(up); + } + for parent in declared_by { + let Some(src) = read(&parent) else { continue }; + let m = mask(&src); + let chains: BTreeSet> = words(&m, b"mod", 0, m.len()).into_iter().map(|at| inline_mods(&m, at)).collect(); + for chain in chains { + let want = Loaded { path: at, name: &name, chain: &chain }; + if let Some(route) = declared_cfgs(&src, &parent, &want) { + let entry = (parent.clone(), route); + if !found.contains(&entry) { + found.push(entry); + } + } + } + } + let mut routes: Vec> = vec![]; + for (parent, (preds, lines)) in found { + let up = file_gates(&parent, read, edges, depth + 1); + routes.push(preds.into_iter().chain(up.preds).collect()); + gates.sources.push((parent, lines)); + gates.sources.extend(up.sources); + } + if root && !routes.is_empty() { + routes.push(vec![]); + } + match routes.len() { + 0 => {} + 1 => gates.preds = routes.pop().unwrap_or_default(), + _ => gates.preds.push(format!("any({})", routes.iter().map(|p| format!("all({})", p.join(","))).collect::>().join(","))), + } + gates +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); // A change to an attribute that turns the test off counts as a change to the test. - let attr_lines: Vec = local.iter().map(|&(_, at)| v.file.lines.of(at)).collect(); - let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); + let attr_lines: Vec = local.iter().flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect(); + let mut preds: Vec = local.into_iter().map(|(p, _, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -3859,8 +4409,31 @@ fn names_rect(op: &str) -> bool { if b.get(after) == Some(&b'(') { after = matching(b, after).map_or(b.len(), |c| c + 1); } - let rest = &op[after..]; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + // The rect, or a part of it, has to be the whole operand: `rect.min.x`, not + // `rect.width() - other.width()`. + let mut rest = &op[after..]; + loop { + let coord = [".x", ".y"].iter().find(|c| rest.starts_with(**c) && !rest.as_bytes().get(2).copied().is_some_and(is_ident)); + match RECT_PARTS.iter().find(|p| rest.starts_with(**p) && !rest.as_bytes().get(p.len()).copied().is_some_and(is_ident)).or(coord) { + Some(p) => rest = &rest[p.len()..], + None => break, + } + } + // Before it, only the path or receiver chain it is read through (`resp.rect`). + let prefix = op[..i].trim_start_matches(['&', '*']); + let mut at = 0; + let mut operator = false; + while at < prefix.len() { + match prefix.as_bytes()[at] { + b'(' | b'[' | b'{' => at = matching(prefix.as_bytes(), at).map_or(prefix.len(), |close| close + 1), + b'+' | b'-' | b'*' | b'/' | b'%' | b'^' | b'|' | b',' | b'=' | b'<' | b'>' | b'!' => { + operator = true; + break; + } + _ => at += 1, + } + } + if rest.is_empty() && !operator { return true; } } @@ -3898,7 +4471,13 @@ fn exact_pixels(v: &View) -> Vec { return None; }; let pixel = (names_rect(&l) && only_numbers(&r)) || (names_rect(&r) && only_numbers(&l)); - pixel.then(|| v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) + // The span runs through the compared operands, not the failure message. + let operands = if a.name.ends_with("_eq") { a.args[1].1 } else { a.args[0].1 }; + pixel.then(|| { + let mut h = v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name)); + h.last = h.last.max(v.file.lines.of(operands)); + h + }) }) .collect() } @@ -3991,6 +4570,57 @@ mod tests { assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } + #[test] + fn census_follows_the_calls_that_run_for_each_entry() { + let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| census_in(&loop_of(body)); + assert_eq!(census("assert!(menu(c).is_some() || verify_fallback(c).is_ok());"), [(2, "census")], "a helper after || can be skipped"); + assert_eq!(census("assert!(menu(c).is_some() && verify_fallback(c).is_ok());"), [], "a helper after && runs"); + assert_eq!(census("assert!(menu(c).is_some()); { let c = fallback(); app.run(c); }"), [(2, "census")], "a shadowed entry name"); + assert_eq!(census("assert!(menu(c).is_some()); app.run(c);"), [], "the entry itself"); + assert_eq!(census("let _run = || app.run(c); assert!(menu(c).is_some());"), [(2, "census")], "a closure that is never called"); + assert_eq!(census("assert!(app.run::(c).is_ok());"), [], "a call with a turbofish"); + assert_eq!(census("assert!(menu::(c).is_some());"), [(2, "census")], "an entry-only call with a turbofish"); + assert_eq!(census("assert!(render(c, -offset).is_ok());"), [], "a negated variable is another input"); + assert_eq!(census("assert!(render(c, -2).is_ok());"), [(2, "census")], "a negative literal is not"); + assert_eq!( + census("let _ = menu(c).is_some() || { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a block on the right of || can be skipped" + ); + assert_eq!( + census("let _ = (menu(c).is_some() || other(c).is_some()) && { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [], + "an || in an earlier group does not skip the block" + ); + assert_eq!(census("assert!(menu(c).is_some()); if first || second {} app.run(c);"), [], "an || in a finished if does not skip the call"); + assert_eq!( + census("let entry = c; let c = fallback(); let c = entry; assert!(menu(c).is_some()); app.run(c);"), + [], + "a name rebound from the entry is the entry again" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; } assert!(menu(entry).is_some()); app.run(c);"), + [(2, "census")], + "an inner entry binding does not end the outer fallback binding" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; app.run(c); } assert!(menu(entry).is_some());"), + [], + "the inner entry binding is live inside its block" + ); + assert_eq!( + census("let Row { c: other } = fallback(); assert!(menu(c).is_some()); app.run(c);"), + [], + "a field label does not rebind the entry" + ); + let receiver = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(k.parse(), k);\n }\n}\n"; + assert_eq!(census_in(receiver), [(2, "census")], "a round trip with the entry as receiver"); + let fixed = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(registry.lookup(\"baseline\"), k);\n }\n}\n"; + assert_eq!(census_in(fixed), [], "a lookup of a fixed key"); + } + #[test] fn census_loops_over_whole_tables_are_reported() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -5750,4 +6380,272 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + fn never_run_test() -> &'static str { + "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n" + } + + #[test] + fn base_hits_match_the_same_test_not_only_its_name() { + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn smoke() {}\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn smoke() {}\n}\n"; + let now: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + assert_eq!(now.len(), 2); + // At the base only `a::smoke` was off. + let base = [now[0].clone()]; + assert!(!newly_off(&base, &now[0]), "a::smoke was off at the base"); + assert!(newly_off(&base, &now[1]), "b::smoke has the same name and ran at the base"); + } + + #[test] + fn an_oversized_base_file_is_not_an_absent_one() { + assert_eq!(base_source(None), BaseSource::Absent); + assert_eq!(base_source(Some("mod child;\n".into())), BaseSource::Text("mod child;\n".into())); + assert_eq!(base_source(Some("x".repeat(MAX_FILE as usize + 1))), BaseSource::TooLarge); + } + + #[test] + fn a_removed_route_counts_as_a_route_change() { + let lib = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(unix)]\n#[path = \"child.rs\"]\nmod other;\n"; + let base_files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib), ("crates/x/src/child.rs", "")].into_iter().collect(); + let base_read = |p: &str| base_files.get(p).map(|s| (*s).to_owned()); + let base = module_gates(&["crates/x/src/child.rs".to_owned()], &base_read); + let now_lib = "#[cfg(target_os = \"macos\")]\nmod child;\n"; + let now_files: HashMap<&str, &str> = [("crates/x/src/lib.rs", now_lib), ("crates/x/src/child.rs", "")].into_iter().collect(); + let now_read = |p: &str| now_files.get(p).map(|s| (*s).to_owned()); + let now = module_gates(&["crates/x/src/child.rs".to_owned()], &now_read); + let changed: BTreeMap>> = [("crates/x/src/lib.rs".to_owned(), Some(BTreeSet::new()))].into_iter().collect(); + assert!(!gate_changed(now.get("crates/x/src/child.rs"), &changed), "the surviving declaration did not change"); + assert!(routes_changed(now.get("crates/x/src/child.rs"), base.get("crates/x/src/child.rs"), &changed)); + let ctx_now = Ctx { module_cfgs: now.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let ctx_base = Ctx { module_cfgs: base.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let off = lint_file("crates/x/src/child.rs", never_run_test(), &ctx_now); + assert_eq!(off.iter().filter(|h| h.rule == Rule::NeverRun).count(), 1); + assert!(newly_off(&lint_file("crates/x/src/child.rs", never_run_test(), &ctx_base), &off[0]), "the Unix route ran it at the base"); + } + + #[test] + fn cfg_string_values_are_decoded() { + let t = &CI_TARGETS[0]; + assert_eq!(cfg_value("target_os=\"lin\\x75x\"", t), Some(true)); + assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", t), Some(true)); + assert_eq!(cfg_value("target_os=r\"linux\"", t), Some(true)); + assert_eq!(cfg_value("target_os=r#\"lin\\x75x\"#", t), Some(false), "raw contents are kept"); + assert_eq!(cfg_value("target_os=\"lin\\qux\"", t), None, "an escape this does not decode"); + assert_eq!(cfg_value("target_os=\"macos\"", t), Some(false)); + let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", escaped), []); + } + + #[test] + fn every_line_of_a_multiline_cfg_counts() { + let src = "#[cfg(\n target_os = \"macos\"\n)]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[2].into_iter().collect())), "a change to the predicate line"); + assert!(!touches(hit, Some(&[4].into_iter().collect())), "the line between the attribute and the test"); + let lib = "#[cfg(\n target_os = \"macos\"\n)]\nmod child;\n"; + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let lines = declared_cfgs(lib, "src/lib.rs", &child).map(|(_, l)| l).unwrap_or_default(); + assert!(lines.contains(&2), "the predicate line of the declaration's cfg: {lines:?}"); + } + + #[test] + fn a_tests_folder_inside_src_is_a_module() { + assert_eq!(module_parent("crates/x/src/tests/child.rs").map(|(n, _)| n), Some("child")); + assert!(module_parent("crates/x/tests/it.rs").is_none(), "an integration test root"); + assert!(module_parent("crates/x/examples/demo.rs").is_none()); + let files: HashMap<&str, &str> = + [("crates/x/src/tests/mod.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/tests/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + assert!(module_cfgs(&["crates/x/src/tests/child.rs".to_owned()], &read).contains_key("crates/x/src/tests/child.rs")); + } + + #[test] + fn raw_path_attributes_load_their_file() { + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let both = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(unix)]\n#[path = r\"child.rs\"]\nmod alias;\n"; + assert_eq!(declared_cfgs(both, "src/lib.rs", &child).map(|(p, _)| p), Some(vec!["any(all(target_os=\"macos\"),all(unix))".to_owned()])); + let hashed = "#[path = r#\"child.rs\"#]\nmod alias;\n"; + assert_eq!(declared_cfgs(hashed, "src/lib.rs", &child).map(|(p, _)| p), Some(vec![])); + } + + #[test] + fn path_declarations_outside_the_module_directory_are_followed() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod platform;\n"), + ("crates/x/src/platform.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod imp;\n"), + ("crates/x/src/shared.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let all: Vec = files.keys().map(|k| (*k).to_owned()).collect(); + let edges = path_edges(&all, &read); + assert_eq!(edges.get("crates/x/src/shared.rs"), Some(&vec!["crates/x/src/platform.rs".to_owned()])); + let gates = module_gates_with(&["crates/x/src/shared.rs".to_owned()], &read, &edges); + assert_eq!(gates.get("crates/x/src/shared.rs").map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + let sibling = Loaded { path: "crates/x/src/shared.rs", name: "shared", chain: &[] }; + let ordinary = "mod shared;\n#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod mac_shared;\n"; + assert_eq!( + declared_cfgs(ordinary, "crates/x/src/platform.rs", &sibling).map(|(p, _)| p), + Some(vec!["target_os=\"macos\"".to_owned()]), + "`mod shared;` in platform.rs loads platform/shared.rs, not the sibling" + ); + let target: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/smoke.rs\"]\nmod smoke;\n"), + ("crates/x/tests/smoke.rs", ""), + ] + .into_iter() + .collect(); + let read_target = |p: &str| target.get(p).map(|s| (*s).to_owned()); + let target_files: Vec = target.keys().map(|k| (*k).to_owned()).collect(); + let target_cfgs: HashMap> = + module_gates_with(&["crates/x/tests/smoke.rs".to_owned()], &read_target, &path_edges(&target_files, &read_target)) + .into_iter() + .map(|(p, g)| (p, g.preds)) + .collect(); + let target_ctx = Ctx { module_cfgs: target_cfgs, ..ctx() }; + assert_eq!(hits_in("crates/x/tests/smoke.rs", never_run_test(), &target_ctx), [], "Cargo still runs the integration test"); + let present = ["crates/x/src/platform.rs".to_owned()]; + let mut chained = edges.clone(); + chained.insert("crates/x/src/inner.rs".to_owned(), vec!["crates/x/src/shared.rs".to_owned()]); + let (loaded, dirs) = path_loaded(&chained, &present, &["crates/x/src/platform/".to_owned()]); + assert!(loaded.contains("crates/x/src/shared.rs") && loaded.contains("crates/x/src/inner.rs"), "followed transitively: {loaded:?}"); + assert!(dirs.contains(&"crates/x/src/shared/".to_owned())); + let base = merge_edges(&edges_without(&edges, &present), HashMap::new()); + assert!(base.is_empty(), "the changed file's routes come from its base text"); + for file in ["mod.rs", "lib.rs", "main.rs"] { + let path = format!("crates/x/src/shared/{file}"); + let mut with_children = HashMap::new(); + with_children.insert(path.clone(), vec![present[0].clone()]); + with_children.insert("crates/x/src/elsewhere.rs".to_owned(), vec!["crates/x/src/shared/child.rs".to_owned()]); + let (loaded, dirs) = path_loaded(&with_children, &present, &[]); + assert!(loaded.contains(&path)); + assert!(dirs.contains(&"crates/x/src/shared/".to_owned()), "the module directory of {file}"); + assert!(loaded.contains("crates/x/src/elsewhere.rs"), "path declarations in children of {file} are followed"); + } + } + + #[test] + fn inline_path_declarations_keep_their_module_chain() { + for parent in ["crates/x/src/lib.rs", "crates/x/src/mod.rs", "crates/x/src/platform.rs"] { + let source = "#[cfg(target_os = \"macos\")]\nmod outer { mod inner { #[path = \"../../../shared.rs\"] mod shared; } }\n"; + let target = if parent.ends_with("platform.rs") { "crates/x/src/shared.rs" } else { "crates/x/shared.rs" }; + let read = |p: &str| (p == parent).then(|| source.to_owned()); + let edges = path_edges(&[parent.to_owned()], &read); + assert_eq!(edges.get(target), Some(&vec![parent.to_owned()]), "the inline directory under {parent}"); + let gates = module_gates_with(&[target.to_owned()], &read, &edges); + let gate = gates.get(target).unwrap(); + assert_eq!(gate.preds, ["target_os=\"macos\""], "the inline declaration's gate in {parent}"); + assert!(gate.sources.iter().any(|(p, lines)| p == parent && lines.contains(&1) && lines.contains(&2))); + let gated = Ctx { module_cfgs: gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + assert_eq!(hits_in(target, never_run_test(), &gated), [(2, "never-run")]); + } + } + + #[test] + fn deleted_parent_query_includes_renamed_away_paths() { + assert_eq!(deleted_diff_args("base-revision"), ["diff", "--name-only", "-z", "--diff-filter=D", "--no-renames", "base-revision"]); + assert_eq!(nul_paths("crates/x/src/plateforme-é.rs\0crates/x/src/a b.rs\0"), ["crates/x/src/plateforme-é.rs", "crates/x/src/a b.rs"]); + let edges: HashMap> = + [("crates/x/src/shared.rs".to_owned(), vec!["crates/x/src/bin/check.rs".to_owned()])].into_iter().collect(); + let deleted = ["crates/x/src/bin/check.rs".to_owned()]; + assert!(path_loaded(&edges, &deleted, &[]).0.contains("crates/x/src/shared.rs"), "a deleted parent's base route"); + let build: HashMap<&str, &str> = + [("apps/a/build.rs", "#[path = \"src/channel.rs\"]\nmod channel;\n"), ("apps/a/src/main.rs", "mod channel;\n")].into_iter().collect(); + let read_build = |p: &str| build.get(p).map(|s| (*s).to_owned()); + let build_files: Vec = build.keys().map(|k| (*k).to_owned()).collect(); + assert!(path_edges(&build_files, &read_build).is_empty(), "a build script is not a test route"); + } + + #[test] + fn routes_at_every_depth_are_kept() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod platform;\n"), + ("crates/x/src/main.rs", "mod platform {\n mod child;\n}\n"), + ("crates/x/src/platform.rs", "mod child;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let both = Ctx { module_cfgs: module_cfgs(&["crates/x/src/platform/child.rs".to_owned()], &read), ..ctx() }; + assert_eq!(hits_in("crates/x/src/platform/child.rs", never_run_test(), &both), [], "the binary's inline module runs it"); + let mac_only: HashMap<&str, &str> = files.iter().filter(|(k, _)| **k != "crates/x/src/main.rs").map(|(k, v)| (*k, *v)).collect(); + let read = |p: &str| mac_only.get(p).map(|s| (*s).to_owned()); + let library = Ctx { module_cfgs: module_cfgs(&["crates/x/src/platform/child.rs".to_owned()], &read), ..ctx() }; + assert_eq!(hits_in("crates/x/src/platform/child.rs", never_run_test(), &library), [(2, "never-run")]); + } + + #[test] + fn multiline_mirror_and_pixel_hits_cover_their_operands() { + let mirror = "#[test]\nfn t() {\n assert_eq!(\n scale(p, 2.0),\n scale(p, 1.0) * 2.0,\n \"message\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", mirror, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::Mirror).unwrap(); + assert!(touches(hit, Some(&[5].into_iter().collect())), "a change to the expected operand"); + assert!(!touches(hit, Some(&[6].into_iter().collect())), "a change to the message"); + let pixel = + "use egui::Rect;\n#[test]\nfn t() {\n assert_eq!(\n button_rect.min.x,\n 120.0,\n \"message\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", pixel, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::ExactPixel).unwrap(); + assert!(touches(hit, Some(&[6].into_iter().collect())), "a change to the expected operand"); + assert!(!touches(hit, Some(&[7].into_iter().collect())), "a change to the message"); + } + + #[test] + fn a_rect_width_difference_is_not_a_hard_coded_width() { + let ui = |body: &str| format!("use egui::Rect;\n#[test]\nfn t() {{\n {body}\n}}\n"); + assert_eq!(only("exact-pixel", &ui("assert_eq!(left_rect.width() - right_rect.width(), 0.0);")), []); + assert_eq!(only("exact-pixel", &ui("assert_eq!(left_rect.width(), 120.0);")), [(4, "exact-pixel")]); + assert_eq!(only("exact-pixel", &ui("assert_eq!(left_rect.min.x, 12.0);")), [(4, "exact-pixel")]); + assert_eq!(only("exact-pixel", &ui("assert_eq!(panels[0].rect.width(), 120.0);")), [(4, "exact-pixel")], "a rect reached through indexing"); + assert_eq!( + only("exact-pixel", &ui("assert_eq!(panels[i - 1].rect.width(), 120.0);")), + [(4, "exact-pixel")], + "arithmetic inside the receiver's index" + ); + assert_eq!(only("exact-pixel", &ui("assert_eq!(2.0 * rect.width(), 120.0);")), [], "arithmetic on the rect width"); + assert_eq!(only("exact-pixel", &ui("assert_eq!(panels[i - 1].rect.width() - right_rect.width(), 0.0);")), []); + assert_eq!(only("exact-pixel", &ui("assert_eq!(response().rect.width(), 120.0);")), [(4, "exact-pixel")], "a rect returned by a call"); + } + + #[test] + fn a_match_binding_shadows_the_outer_fixture_in_its_arm() { + let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => {}\n }\n}\n"; + assert_eq!(only("fixture-only", arm), []); + let after = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) => consume(m),\n None => {}\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the match"); + let label = + "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Row { n: actual } => assert_eq!(n, 0),\n _ => {}\n }\n}\n"; + assert_eq!(only("fixture-only", label), [(2, "fixture-only")], "a field label binds another name"); + } + + #[test] + fn reads_source_needs_a_path_read_of_a_known_rust_file() { + let rs = |call: &str| only("reads-source", &format!("#[test]\nfn t() {{\n let s = {call};\n assert!(s.contains(\"x\"));\n}}\n")); + assert_eq!(rs("fs::read_to_string(format!(\"{}.json\", \"snapshot.rs\")).unwrap()"), [], "a format argument is not the path"); + assert_eq!(rs("fs::read_to_string(\"sample.r s\").unwrap()"), [], "whitespace inside a literal is kept"); + assert_eq!(rs("fs::read_to_string(\"test data/sample.rs\").unwrap()"), [(3, "reads-source")]); + assert_eq!(rs("Read::read_to_string(&mut r, &mut String::from(\"seed.rs\")).unwrap()"), [], "an output buffer"); + assert_eq!(rs("r.read_to_string(&mut String::from(\"seed.rs\")).unwrap()"), [], "a reader method"); + assert_eq!(rs("std::fs::read_to_string(\"src/lib.rs\").unwrap()"), [(3, "reads-source")]); + assert_eq!(rs("fs::read_to_string(format!(\"src/{name}.rs\")).unwrap()"), [(3, "reads-source")], "a format string with a Rust suffix"); + assert_eq!( + rs("fs::read_to_string(format!(\"{}/{}\", root, \"src/lib.rs\")).unwrap()"), + [(3, "reads-source")], + "a value substituted at the end" + ); + let alias = "use std::fs as filesystem;\n#[test]\nfn t() {\n let s = filesystem::read_to_string(\"src/lib.rs\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", alias), [(4, "reads-source")], "an alias of std::fs"); + let tree = alias.replace("use std::fs as filesystem;", "use std::{fs as filesystem, io};"); + assert_eq!(only("reads-source", &tree), [(4, "reads-source")], "an alias in an import tree"); + let self_alias = alias.replace("use std::fs as filesystem;", "use std::fs::{self as filesystem, File};"); + assert_eq!(only("reads-source", &self_alias), [(4, "reads-source")], "a self alias in a filesystem import tree"); + let later_alias = alias.replace("use std::fs as filesystem;", "use std::{io as input, fs::{File, self as filesystem}};"); + assert_eq!(only("reads-source", &later_alias), [(4, "reads-source")], "a self alias after other imported names and aliases"); + let imported = "use std::fs::read_to_string;\n#[test]\nfn t() {\n let s = read_to_string(\"src/lib.rs\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", imported), [(4, "reads-source")]); + let glob = imported.replace("use std::fs::read_to_string;", "use std::fs::*;"); + assert_eq!(only("reads-source", &glob), [(4, "reads-source")], "a glob import"); + } } From 28559ec558340323d05043fe7806ece9ecd585fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:52:27 -0800 Subject: [PATCH 4/8] xtask: test-lint reads cfg_attr path routes, numeric literals, turbofish reads and spaced cfg strings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - never-run follows `#[cfg_attr(, path = "…")]` routes: a routed file loads under its condition (after earlier routes fail), the default or plain `#[path]` file loads only when no route applies, and path_edges follows the routed file. Path strings are split outside literals and their escapes decoded. - The census literal check accepts one numeric literal or fixed arithmetic on literals (`1`, `-2`, `1 << 4`); `1 + offset`, `1..limit` and `1usize - offset` count as another input. - reads-source skips a turbofish after `fs::read_to_string` (`::<&str>`). - cfg predicates keep whitespace inside string values (`"li nux"` is not `linux`), and a comma inside a string value no longer splits `any(…)`/`all(…)`. --- xtask/src/test_lint.rs | 249 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 236 insertions(+), 13 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 1a7731430a..5b2d45eba8 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -319,7 +319,11 @@ fn path_edges(files: &[String], read: &dyn Fn(&str) -> Option) -> HashMa continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + // A `cfg_attr` route loads its file when its condition holds. + let rels = path_attr(&m, src.as_bytes(), item, at) + .into_iter() + .chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, rel)| rel)); + for rel in rels { let target = path_target(parent, &inline_mods(&m, at), &rel); let parents = out.entry(target).or_default(); if !parents.contains(parent) { @@ -1753,11 +1757,30 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. // A minus sign makes a literal only in front of a number (`-2`, not `-offset`). let s = s.strip_prefix('-').unwrap_or(s); - s.is_empty() - || s.starts_with(['"', '\'', '|']) - || s.starts_with("move|") - || s.starts_with(|c: char| c.is_ascii_digit()) - || matches!(s, "true" | "false" | "None") + let mut start = 0; + let mut operands = 0; + let mut numeric = true; + for (i, c) in s.char_indices().chain([(s.len(), '+')]) { + if !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { + continue; + } + let head = &s[start..i]; + if i < s.len() + && matches!(c, '+' | '-') + && head + .strip_suffix(['e', 'E']) + .is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.bytes().all(|c| c.is_ascii_digit() || matches!(c, b'_' | b'.'))) + { + continue; + } + if !head.is_empty() { + operands += 1; + numeric &= numeric_literal(head); + } + start = i + c.len_utf8(); + } + let numeric = numeric && operands > 0; + s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None") }; (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { let mut start = name_end; @@ -1797,6 +1820,61 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { }) } +/// Whether the whitespace-free `s` is one numeric literal (`1`, `0x1F`, `2.5f32`, `1_000`, `1e-3`), not +/// an expression that starts with one (`1+offset`, `1..limit`). +fn numeric_literal(s: &str) -> bool { + let b = s.as_bytes(); + let radix = match b.get(..2) { + Some(b"0x") => 16, + Some(b"0o") => 8, + Some(b"0b") => 2, + _ => 10, + }; + let mut i = if radix == 10 { 0 } else { 2 }; + let mut digits = 0; + while let Some(&c) = b.get(i) { + if (c as char).is_digit(radix) { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 || !b.first().is_some_and(u8::is_ascii_digit) { + return false; + } + if radix == 10 { + if b.get(i) == Some(&b'.') { + i += 1; + if i < b.len() && !b[i].is_ascii_digit() { + return false; + } + while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'_') { + i += 1; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + let mut digits = 0; + while let Some(&c) = b.get(i) { + if c.is_ascii_digit() { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 { + return false; + } + } + } + matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") +} + /// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the /// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { @@ -3490,7 +3568,11 @@ fn reads_source_hits(file: &File) -> Vec { continue; } } - let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + let mut open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + if word == b"read_to_string" { + // A turbofish may follow the filesystem read: `fs::read_to_string::<&str>(path)`. + open = skip_turbofish(m, open); + } let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; // Whitespace inside a literal is part of the path (`"sample.r s"`). let arg = norm_outside_literals(&code[open + 1..close], &m[open + 1..close]); @@ -3922,7 +4004,8 @@ fn cfg_value(p: &str, t: &Target) -> Option { if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) { let mut parts = vec![]; let mut start = 0; - for at in top_level_at(args, ",").into_iter().chain([args.len()]) { + // A comma inside a string value does not split the arguments (`target_os = "a,unix"`). + for at in top_level_at(&String::from_utf8_lossy(&mask(args)), ",").into_iter().chain([args.len()]) { if at > start { parts.push(cfg_value(&args[start..at], t)); } @@ -4063,10 +4146,12 @@ fn cfg_attr_preds(text: &str, outer: Option<&str>) -> Vec { out } -/// A `cfg` predicate's source text without whitespace or comments. Masking would also blank the -/// string literals `target_os = "macos"` needs, so only comments are blanked. +/// A `cfg` predicate's source text without comments or the whitespace between tokens. Masking would +/// also blank the string literals `target_os = "macos"` needs, so only comments are blanked, and +/// whitespace inside a string literal is kept. fn pred_text(src: &[u8]) -> String { - norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) + let text = String::from_utf8_lossy(src); + norm_outside_literals(&mask_parts(&text, true, false), &mask(&text)) } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the @@ -4146,8 +4231,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => path_target(parent, want.chain, &rel) == want.path, + // The condition under which a `cfg_attr` route decides the file, when one does. + // Rust takes the first `path` attribute that applies, so only the routes before a plain + // `#[path]` can take its place. + let mut routed = None; + let direct = words(&m, b"path", item, at).into_iter().find_map(|w| path_attr(&m, src.as_bytes(), w, w + 4).map(|rel| (w, rel))); + let routes = cfg_attr_paths(&m, src.as_bytes(), item, direct.as_ref().map_or(at, |(w, _)| *w)); + let fallback = match &direct { + Some((_, rel)) => path_target(parent, want.chain, rel) == want.path, None => { // The default file of `mod name;`: `name.rs` or `name/mod.rs` under the declaring // module's directory and the inline modules around the declaration. @@ -4163,6 +4254,37 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, && [format!("{name}.rs"), format!("{name}/mod.rs")].iter().any(|f| join_path(&base, f) == want.path) } }; + let loads = if routes.is_empty() { + fallback + } else { + // The fallback file loads only when no route's condition holds. + let mut conds: Vec = routes + .iter() + .enumerate() + .filter(|(_, (_, rel))| path_target(parent, want.chain, rel) == want.path) + .map(|(i, (c, _))| { + if i == 0 { + c.clone() + } else { + let earlier = routes[..i].iter().map(|(c, _)| format!("not({c})")).collect::>(); + format!("all({},{c})", earlier.join(",")) + } + }) + .collect(); + if fallback { + let all: Vec<&str> = routes.iter().map(|(c, _)| c.as_str()).collect(); + conds.push(match all.as_slice() { + [one] => format!("not({one})"), + _ => format!("not(any({}))", all.join(",")), + }); + } + routed = match conds.len() { + 0 => None, + 1 => conds.pop(), + _ => Some(format!("any({})", conds.join(","))), + }; + routed.is_some() + }; if !loads { continue; } @@ -4172,6 +4294,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, // Every line of a multiline attribute counts. at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); + if let Some(cond) = routed { + preds.push(cond); + // The lines of the `cfg_attr` attributes that route the file. + for w in words(&m, b"cfg_attr", item, at) { + let open = skip_ws(&m, w + 8); + at_lines.extend(lines.of(w)..=lines.of(matching(&m, open).unwrap_or(w))); + } + } for (p, a, end) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); at_lines.extend(lines.of(a)..=lines.of(end)); @@ -4205,6 +4335,45 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { }) } +/// The `path = "…"` values inside the `#[cfg_attr(, …)]` attributes in `m[from..to]`, each +/// with its condition (`#[cfg_attr(unix, path = "x.rs")]` gives `("unix", "x.rs")`). A nested +/// `cfg_attr` joins its condition to the enclosing ones with `all(…)`. +fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { + fn walk(text: &str, outer: Option<&str>, out: &mut Vec<(String, String)>) { + // Commas and brackets inside a string literal do not split the arguments (`"mac,impl.rs"`). + let cuts = top_level_at(&String::from_utf8_lossy(&mask(text)), ","); + let Some(&first) = cuts.first() else { return }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(v) = arg.strip_prefix("path=") { + // An ordinary or raw string, with its escapes decoded: `"x.rs"`, `r#"x.rs"#`, `"\x6dac.rs"`. + if let Some(rel) = cfg_string(v) { + out.push((cond.clone(), rel)); + } + } else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) { + walk(n, Some(&cond), out); + } + start = cut + 1; + } + } + let mut out = vec![]; + for at in words(m, b"cfg_attr", from, to) { + let before = m[..at].trim_ascii_end(); + if !before.strip_suffix(b"[").is_some_and(|h| h.trim_ascii_end().ends_with(b"#") && !h.trim_ascii_end().ends_with(b"#!")) { + continue; + } + let open = skip_ws(m, at + 8); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + walk(&pred_text(&src[open + 1..close]), None, &mut out); + } + out +} + /// `rel` joined to the directory `base`, with `.` and `..` resolved. fn join_path(base: &str, rel: &str) -> String { let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); @@ -4526,6 +4695,27 @@ mod tests { assert_eq!(census(derived), [(2, "census")]); let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n"; assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip"); + let fixed_arg = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1), Some(k));\n assert_eq!(Kind::from_id(k.id(), -2), Some(k));\n }\n}\n"; + assert_eq!(census(fixed_arg), [(2, "census")], "a numeric literal is not another input"); + let shifted = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1 << 4), Some(k));\n }\n}\n"; + assert_eq!(census(shifted), [(2, "census")], "fixed arithmetic is not another input"); + let offset = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1 + offset), Some(k));\n }\n}\n"; + assert_eq!(census(offset), [], "an expression that only starts with a digit is another input"); + let suffixed = + "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1usize - offset), Some(k));\n }\n}\n"; + assert_eq!(census(suffixed), [], "a suffixed number minus a variable is another input"); + let range = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1..limit), Some(k));\n }\n}\n"; + assert_eq!(census(range), [], "a range with a variable bound is another input"); + } + + #[test] + fn numeric_literals_are_one_token() { + for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] { + assert!(numeric_literal(s), "{s}"); + } + for s in ["1+offset", "1..limit", "1usize-offset", "1<<4"] { + assert!(!numeric_literal(s), "{s}"); + } } #[test] @@ -6329,6 +6519,10 @@ mod tests { fn reads_source_covers_read_to_string_of_rust_files() { let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", read), [(3, "reads-source")]); + let turbofish = "#[test]\nfn t() {\n let s = fs::read_to_string::<&str>(\"src/lib.rs\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", turbofish), [(3, "reads-source")], "a turbofish before the argument"); + let suffix = "#[test]\nfn t() {\n assert!(rendered.ends_with::<&str>(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", suffix), [], "a string suffix check"); let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", data), []); let comment = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"input.rs\" */ \"data.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; @@ -6432,8 +6626,11 @@ mod tests { assert_eq!(cfg_value("target_os=r#\"lin\\x75x\"#", t), Some(false), "raw contents are kept"); assert_eq!(cfg_value("target_os=\"lin\\qux\"", t), None, "an escape this does not decode"); assert_eq!(cfg_value("target_os=\"macos\"", t), Some(false)); + assert_eq!(cfg_value("any(target_os=\"foo,unix,bar\")", t), Some(false), "a comma inside a string value"); let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", escaped), []); + let spaced = "#[cfg(target_os = \"li nux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", spaced), [(3, "never-run")], "whitespace inside a string value is kept"); } #[test] @@ -6469,6 +6666,32 @@ mod tests { assert_eq!(declared_cfgs(hashed, "src/lib.rs", &child).map(|(p, _)| p), Some(vec![])); } + #[test] + fn cfg_attr_path_attributes_load_their_file() { + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let declared = |src: &str| declared_cfgs(src, "src/lib.rs", &child).map(|(p, _)| p); + let routed = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg_attr(unix, path = \"child.rs\")]\nmod alias;\n"; + assert_eq!(declared(routed), Some(vec!["any(all(target_os=\"macos\"),all(unix))".to_owned()])); + let away = "#[cfg_attr(target_os = \"macos\", path = \"mac_child.rs\")]\nmod child;\n"; + assert_eq!(declared(away), Some(vec!["not(target_os=\"macos\")".to_owned()]), "the default file loads only when the condition fails"); + let comma = Loaded { path: "src/mac,impl.rs", name: "imp", chain: &[] }; + let routed = "#[cfg_attr(target_os = \"macos\", path = \"mac,impl.rs\")]\nmod imp;\n"; + assert_eq!(declared_cfgs(routed, "src/lib.rs", &comma).map(|(p, _)| p), Some(vec!["target_os=\"macos\"".to_owned()]), "a comma in the path"); + let escaped = "#[cfg_attr(unix, path = \"\\x63hild.rs\")]\nmod alias;\n"; + assert_eq!(declared(escaped), Some(vec!["unix".to_owned()]), "an escape in the path is decoded"); + let ordered = "#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\n#[path = \"child.rs\"]\nmod alias;\n"; + assert_eq!(declared(ordered), Some(vec!["not(target_os=\"macos\")".to_owned()]), "an earlier route takes the place of a plain path"); + let routes = "#[cfg_attr(unix, path = \"unix.rs\")]\n#[cfg_attr(target_os = \"linux\", path = \"child.rs\")]\nmod alias;\n"; + assert_eq!(declared(routes), Some(vec!["all(not(unix),target_os=\"linux\")".to_owned()])); + let later = "#[path = \"child.rs\"]\n#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\nmod alias;\n"; + assert_eq!(declared(later), Some(vec![]), "a route after a plain path never applies"); + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\nmod imp;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let edges = path_edges(&["crates/x/src/lib.rs".to_owned()], &read); + assert_eq!(edges.get("crates/x/src/mac.rs"), Some(&vec!["crates/x/src/lib.rs".to_owned()])); + } + #[test] fn path_declarations_outside_the_module_directory_are_followed() { let files: HashMap<&str, &str> = [ From da8e9cc197cbea035bdd840d6b70764934b250cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:03:36 -0800 Subject: [PATCH 5/8] xtask: test-lint census leaves out loops that run each entry through a computation A loop over a whole table whose body passes the entry to a call together with other state (a command run, a file written, a render, a parse of other input) checks behavior for each entry, so the census rule no longer reports it. A lookup, a call on the entry alone, literal arguments and calls in a failure message still count as a census. The call counts only where it runs whenever the loop's assertions pass: not after an `||`, not on the right of an `&&` whose result is not asserted, not inside an `if`, `else`, `match` arm, `while` or async body, and not inside a closure the loop never calls. A name counts as the entry from the `let` that binds it from the entry to the end of its block, and not where a nested loop, a closure parameter or another `let` rebinds it or where it names a field. An asserting helper keeps a loop out of the census only where it runs the same way, and a round trip can read the entry as its receiver (`k.parse()`). --- xtask/src/test_lint.rs | 799 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 793 insertions(+), 6 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 449885209f..9746b77bcd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -45,7 +45,9 @@ //! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of //! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`, //! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or -//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. A loop that +//! passes the entry to a call together with other state (a command run, a file written, a +//! render) is a table of behavior cases and is not reported; //! * `mirror`: `assert_eq!(f(a), f(b) …)`, where the expected side derives its value from a //! second call of the same function (same path) with arithmetic, so a fault in `f` moves both //! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same @@ -1173,6 +1175,11 @@ const COMMON: &[&str] = &[ /// The names called in `m[from..to]`: functions (`name(`, also through a path), methods /// (`.name(`), including calls with turbofish arguments, and macros (`name!`). fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + calls_at(m, from, to).into_iter().map(|(name, method, _)| (name, method)).collect() +} + +/// [`calls`] with the offset where each name starts. +fn calls_at(m: &[u8], from: usize, to: usize) -> Vec<(String, bool, usize)> { let m = &m[..to]; let mut out = vec![]; let mut i = from; @@ -1189,7 +1196,7 @@ fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { let name = String::from_utf8_lossy(&m[i..end]).into_owned(); let method = i > 0 && m[i - 1] == b'.'; if !KEYWORDS.contains(&name.as_str()) { - out.push((if bang { format!("{name}!") } else { name }, method)); + out.push((if bang { format!("{name}!") } else { name }, method, i)); } } i = end; @@ -1619,7 +1626,12 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let weak_in = |from: usize, to: usize, var: &str| { let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); let body = &unmessaged[from - v.t.open..to - v.t.open]; - helpers_in(from, to).is_empty() + // A helper counts only where it runs whenever the assertions pass, not after an `||`. + let (f, t) = (from + 1 - v.t.open, to - v.t.open); + let helper_runs = calls_at(&unmessaged, f, t).into_iter().any(|(n, method, at)| { + !(n.ends_with('!') && is_assert_macro(&n)) && is_helper_call(&n, method, helpers) && runs_with_assertion(&unmessaged, f, t, at) + }); + !helper_runs && !rejects(body) && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::>(), var)) @@ -1636,6 +1648,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { && helpers_in(kw + 2, open).is_empty() && words(m, b"break", open, close).is_empty() && weak_in(open, close, var) + && !feeds_entry(&unmessaged, &pattern, open + 1 - v.t.open, close - v.t.open) { return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; } @@ -1649,6 +1662,511 @@ fn census(v: &View, helpers: &HashSet) -> Vec { vec![] } +/// Calls that read or look up a value rather than compute one, so passing the entry to one of them +/// together with other state does not make the loop a behavior table. +const LOOKUPS: &[&str] = &[ + "contains", + "contains_key", + "starts_with", + "ends_with", + "get", + "get_mut", + "iter", + "into_iter", + "any", + "find", + "position", + "binary_search", + "eq", + "ne", + "find_map", +]; + +/// The lowercase names a `for` or `let` pattern binds. A field label (`Row { c: other }`) binds +/// the name after it. +fn pattern_names(pattern: &str) -> impl Iterator + '_ { + let b = pattern.as_bytes(); + pattern + .match_indices(|c: char| c.is_ascii_alphanumeric() || c == '_') + .filter(move |&(at, _)| at == 0 || !is_ident(b[at - 1])) + .map(move |(at, _)| (at, at + b[at..].iter().take_while(|&&c| is_ident(c)).count())) + .filter(move |&(at, end)| { + // Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`). + let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count(); + let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count(); + !in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':') + }) + .map(move |(at, end)| &pattern[at..end]) + .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) + .map(str::to_owned) +} + +/// Whether the body `b[from..to]` of a loop whose pattern is `pattern` feeds the entry into a +/// computation with other inputs: a call (not one of [`LOOKUPS`], nor a macro) whose receiver and +/// arguments include a value read from the entry and another value that is not a literal, such as +/// `app.run("…", json!({"id": id}))`, `export(&doc, &Options { level, .. })` or `check(SCHEMA, ¶ms)` +/// with `params` bound from the entry inside the loop. Such a loop runs, renders or writes something +/// for each entry, so it is a table of behavior cases. A call that takes the entry alone (`menu(c)`, +/// `Kind::from_id(k.id())`) is still a lookup. +fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { + // The names that hold the entry, each from the end of its binding to the end of its block. + let mut derived: Vec<(String, usize, usize)> = pattern_names(pattern).map(|n| (n, from, to)).collect(); + // Where a binding does not read the entry, the name holds another value until its scope ends. + let mut shadows: Vec<(String, usize, usize)> = vec![]; + for at in words(b, b"for", from, to) { + let Some(&kw) = words(b, b"in", at + 3, to).first() else { continue }; + let Some(open) = loop_open(b, kw + 2, to) else { continue }; + let Some(close) = matching(b, open).filter(|&c| c < to) else { continue }; + shadows.extend(pattern_names(&String::from_utf8_lossy(&b[at + 3..kw])).map(|n| (n, open + 1, close))); + } + // Simple closure parameters shadow captures in both block and expression bodies. + for at in from..to { + if b[at] != b'|' || b.get(at + 1) == Some(&b'|') { + continue; + } + let head = b[from..at].trim_ascii_end(); + let head = head.strip_suffix(b"move").unwrap_or(head).trim_ascii_end(); + if !head.is_empty() && !matches!(head.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) { + continue; + } + let Some(end) = (at + 1..to).find(|&i| b[i] == b'|') else { continue }; + // Parameters may carry types (`|c: Command|`, `|p: &[u8]|`). + if !b[at + 1..end] + .iter() + .all(|&c| is_ident(c) || c.is_ascii_whitespace() || matches!(c, b',' | b'&' | b':' | b'<' | b'>' | b'(' | b')' | b'[' | b']' | b'\'')) + { + continue; + } + let mut until = skip_ws(b, end + 1); + if b.get(until) == Some(&b'{') { + until = matching(b, until).unwrap_or(to).min(to); + } else { + while until < to && !matches!(b[until], b',' | b';' | b')' | b']' | b'}') { + until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 }; + } + } + // Each parameter binds the names before its type. + let params = String::from_utf8_lossy(&b[at + 1..end]).into_owned(); + let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); + shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); + } + // A field access (`options.c`) or a field label (`Row { c: x }`) names a field, not the binding. + let is_field = |at: usize, len: usize| { + b[..at].trim_ascii_end().last() == Some(&b'.') || { + let next = skip_ws(b, at + len); + b.get(next) == Some(&b':') && b.get(next + 1) != Some(&b':') + } + }; + let live = |f: usize, t: usize, names: &[(String, usize, usize)], shadows: &[(String, usize, usize)]| { + names.iter().any(|(n, since, until)| { + words(b, n.as_bytes(), f.max(*since), t.min(*until)) + .into_iter() + .any(|at| !is_field(at, n.len()) && !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z)) + }) + }; + // Names bound inside the loop from the entry count as the entry. + for at in words(b, b"let", from, to) { + let Some(eq) = + (at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + else { + continue; + }; + let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); + let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); + if live(eq + 1, end, &derived, &shadows) { + // Rebinding from the entry suspends earlier shadows until this block ends. + let until = block_close(b, at).min(to); + let mut resumed = vec![]; + for s in shadows.iter_mut().filter(|s| names.contains(&s.0) && s.1 <= at && at < s.2) { + if until < s.2 { + resumed.push((s.0.clone(), until, s.2)); + } + s.2 = end; + } + shadows.extend(resumed); + derived.extend(names.into_iter().map(|n| (n, end, until))); + } else { + let until = block_close(b, at).min(to); + shadows.extend(names.into_iter().filter(|n| derived.iter().any(|(d, _, _)| d == n)).map(|n| (n, end, until))); + } + } + let reads = |f: usize, t: usize| live(f, t, &derived, &shadows); + let literal = |s: &[u8]| { + let s = norm(s); + let s = s.trim_start_matches(['&', '*']); + // String, byte and raw literals keep their prefix after masking (`r"…"`, `b'…'`, `br#"…"#`). + let s = match s.find(['"', '\'']) { + Some(q) if q <= 3 && s[..q].bytes().all(|c| matches!(c, b'b' | b'c' | b'r' | b'#')) => &s[q..], + _ => s, + }; + // A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input. + // A minus sign makes a literal only in front of a number (`-2`, not `-offset`). + let s = s.strip_prefix('-').unwrap_or(s); + let mut start = 0; + let mut operands = 0; + let mut numeric = true; + for (i, c) in s.char_indices().chain([(s.len(), '+')]) { + if !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { + continue; + } + let head = &s[start..i]; + if i < s.len() + && matches!(c, '+' | '-') + && head + .strip_suffix(['e', 'E']) + .is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.bytes().all(|c| c.is_ascii_digit() || matches!(c, b'_' | b'.'))) + { + continue; + } + if !head.is_empty() { + operands += 1; + numeric &= numeric_literal(head); + } + start = i + c.len_utf8(); + } + let numeric = numeric && operands > 0; + s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None") + }; + (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { + let mut start = name_end; + while start > from && is_ident(b[start - 1]) { + start -= 1; + } + let name = String::from_utf8_lossy(&b[start..name_end]); + if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) { + return false; + } + let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; + let args = split_args(b, open + 1, close); + let mut inputs = args.clone(); + if start > from && b[start - 1] == b'.' { + // The receiver: the chain of names, calls and indexing before the dot. + let mut r = start - 1; + while r > from { + match b[r - 1] { + c if is_ident(c) || c == b'.' => r -= 1, + // A chain rustfmt splits over lines continues with a `.` after the line break. + c if c.is_ascii_whitespace() && b[r..start].iter().find(|c| !c.is_ascii_whitespace()) == Some(&b'.') => r -= 1, + b')' | b']' => match (from..r - 1).rev().find(|&o| matching(b, o) == Some(r - 1)) { + Some(o) => r = o, + None => break, + }, + _ => break, + } + } + inputs.push((r, start - 1)); + } + let fed = inputs.iter().any(|&(f, t)| reads(f, t)); + // A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only + // another argument (`u.parse(&text)`) makes it a computation. + let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs }; + let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(f, t)); + fed && other + }) +} + +/// Whether the whitespace-free `s` is one numeric literal (`1`, `0x1F`, `2.5f32`, `1_000`, `1e-3`), not +/// an expression that starts with one (`1+offset`, `1..limit`). +fn numeric_literal(s: &str) -> bool { + let b = s.as_bytes(); + let radix = match b.get(..2) { + Some(b"0x") => 16, + Some(b"0o") => 8, + Some(b"0b") => 2, + _ => 10, + }; + let mut i = if radix == 10 { 0 } else { 2 }; + let mut digits = 0; + while let Some(&c) = b.get(i) { + if (c as char).is_digit(radix) { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 || !b.first().is_some_and(u8::is_ascii_digit) { + return false; + } + if radix == 10 { + if b.get(i) == Some(&b'.') { + i += 1; + if i < b.len() && !b[i].is_ascii_digit() { + return false; + } + while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'_') { + i += 1; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + let mut digits = 0; + while let Some(&c) = b.get(i) { + if c.is_ascii_digit() { + digits += 1; + } else if c != b'_' { + break; + } + i += 1; + } + if digits == 0 { + return false; + } + } + } + matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") +} + +/// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the +/// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. +fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { + let before = open; + if before > from && is_ident(b[before - 1]) { + return Some(before); + } + if before == from || b[before - 1] != b'>' { + return None; + } + let mut depth = 0usize; + for i in (from..before).rev() { + match b[i] { + b'>' if i == 0 || b[i - 1] != b'-' => depth += 1, + b'<' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + let head = b[from..i].trim_ascii_end(); + let end = head.strip_suffix(b"::")?.trim_ascii_end().len(); + return (end > 0 && is_ident(b[from + end - 1])).then_some(from + end); + } + } + b';' | b'{' | b'}' => return None, + _ => {} + } + } + None +} + +/// Whether a call starting at `start` in the loop body `b[from..to]` runs whenever the loop's +/// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`, +/// also with a block as the right operand); the right side of `&&` has to run only in an asserted +/// condition. A call inside a closure bound with `let` runs only when the loop calls +/// that closure. +fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { + runs_with_assertion_within(b, from, to, start, &[]) +} + +/// [`runs_with_assertion`], where `active` holds the calls whose check is in progress, so a closure +/// that calls itself does not recurse without end. +fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { + if active.contains(&start) { + return false; + } + let mut active = active.to_vec(); + active.push(start); + if in_uncalled_closure(b, from, to, start, &active) { + return false; + } + // Check enclosing blocks independently of the call's statement: an earlier semicolon inside + // a conditional block does not make its later statements run unconditionally. + for open in (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) { + let mut head = open; + while head > from { + head -= 1; + match b[head] { + b')' | b']' => { + let Some(back) = (from..head).rev().find(|&i| matching(b, i) == Some(head)) else { return false }; + head = back; + } + b';' | b'{' | b'}' => { + head += 1; + break; + } + _ => {} + } + } + let prefix = b[head..open].trim_ascii(); + if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { + if !runs_with_assertion_within(b, from, to, open, &active) { + return false; + } + } else if !prefix.ends_with(b"|") + && !(prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace)) + && (prefix.ends_with(b"=>") + || [b"async".as_slice(), b"async move"] + .iter() + .any(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) + || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) + || (!words(prefix, b"loop", 0, prefix.len()).is_empty() + && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) + { + // A nested `for` body is taken to run, like the loop body itself; [`feeds_entry`] keeps + // its own bindings apart. + return false; + } + } + // The statement starts after a `;` or an unmatched brace, except for the `{` of a block that is + // the operand of `||` or `&&`. + let mut stmt = from; + let mut braces = 0usize; + for i in (from..start).rev() { + match b[i] { + // A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`) + // unless an operator joins the call's expression to it. + b'}' if braces == 0 && { + let after = b[i + 1..start].trim_ascii_start(); + !(after.starts_with(b"||") || after.starts_with(b"&&") || after.starts_with(b".") || after.starts_with(b"?")) + } => + { + stmt = i + 1; + break; + } + b'}' => braces += 1, + b'{' if braces > 0 => braces -= 1, + b'{' => { + let before = b[from..i].trim_ascii_end(); + if !(before.ends_with(b"||") || before.ends_with(b"&&")) { + stmt = i + 1; + break; + } + } + b';' if braces == 0 => { + stmt = i + 1; + break; + } + _ => {} + } + } + // Only an operator at the call's own nesting level or an enclosing one counts, not one inside + // an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand; + // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. + // Earlier sibling elements cannot skip the call, but guards around their group still can. + let mut depth = 0usize; + let params = (stmt..start).find_map(|pipe| { + if b[pipe] != b'|' { + return None; + } + let head = b[stmt..pipe].trim_ascii(); + let head = head.strip_suffix(b"move").or_else(|| head.strip_suffix(b"async")).unwrap_or(head).trim_ascii_end(); + if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { + return None; + } + (pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end)) + }); + let mut closure = params.map(|(pipe, _)| pipe); + let mut sibling = false; + for i in (stmt + 1..start).rev() { + if params.is_some_and(|(pipe, end)| pipe <= i && i <= end) { + continue; + } + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => sibling = false, + b'(' | b'[' | b'{' => depth -= 1, + _ => {} + } + if depth != 0 { + continue; + } + if b[i] == b',' { + sibling = true; + } + if sibling { + continue; + } + if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') { + break; + } + if b[i] == b'&' + && b[i - 1] == b'&' + && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + && !asserted_conjunction(b, from, to, i - 1) + { + return false; + } + if b[i] == b'|' && b[i - 1] == b'|' { + let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1); + let prefix = &b[stmt..end]; + let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5])); + let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6])); + if !moved + && !asynchronous + && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + { + return false; + } + closure = Some(stmt + prefix.len()); + } + } + // `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`. + let Some(end) = closure else { return true }; + let head = String::from_utf8_lossy(&b[stmt..end]); + let head = head.trim(); + let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true }; + let Some(name) = pattern_names(binding).last() else { return true }; + words(b, name.as_bytes(), end, to).into_iter().any(|at| { + // `other.run()` calls a method, not the closure. + b[..at].trim_ascii_end().last() != Some(&b'.') + && b.get(skip_ws(b, at + name.len())) == Some(&b'(') + && runs_with_assertion_within(b, from, to, at, &active) + }) +} + +/// Whether an `&&` is at the top level of an assertion's first argument. +fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool { + macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| { + let Some(&(mut f, mut t)) = a.args.first() else { return false }; + loop { + f += b[f..t].len() - b[f..t].trim_ascii_start().len(); + t = f + b[f..t].trim_ascii_end().len(); + if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) { + break; + } + f += 1; + t -= 1; + } + // A top-level `||` lets the assertion pass without the conjunction. + let cond = String::from_utf8_lossy(&b[f..t]); + f <= at && at < t && top_level_at(&cond, "||").is_empty() && top_level_at(&cond, "&&").contains(&(at - f)) + }) +} + +/// Whether `start` lies in the block body of a closure bound with `let` in +/// `b[from..to]` (`let run = || { … };`, also `move` or `async`) that the loop never calls. +fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { + let mut depth = 0usize; + for i in (from..start).rev() { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' if depth > 0 => depth -= 1, + b'{' if depth > 0 => depth -= 1, + b'{' => { + let Some(params) = b[from..i].trim_ascii_end().strip_suffix(b"|") else { continue }; + let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; + let head = params[..pipe].trim_ascii_end(); + let head = String::from_utf8_lossy(head); + let head = head.trim_end(); + let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end(); + let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue }; + let Some(name) = pattern_names(binding).last() else { continue }; + let close = matching(b, i).unwrap_or(to); + if !words(b, name.as_bytes(), close, to).into_iter().any(|at| { + b[..at].trim_ascii_end().last() != Some(&b'.') + && b.get(skip_ws(b, at + name.len())) == Some(&b'(') + && runs_with_assertion_within(b, from, to, at, active) + }) { + return true; + } + } + _ => {} + } + } + false +} + /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions @@ -1881,8 +2399,8 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { /// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole /// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so /// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's -/// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is -/// not a round trip of the entry. +/// arguments (`Kind::from_id(k.id())`) or its receiver (`k.parse()`) must read the loop entry `var`; +/// a lookup of a fixed key is not a round trip of the entry. fn round_trip_call(op: &str, var: &str) -> bool { let mut op = op.trim_start_matches(['&', '*']); loop { @@ -1898,7 +2416,11 @@ fn round_trip_call(op: &str, var: &str) -> bool { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',', '&']) - && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) + && matching(op.as_bytes(), open).is_some_and(|close| { + // The entry is read in the arguments (`Kind::from_id(k.id())`) or is the receiver (`k.parse()`). + let receiver = op[..at].strip_suffix('.').is_some_and(|r| reads_ident(r, var)); + only_unwraps(&op[close + 1..]) && (receiver || reads_ident(&op[open + 1..close], var)) + }) }) }) } @@ -7307,4 +7829,269 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn census_follows_the_calls_that_run_for_each_entry() { + let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| census_in(&loop_of(body)); + assert_eq!(census("assert!(menu(c).is_some() || verify_fallback(c).is_ok());"), [(2, "census")], "a helper after || can be skipped"); + assert_eq!(census("assert!(menu(c).is_some() && verify_fallback(c).is_ok());"), [], "a helper after && runs"); + assert_eq!(census("assert!(menu(c).is_some()); { let c = fallback(); app.run(c); }"), [(2, "census")], "a shadowed entry name"); + assert_eq!(census("assert!(menu(c).is_some()); app.run(c);"), [], "the entry itself"); + assert_eq!(census("let _run = || app.run(c); assert!(menu(c).is_some());"), [(2, "census")], "a closure that is never called"); + assert_eq!( + census("let _run = || { let r = app.run(c); r }; assert!(menu(c).is_some());"), + [(2, "census")], + "a block closure that is never called" + ); + assert_eq!(census("let run = || { let r = app.run(c); r }; assert!(run().is_ok());"), [], "a block closure the loop calls"); + assert_eq!( + census("let params = fallback(); app.run(params); let params = c; assert!(menu(c).is_some());"), + [(2, "census")], + "a binding from the entry does not reach back to an earlier use of its name" + ); + assert_eq!( + census("{ let params = c; } app.run(params); assert!(menu(c).is_some());"), + [(2, "census")], + "a binding from the entry ends with its block" + ); + assert_eq!(census("app.run(options.c); assert!(menu(c).is_some());"), [(2, "census")], "a field with the entry's name"); + assert_eq!(census("assert!(app.run::(c).is_ok());"), [], "a call with a turbofish"); + assert_eq!(census("assert!(menu::(c).is_some());"), [(2, "census")], "an entry-only call with a turbofish"); + assert_eq!(census("assert!(render(c, -offset).is_ok());"), [], "a negated variable is another input"); + assert_eq!(census("assert!(render(c, -2).is_ok());"), [(2, "census")], "a negative literal is not"); + assert_eq!( + census("let _ = menu(c).is_some() || { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a block on the right of || can be skipped" + ); + assert_eq!( + census("let _ = menu(c).is_some() || { foo(); app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a semicolon keeps the enclosing ||" + ); + assert_eq!(census("assert!(menu(c).is_some() && { foo(); app.run(c).is_ok() });"), [], "a semicolon keeps the enclosing &&"); + assert_eq!( + census("let _ = (menu(c).is_some() || other(c).is_some()) && { app.run(c).is_ok() }; assert!(menu(c).is_some());"), + [(2, "census")], + "a discarded conjunction can skip the block when its left side is false" + ); + assert_eq!(census("assert!(menu(c).is_some()); if first || second {} app.run(c);"), [], "an || in a finished if does not skip the call"); + assert_eq!( + census("let entry = c; let c = fallback(); let c = entry; assert!(menu(c).is_some()); app.run(c);"), + [], + "a name rebound from the entry is the entry again" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; } assert!(menu(entry).is_some()); app.run(c);"), + [(2, "census")], + "an inner entry binding does not end the outer fallback binding" + ); + assert_eq!( + census("let entry = c; let c = fallback(); { let c = entry; app.run(c); } assert!(menu(entry).is_some());"), + [], + "the inner entry binding is live inside its block" + ); + assert_eq!( + census("let Row { c: other } = fallback(); assert!(menu(c).is_some()); app.run(c);"), + [], + "a field label does not rebind the entry" + ); + let receiver = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(k.parse(), k);\n }\n}\n"; + assert_eq!(census_in(receiver), [(2, "census")], "a round trip with the entry as receiver"); + let fixed = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(registry.lookup(\"baseline\"), k);\n }\n}\n"; + assert_eq!(census_in(fixed), [], "a lookup of a fixed key"); + } + + #[test] + fn census_follows_conditions_and_scopes_around_the_call() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _ = false && app.run(c).is_ok(); assert!(menu(c).is_some());"), + [(2, "census")], + "a discarded conjunction can skip the call" + ); + assert_eq!( + census("let ok = ready && app.run(c).is_ok(); assert!(menu(c).is_some());"), + [(2, "census")], + "a bound conjunction can skip the call" + ); + assert_eq!(census("debug_assert!(menu(c).is_some() && app.run(c).is_ok());"), [], "an asserted conjunction requires the call"); + assert_eq!( + census("assert!(other(c).is_some() && app.run(c).is_ok() || menu(c).is_some());"), + [(2, "census")], + "an || after the conjunction lets the assertion pass without it" + ); + assert_eq!(census("let _ = &&app.run(c); assert!(menu(c).is_some());"), [], "a double borrow does not short-circuit the call"); + assert_eq!( + census("let run = || app.run(c); assert!(menu(c).is_some() || run().is_ok());"), + [(2, "census")], + "a closure invocation after || can be skipped" + ); + assert_eq!( + census("let run = || { app.run(c) }; assert!(menu(c).is_some() || run().is_ok());"), + [(2, "census")], + "a block closure invocation after || can be skipped" + ); + assert_eq!(census("let run = || app.run(c); assert!(run().is_ok());"), [], "a closure invocation required by the assertion runs"); + assert_eq!( + census("let run = || app.run(c); other.run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a method of the same name does not call the closure" + ); + assert_eq!( + census("let run = || app.run(c).and(run()); assert!(menu(c).is_some());"), + [(2, "census")], + "a recursive closure does not establish that its body runs" + ); + assert_eq!(census("if false { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an if can skip the call"); + assert_eq!(census("if flag {} else { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an else can skip the call"); + assert_eq!( + census("match flag { true => { app.run(c); }, false => {} } assert!(menu(c).is_some());"), + [(2, "census")], + "a match arm can skip the call" + ); + assert_eq!(census("while flag { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a while can skip the call"); + assert_eq!(census("let entry = c; { let c = entry; app.run(c); } assert!(menu(c).is_some());"), [], "a plain block runs"); + assert_eq!(census("for c in defaults() { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a nested loop shadows the entry"); + assert_eq!(census("for c in app.defaults(c) { app.run(c); } assert!(menu(c).is_some());"), [], "the loop source reads the outer entry"); + assert_eq!( + census("for c in defaults() { let params = c; app.run(params); } assert!(menu(c).is_some());"), + [(2, "census")], + "a nested binding stays shadowed through aliases" + ); + assert_eq!(census("for c in defaults() {} app.run(c); assert!(menu(c).is_some());"), [], "the nested loop's shadow ends with its body"); + assert_eq!(census("for x in 0..3 { app.run(c, x); } assert!(menu(c).is_some());"), [], "a nested loop body runs the call"); + assert_eq!( + census("let run = |c| app.run(c); run(default()); assert!(menu(c).is_some());"), + [(2, "census")], + "a closure parameter shadows the entry" + ); + assert_eq!( + census("let run = |other| app.run(c); run(default()); assert!(menu(c).is_some());"), + [], + "another closure parameter keeps the entry" + ); + assert_eq!( + census("let run = |c| { app.run(c); }; run(default()); assert!(menu(c).is_some());"), + [(2, "census")], + "a block closure parameter shadows the entry" + ); + assert_eq!( + census("let run = |other| { app.run(c); }; run(default()); assert!(menu(c).is_some());"), + [], + "a called block closure keeps its capture" + ); + } + + #[test] + fn census_follows_block_initializers_argument_guards_and_parameterized_closures() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("let result = { verify(c) }; assert!(result.is_ok());"), [], "a block initializer runs its helper"); + assert_eq!( + census("let _future = async { app.run(c); }; assert!(menu(c).is_some());"), + [(2, "census")], + "an unpolled async block does not run its body" + ); + assert_eq!( + census("let result = if ready { verify(c) } else { Ok(()) }; assert!(result.is_ok());"), + [(2, "census")], + "a conditional initializer can skip its helper" + ); + assert_eq!( + census("let _ = false && accept(0, app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an enclosing conjunction survives argument commas" + ); + assert_eq!(census("let _ = accept(flag || other, app.run(c)); assert!(menu(c).is_some());"), [], "a sibling argument cannot skip the call"); + assert_eq!( + census("let _ = ready || accept(0, app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an enclosing disjunction survives argument commas" + ); + assert_eq!( + census("let _ = ready && accept((flag || other, 0), app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a nested sibling keeps the enclosing guard" + ); + assert_eq!(census("assert!(ready && accept(0, app.run(c)));"), [], "an asserted enclosing conjunction requires the argument"); + assert_eq!(census("let _ = accept(0, { app.run(c) }); assert!(menu(c).is_some());"), [], "an argument block runs"); + assert_eq!( + census("let _run = |_: ()| app.run(c); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled typed closure can skip its body" + ); + assert_eq!(census("let run = |_: ()| app.run(c); assert!(run(()).is_ok());"), [], "an asserted typed closure invocation runs its body"); + assert_eq!( + census("let run = move |x| app.run(c, x); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled move closure can skip its body" + ); + assert_eq!(census("let run = move |x| app.run(c, x); assert!(run(0).is_ok());"), [], "an asserted move closure invocation runs its body"); + assert_eq!( + census("let run = |_: ()| app.run(c); assert!(menu(c).is_some() || run(()).is_ok());"), + [(2, "census")], + "a guarded typed closure invocation can skip its body" + ); + assert_eq!( + census("let run = |c: Command| app.run(c); run(default()); assert!(menu(c).is_some());"), + [(2, "census")], + "a typed closure parameter shadows the entry" + ); + } + + #[test] + fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let run = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app.session.execute(CMD, &json!({\"way\": k})).is_ok());\n }\n}\n"; + assert_eq!(census(run), [], "a command run for each entry"); + let split = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app\n .run(k)\n .is_ok());\n }\n}\n"; + assert_eq!(census(split), [], "a chain split over lines keeps its receiver"); + let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n"; + assert_eq!(census(rendered), [], "a file written for each entry"); + let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(check_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; + assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema"); + let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n"; + assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census"); + let alone = "#[test]\nfn t() {\n for c in COMMANDS {\n let m = menu(c);\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(alone), [(2, "census")], "a call on the entry alone is a lookup"); + let constant = + "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c, 2, \"x\", r\"y\", b'z', br#\"w\"#).is_some());\n }\n}\n"; + assert_eq!(census(constant), [(2, "census")], "literal arguments are not other inputs"); + let message = "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some(), \"{}\", app.describe(c));\n }\n}\n"; + assert_eq!(census(message), [(2, "census")], "a call in a failure message runs only after a failure"); + let closure = "#[test]\nfn t() {\n let tree = tree();\n for p in PLACES {\n let m = tree.iter().find(|t| t == p).map(|(_, items)| items.len());\n assert!(m.is_some());\n }\n}\n"; + assert_eq!(census(closure), [(2, "census")], "a closure passed along a lookup is not another input"); + let registry = "#[test]\nfn t() {\n let registry = registry();\n for k in Kind::ALL {\n assert_eq!(registry.lookup(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip"); + let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n"; + assert_eq!(census(parsed), [], "parsing other input with each entry computes a result"); + let skipped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() || app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(skipped), [(2, "census")], "a call after || may never run"); + let joined = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(joined), [], "a call after && runs whenever the assertion passes"); + let grouped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!((menu(c).is_some() || other(c).is_some()) && app.run(c).is_ok());\n }\n}\n"; + assert_eq!(census(grouped), [], "an || inside an earlier group does not skip the call"); + let deferred = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(deferred), [], "a zero-argument closure feeds the entry into a computation"); + let moved = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = move || app.run(c);\n assert!(run().is_ok());\n }\n}\n"; + assert_eq!(census(moved), [], "a move closure feeds the entry into a computation"); + let deferred_async = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = async || app.run(c);\n assert!(block_on(run()).is_ok());\n }\n}\n"; + assert_eq!(census(deferred_async), [], "an async closure feeds the entry into a computation"); + let sibling = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let result = (flag || other, app.run(c));\n assert!(result.1.is_ok());\n }\n}\n"; + assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); + } + + #[test] + fn numeric_literals_are_one_token() { + for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] { + assert!(numeric_literal(s), "{s}"); + } + for s in ["1+offset", "1..limit", "1usize-offset", "1<<4"] { + assert!(!numeric_literal(s), "{s}"); + } + } } From 1eb22f6134f32fc217d0dcfb6dae9f6683838612 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 03:01:11 -0800 Subject: [PATCH 6/8] xtask: test-lint census entry reads skip path segments, comment gaps and block statements - An entry name after `::` (`defaults::c`) is a path segment, not a read of the loop binding. - A `let` initializer scans to the end of its statement, so a block initializer binds its tail (`{ prepare(); c }`) and not the earlier statements in the block; `if let` and `while let` end at their block. - A call keeps its name when masked comment whitespace sits before `(`, except after a keyword (`if (a)`). - The argument-guard and alias tests now depend on the logic they cover. --- xtask/src/test_lint.rs | 66 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 8 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 4c39f6ad13..f25a31ecf1 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1764,9 +1764,10 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); } - // A field access (`options.c`) or a field label (`Row { c: x }`) names a field, not the binding. + // A field access (`options.c`), a path segment (`defaults::c`) or a field label (`Row { c: x }`) + // names a field or an item, not the binding. let is_field = |at: usize, len: usize| { - b[..at].trim_ascii_end().last() == Some(&b'.') || { + b[..at].trim_ascii_end().last() == Some(&b'.') || b[..at].trim_ascii_end().ends_with(b"::") || { let next = skip_ws(b, at + len); b.get(next) == Some(&b':') && b.get(next + 1) != Some(&b':') } @@ -1785,9 +1786,27 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { else { continue; }; - let end = (eq..to).find(|&i| b[i] == b';').unwrap_or(to); + // `if let` and `while let` end their initializer at the conditional's block. + let conditional = [b"if".as_slice(), b"while"].iter().any(|kw| b[from..at].trim_ascii_end().ends_with(kw)); + let end = if conditional { (eq..to).find(|&i| b[i] == b'{').unwrap_or(to) } else { statement_end(&b[..to], eq) }; + // A block initializer binds the value of its tail (`{ prepare(); c }`). + let mut value = eq + 1; + let init = skip_ws(b, value); + if !conditional && b.get(init) == Some(&b'{') && matching(b, init).is_some_and(|close| b[close + 1..end].trim_ascii().is_empty()) { + let close = matching(b, init).unwrap_or(end); + let mut i = init + 1; + value = i; + while i < close { + match b[i] { + b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close), + b';' => value = i + 1, + _ => {} + } + i += 1; + } + } let names: Vec = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect(); - if live(eq + 1, end, &derived, &shadows) { + if live(value, end, &derived, &shadows) { // Rebinding from the entry suspends earlier shadows until this block ends. let until = block_close(b, at).min(to); let mut resumed = vec![]; @@ -1937,9 +1956,18 @@ fn numeric_literal(s: &str) -> bool { /// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the /// `::<…>` of a turbofish (`app.run::(c)`). `None` when no name precedes the `(`. fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { - let before = open; + // Masked comments leave spaces between the name and the `(` (`app.run /* note */ (c)`). + let before = from + b[from..open].trim_ascii_end().len(); if before > from && is_ident(b[before - 1]) { - return Some(before); + // A keyword before a parenthesized expression (`if (a)`, `return (x)`) is not a call. + let mut start = before; + while start > from && is_ident(b[start - 1]) { + start -= 1; + } + const KEYWORDS: [&[u8]; 15] = + [b"if", b"else", b"match", b"while", b"for", b"in", b"return", b"break", b"let", b"mut", b"move", b"async", b"await", b"as", b"loop"]; + let keyword = KEYWORDS.contains(&&b[start..before]); + return (before == open || !keyword).then_some(before); } if before == from || b[before - 1] != b'>' { return None; @@ -8592,7 +8620,11 @@ mod tests { [(2, "census")], "a nested sibling keeps the enclosing guard" ); - assert_eq!(census("assert!(ready && accept(0, app.run(c)));"), [], "an asserted enclosing conjunction requires the argument"); + assert_eq!( + census("assert!(menu(c).is_some() && accept(0, app.run(c)).is_some());"), + [], + "an asserted enclosing conjunction requires the argument" + ); assert_eq!(census("let _ = accept(0, { app.run(c) }); assert!(menu(c).is_some());"), [], "an argument block runs"); assert_eq!( census("let _run = |_: ()| app.run(c); assert!(menu(c).is_some());"), @@ -8616,6 +8648,24 @@ mod tests { [(2, "census")], "a typed closure parameter shadows the entry" ); + assert_eq!( + census("app.run(defaults::c); assert!(menu(c).is_some());"), + [(2, "census")], + "a path segment named like the entry does not read it" + ); + assert_eq!(census("app.run(c); assert!(menu(c).is_some());"), [], "a plain argument reads the entry"); + assert_eq!(census("let input = { prepare(); c }; assert!(render(input, offset).is_ok());"), [], "a block initializer's tail binds the entry"); + assert_eq!(census("assert!(app.run /* note */ (c).is_ok());"), [], "a comment before the arguments keeps the call"); + assert_eq!( + census("let input = { prepare(); let _ = c; fixed }; assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"), + [(2, "census")], + "a block initializer binds its tail, not earlier statements" + ); + assert_eq!( + census("if let Some(input) = fallback() { prepare(); } menu(c); assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"), + [(2, "census")], + "an if let initializer ends at its block" + ); } #[test] @@ -8627,7 +8677,7 @@ mod tests { assert_eq!(census(split), [], "a chain split over lines keeps its receiver"); let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n"; assert_eq!(census(rendered), [], "a file written for each entry"); - let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(check_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; + let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(validate_params(SCHEMA, ¶ms).is_ok());\n }\n}\n"; assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema"); let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n"; assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census"); From cf51c8894cef9d5329e36f1be2f6ec948979fcd6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:55:33 -0800 Subject: [PATCH 7/8] xtask: test-lint decodes string continuations in cfg_attr paths and keeps census hits for fixed ranges A path string that continues on the next line with a backslash now decodes to the joined file name, so the conditional route is kept. A range argument with two fixed bounds (1..4, 1..=4) no longer counts as an input, so the round-trip census diagnostic stays; a range with a variable bound still suppresses it. Adds a test for a bracket in a cfg_attr path filename keeping its sibling cfg gate. --- xtask/src/test_lint.rs | 46 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 53f367f0e4..44d73697e2 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1851,7 +1851,8 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let mut operands = 0; let mut numeric = true; for (i, c) in s.char_indices().chain([(s.len(), '+')]) { - if !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { + let range = c == '.' && (s.as_bytes().get(i + 1) == Some(&b'.') || s[..i].ends_with('.')) || c == '=' && s[..i].ends_with(".."); + if !range && !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') { continue; } let head = &s[start..i]; @@ -5067,6 +5068,9 @@ fn unescape(s: &str) -> String { continue; } match chars.next() { + Some(c @ ('\n' | '\r')) if c == '\n' || chars.peek() == Some(&'\n') => { + while chars.next_if(|c| matches!(c, ' ' | '\t' | '\n' | '\r')).is_some() {} + } Some('n') => out.push('\n'), Some('t') => out.push('\t'), Some('r') => out.push('\r'), @@ -5579,7 +5583,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, } let open = skip_ws(m, at + "cfg_attr".len()); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let text = pred_text(&src[open + 1..close]); + let text = norm_outside_literals(&mask_parts(&String::from_utf8_lossy(&src[open + 1..close]), true, false)); let cuts = attr_commas(&text); let Some(&first) = cuts.first() else { continue }; let mut start = first + 1; @@ -8618,6 +8622,30 @@ mod tests { assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]); } + #[test] + fn conditional_paths_decode_string_continuations() { + for newline in ["\n", "\r\n"] { + let src = format!("#[cfg_attr(unix, path = \"chi\\{newline} \t\r\n ld.rs\")]\nmod c;\n"); + assert_eq!(cfg_attr_paths(&mask(&src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child.rs".to_owned())]); + } + let src = "#[cfg_attr(unix, path = \"child file.rs\")]\nmod c;\n"; + assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child file.rs".to_owned())]); + let raw = "#[cfg_attr(unix, path = r\"chi\\\n ld.rs\")]\nmod c;\n"; + assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "chi\\\n ld.rs".to_owned())]); + } + + #[test] + fn conditional_paths_keep_sibling_cfg_gates_with_brackets_in_filenames() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"mac[.rs\", cfg(target_os = \"macos\"))]\nmod platform;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/mac[.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]); + } + #[test] fn path_attributes_accept_raw_strings() { for src in ["#[path = r\"shared.rs\"]\nmod s;\n", "#[path = r#\"shared.rs\"#]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n"] { @@ -8951,6 +8979,20 @@ mod tests { assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } + #[test] + fn census_keeps_diagnostics_for_fixed_range_arguments() { + for range in ["1..4", "1..=4", "-4..-1", "1..(2 + 2)"] { + let src = + format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n"); + assert_eq!(only("census", &src), [(2, "census")], "{range}"); + } + for range in ["1..limit", "1..=limit", "start..4", "1..(limit + 2)"] { + let src = + format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n"); + assert_eq!(only("census", &src), [], "{range}"); + } + } + #[test] fn numeric_literals_are_one_token() { for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] { From fffcca5cd2c9f422b75b9f67458bbe58c917a948 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:20:29 -0800 Subject: [PATCH 8/8] CI: build paths without parent-step literals the read check counts as reads The shared gate's undeclared-read check (select legs) reports two reads on main: crates/text/build.rs reads the workspace root (`.`) and crates/engine/src/tests/fontfiles.rs reads `crates`. Neither path names another member's files. - crates/text/build.rs takes the workspace root as the second ancestor of the crate directory instead of joining "../..". A relative CRAFT_FONTS_DIR still resolves from the same directory. - the_fonts_folder_next_to_a_document_is_an_absolute_path builds its climb to the filesystem root from ParentDir components instead of formatting a repeated "../". The test still opens the document by a relative path to its temporary folder. The check reports 0 problems on the result, down from 2 on main. --- crates/engine/src/tests/fontfiles.rs | 4 ++-- crates/text/build.rs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index e90aec1df9..fc8d72ead2 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -143,8 +143,8 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { let (_dir, root) = folder("relative"); std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap(); let cwd = std::env::current_dir().unwrap(); - let up = "../".repeat(cwd.components().count().saturating_sub(1)); - let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display()); + let up: PathBuf = cwd.components().skip(1).map(|_| std::path::Component::ParentDir).collect(); + let relative = up.join(root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap()).display().to_string(); assert!(Path::new(&relative).is_relative()); let mut s = session_for(&root); let mut doc = vectorcraft_doc::Document::new(100.0, 100.0); diff --git a/crates/text/build.rs b/crates/text/build.rs index 7863efe464..99eb1587f3 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -103,7 +103,8 @@ fn from_workspace(dir: PathBuf) -> PathBuf { return dir; } let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); - crate_dir.join("../..").join(dir) + // The workspace root is two levels above `crates/text`. + crate_dir.ancestors().nth(2).unwrap_or(&crate_dir).join(dir) } /// The one craft-fonts face web builds embed (family, style).