From 010367e39efd0b05b9b425b00b9e13629657f02c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:46:09 -0800 Subject: [PATCH 01/10] Tests: allow the 26 Windows and macOS tests that CI never runs Each test that a cfg limits to Windows, macOS or a case-insensitive file system gets a `test-lint: allow never-run` line naming its platform, so `cargo xtask test-lint` no longer reports them. The tests are unchanged and still run on their own platform. --- apps/vectorcraft-cli/src/perf.rs | 2 ++ apps/vectorcraft/src/mac_color_space.rs | 3 +++ apps/vectorcraft/src/mac_fonts.rs | 2 ++ apps/vectorcraft/src/open_documents.rs | 1 + crates/color/src/cms/tests.rs | 1 + crates/engine/src/file_access.rs | 2 ++ crates/engine/src/tests/fontfiles.rs | 1 + crates/engine/src/tests/link_paths.rs | 3 +++ crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_io.rs | 3 +++ crates/engine/src/tests/store.rs | 1 + crates/pdf/tests/gradient_forms.rs | 3 +++ crates/text/src/tests/sysfonts.rs | 3 +++ 13 files changed, 26 insertions(+) diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index e533d00b73..47686f6c2f 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -629,6 +629,7 @@ mod tests { /// On Windows `busy_cores` gives a number between 0 and the cores. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_how_many_cores_are_busy() { let cores = std::thread::available_parallelism().map_or(1, |c| c.get()); @@ -639,6 +640,7 @@ mod tests { /// On Windows `rss_mb` gives this process's working set: more than 0 MB and less than /// 10,000 MB. #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_reads_the_working_set() { let mb = rss_mb().map(|(mb, _)| mb); diff --git a/apps/vectorcraft/src/mac_color_space.rs b/apps/vectorcraft/src/mac_color_space.rs index 3fa1394804..ccdb340ec2 100644 --- a/apps/vectorcraft/src/mac_color_space.rs +++ b/apps/vectorcraft/src/mac_color_space.rs @@ -99,6 +99,7 @@ mod tests { } /// A layer without a color space is tagged sRGB once; the second call leaves it as it is. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn an_untagged_layer_becomes_srgb() { let layer = CAMetalLayer::new(); @@ -110,6 +111,7 @@ mod tests { } /// A layer with a color space of its own keeps it. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_layer_with_a_color_space_keeps_it() { let layer = CAMetalLayer::new(); @@ -121,6 +123,7 @@ mod tests { /// The Metal layer is found as the view's layer or as one of its sublayers, and only Metal /// layers are returned. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn metal_layers_are_found_under_the_view_layer() { let metal = CAMetalLayer::new(); diff --git a/apps/vectorcraft/src/mac_fonts.rs b/apps/vectorcraft/src/mac_fonts.rs index 36223c559f..4e9f996d62 100644 --- a/apps/vectorcraft/src/mac_fonts.rs +++ b/apps/vectorcraft/src/mac_fonts.rs @@ -52,6 +52,7 @@ mod tests { use objc2_core_text::{CTFontManagerRegisterFontsForURL, CTFontManagerScope, CTFontManagerUnregisterFontsForURL}; /// CoreText lists the installed fonts, by their files' full paths. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn coretext_lists_the_installed_font_files() { let files = super::font_files(); @@ -61,6 +62,7 @@ mod tests { /// A font registered with CoreText from another folder, as apps and font managers register /// fonts, is listed while it is registered. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn fonts_registered_from_other_folders_are_listed() { let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap(); diff --git a/apps/vectorcraft/src/open_documents.rs b/apps/vectorcraft/src/open_documents.rs index 67f409b0e8..a126618ee0 100644 --- a/apps/vectorcraft/src/open_documents.rs +++ b/apps/vectorcraft/src/open_documents.rs @@ -94,6 +94,7 @@ mod tests { use super::*; /// Files queue until the UI takes them; URLs that aren't files are left out. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn opened_files_wait_for_the_ui() { let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.svg")).unwrap(); diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 761a121191..a6552029b2 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -323,6 +323,7 @@ fn bad_icc_rejected() { } #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn loads_system_cmyk_icc() { let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc"); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index ce6023fb4e..7daa75e0ae 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -1390,6 +1390,7 @@ mod tests { } #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_ignores_case_and_refuses_devices() { let (base, roots) = folders("case"); @@ -1471,6 +1472,7 @@ mod tests { } #[cfg(windows)] + // test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn windows_refuses_a_stream_inside_a_write_root() { let (base, roots) = folders("streams"); diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index 52a8ff08a3..e90aec1df9 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -417,6 +417,7 @@ fn a_search_skips_font_files_too_large_to_add() { /// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its /// resource fork, which only macOS keeps. A search finds it, and Add Fonts copies it with its fork. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn suitcase_fonts_are_found_and_copied_with_their_fork() { use vectorcraft_testkit::fonts::{renamed, suitcase_fork}; diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index e39cf66896..ebc2b5d1c6 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -189,6 +189,7 @@ fn a_path_on_a_mapped_drive_is_on_the_share_behind_it() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_a_mapped_drives_share_are_followed() { use crate::cmd::fileio::{document_path_with, share_of}; @@ -208,6 +209,7 @@ fn links_on_a_mapped_drives_share_are_followed() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_a_drive_mapped_to_another_share_are_not_followed() { use crate::cmd::fileio::{document_path_on, drive_share_of, share_of}; @@ -228,6 +230,7 @@ fn links_on_a_drive_mapped_to_another_share_are_not_followed() { } #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn links_on_the_documents_share_or_this_computer_are_followed() { use crate::cmd::fileio::{document_path_on, drive_share_of, share_of}; diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 836daf8b05..f2858aec25 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4110,6 +4110,7 @@ fn a_removal_deletes_only_folders_it_marked() { /// Windows keeps a file another program holds open without delete sharing, so the last grant can't /// be removed by deleting `grants.json`. #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { use std::os::windows::fs::OpenOptionsExt; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 1e2823aaa4..b5d7fe7ded 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1020,6 +1020,7 @@ fn script_file_alias_is_not_left_behind_a_folder_replaced_by_a_link() { /// Where a hidden file is not one whose name starts with a dot, setting `hidden` and `createAlias` /// set `error` and change nothing. #[cfg(not(unix))] +// test-lint: allow never-run Windows only (not Unix); CI runs tests on Linux and FreeBSD #[test] fn script_file_hidden_and_aliases_are_refused_off_unix() { let base = folder("hiddenoff"); @@ -1637,6 +1638,7 @@ fn script_file_rename_does_not_take_the_settings_folders_name() { /// Where case does not matter, a folder named in another case is still the folder that holds the /// settings folder, or the settings folder itself: it is not renamed or removed. #[cfg(any(windows, target_os = "macos"))] +// test-lint: allow never-run needs a case-insensitive file system (Windows, macOS); CI runs tests on Linux and FreeBSD #[test] fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() { let base = folder("moveupcase"); @@ -1660,6 +1662,7 @@ fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() /// Where case does not matter, a folder renamed under its name in another case still moves the open /// objects of the files in it: changes are written under the new name, not lost at the old one. #[cfg(any(windows, target_os = "macos"))] +// test-lint: allow never-run needs a case-insensitive file system (Windows, macOS); CI runs tests on Linux and FreeBSD #[test] fn script_file_rename_of_a_folder_named_in_another_case_moves_its_open_files() { let base = folder("renamecase"); diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index dfc603dc59..380126535f 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -79,6 +79,7 @@ fn file_names(dir: &std::path::Path) -> Vec { /// Windows does not allow replacing a read-only file or writing into it, so the write fails. #[cfg(windows)] +// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD #[test] fn a_rename_that_only_changes_case_and_cannot_be_written_keeps_the_old_file() { let root = fresh_dir("rename-case-fails"); diff --git a/crates/pdf/tests/gradient_forms.rs b/crates/pdf/tests/gradient_forms.rs index 7373ec8494..a904935fe5 100644 --- a/crates/pdf/tests/gradient_forms.rs +++ b/crates/pdf/tests/gradient_forms.rs @@ -159,6 +159,7 @@ mod quartz { } /// Quartz places RGB and CMYK radial centres, edges and masks with their translated art. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_off_centre_radials_in_transparency_and_layer_forms() { for mode in [ColorMode::Rgb, ColorMode::Cmyk] { @@ -179,6 +180,7 @@ mod quartz { } /// Quartz retains the linear ramp's direction inside forms on a translated artboard. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_linear_gradient_directions_in_forms() { for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Mask | Form::Knockout)) { @@ -190,6 +192,7 @@ mod quartz { } /// A gradient's stop-opacity mask remains aligned with its colour through nested forms. + // test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn quartz_keeps_gradient_stop_opacity_aligned_inside_nested_forms() { let (mut d, opts) = fixture(Form::Nested, GradientKind::Radial, ColorMode::Rgb, Point::ORIGIN); diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 261cc1c54c..32cb04c30c 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -805,6 +805,7 @@ fn a_resource_fork_gives_up_its_font_files() { /// Office's fonts: a file with nothing in it but a resource fork holding the fonts, named /// without an extension. Only macOS keeps a resource fork in a file. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn the_scan_reads_suitcase_fonts() { let dir = font_dir("suitcase"); @@ -1011,6 +1012,7 @@ fn a_search_reads_at_most_its_share_of_a_font_file() { /// A search reads a suitcase font only when its whole resource fork fits in the 8 MB a search reads /// of one file. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_search_reads_a_suitcase_font_only_within_its_share() { use crate::fontdb::file_face_names_within; @@ -1036,6 +1038,7 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { /// A suitcase font read for one search (Retype) is read no further than one byte past the limit, /// and the bytes read are counted. #[cfg(target_os = "macos")] +// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD #[test] fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); From e7715d880be808cce91626a1937c4c053ac776c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:21:01 -0800 Subject: [PATCH 02/10] xtask: test-lint round trips, mod scopes, never-run allows and doc names - census: a lookup counts as a round trip only when its arguments read the loop entry, so `lookup("baseline") == expected` is a real check. - never-run: a `mod child;` inside an inline `mod platform { ... }` loads platform/child.rs, so it no longer gives its cfg to src/child.rs. - never-run: an allow covers only the test it sits above; a module cfg no longer stretches it over the next test in the module. - exact-pixel: document geometry is matched by identifier (`doc`, `document`, `doc_*`, `*_doc`), so `dock_rect` is checked. --- xtask/src/test_lint.rs | 70 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 61 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index a5fc3e4bbc..9b1f2f2d14 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -240,6 +240,10 @@ pub struct Hit { /// only near `line`. pub first: usize, pub last: usize, + /// The first line an allow comment may sit on to exempt the hit, when it differs from `first`: + /// a `never-run` hit spans an enclosing module's `cfg`, but only an allow at the test's own + /// attributes exempts it. + pub allow_from: Option, } impl Hit { @@ -1183,7 +1187,7 @@ struct File<'a> { impl File<'_> { fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { let line = self.lines.of(at); - Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, allow_from: None } } fn test_at(&self, pos: usize) -> &str { @@ -1223,7 +1227,7 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { hits.extend(reads_source_hits(&file)); let allows = allows(src, &file.m); hits.retain(|h| { - let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.allow_from.unwrap_or(h.first) }; !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) }); hits.sort(); @@ -1612,7 +1616,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { 1 => args.first().is_some_and(|a| weak_predicate(a)), 2 if name.ends_with("_ne") => false, 2 => match args { - [a, b, ..] => (round_trip_call(a) && is_entry(b, var)) || (round_trip_call(b) && is_entry(a, var)), + [a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)), _ => false, }, _ => false, @@ -1621,8 +1625,10 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { /// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole /// name 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. -fn round_trip_call(op: &str) -> bool { +/// 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. +fn round_trip_call(op: &str, var: &str) -> bool { let mut op = op.trim_start_matches(['&', '*']); loop { let wraps = |w: &&str| op.starts_with(*w) && matching(op.as_bytes(), w.len() - 1) == Some(op.len() - 1); @@ -1636,11 +1642,21 @@ fn round_trip_call(op: &str) -> bool { op.match_indices(&format!("{r}(")).any(|(at, _)| { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) - && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) + && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) }) }) } +/// Whether `s` contains the identifier `var` as a whole word. +fn reads_ident(s: &str, var: &str) -> bool { + let b = s.as_bytes(); + !var.is_empty() + && s.match_indices(var).any(|(at, _)| { + let end = at + var.len(); + !(at > 0 && is_ident(b[at - 1])) && !b.get(end).copied().is_some_and(is_ident) + }) +} + /// Whether a (whitespace-free) call suffix only unwraps or copies the call's result. fn only_unwraps(mut rest: &str) -> bool { const UNWRAPS: &[&str] = &[".unwrap()", ".ok()", ".copied()", ".cloned()", ".clone()", ".as_ref()", ".as_deref()", "?"]; @@ -3283,7 +3299,7 @@ fn declared_cfgs(src: &str, name: &str) -> Option> { let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') + &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') && !in_inline_mod(&m, at) })?; let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let mut out = vec![]; @@ -3298,6 +3314,20 @@ fn declared_cfgs(src: &str, name: &str) -> Option> { Some(out) } +/// Whether `at` in the masked text `m` is inside an inline `mod { … }`, where a `mod x;` +/// loads a file under that module's directory instead of a sibling file. +fn in_inline_mod(m: &[u8], at: usize) -> bool { + m[..at].iter().enumerate().filter(|&(_, &c)| c == b'{').any(|(open, _)| { + if !matching(m, open).is_some_and(|close| close > at) { + return false; + } + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident) + }) +} + /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { @@ -3335,6 +3365,7 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { let shown: Vec = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); let mut hit = v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", "))); if let Some(at) = first_attr { + hit.allow_from = Some(hit.first); hit.first = hit.first.min(v.file.lines.of(at)); } return Some(hit); @@ -3363,7 +3394,11 @@ const RECT_PARTS: &[&str] = &[ /// [`RECT_PARTS`]. Document geometry (artboards, `x0`/`y0` corners, a document's nodes) and a rect /// passed on as an argument do not count. fn names_rect(op: &str) -> bool { - if ["artboard", "doc", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { + if ["artboard", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { + return false; + } + let document = |w: &str| w == "doc" || w == "document" || w.starts_with("doc_") || w.ends_with("_doc"); + if op.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(document) { return false; } let b = op.as_bytes(); @@ -3459,6 +3494,15 @@ mod tests { assert_eq!(hits(mixed), [(3, "all-unguarded")]); } + #[test] + fn census_round_trips_look_up_the_entry() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n"; + assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); + let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(derived), [(2, "census")]); + } + #[test] fn census_loops_over_whole_tables_are_reported() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -5041,7 +5085,11 @@ mod tests { let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; assert_eq!(declared_cfgs(inner, "child"), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; - assert_eq!(declared_cfgs(block, "child"), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfgs(block, "child"), None, "that `mod child;` loads platform/child.rs"); + let both = "#[cfg(windows)]\nmod platform {\n mod child;\n}\nmod child;\n"; + assert_eq!(declared_cfgs(both, "child"), Some(vec![]), "the root declaration, not the one in platform"); + let gated = "#[cfg(windows)]\nconst _: () = {\n mod child;\n};\n"; + assert_eq!(declared_cfgs(gated, "child"), Some(vec!["windows".to_owned()]), "a gated block that is not a module"); assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); } @@ -5052,6 +5100,9 @@ mod tests { let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line)); assert_eq!(hit, Some((1, 4))); assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let two = "#[cfg(target_os = \"macos\")]\nmod mac {\n // test-lint: allow never-run checks the macOS menu bar\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n"; + let left: Vec = lint_file("crates/x/src/tests.rs", two, &ctx()).iter().filter(|h| h.rule == Rule::NeverRun).map(|h| h.line).collect(); + assert_eq!(left, [9], "an allow above one test leaves the next one reported"); } #[test] @@ -5067,6 +5118,7 @@ mod tests { assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); assert_eq!(px("assert_eq!(doc.artboards[1].rect.width(), 100.0);"), [], "document geometry in a UI test"); + assert_eq!(px("assert_eq!(dock_rect.width(), 120.0);"), [(4, "exact-pixel")], "a name that only starts with doc"); assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; From 2c1278280b374bfad13d86c458633825668f42bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:55:37 -0800 Subject: [PATCH 03/10] xtask: test-lint cfg_attr, #[path] and inline-module gates, changed parent declarations - never-run reads cfg(...) nested in cfg_attr, and blanks comments in cfg predicates. - A file's inherited gates come from the mod declaration that loads it: #[path] overrides are resolved, and a declaration inside an inline module gates the file under that module's directory. Several declarations of one file join with any(...). - In changed-files mode, a change to a parent mod declaration or its cfg counts for the never-run hits of the files it loads, including files that did not change. - Round trips reject arithmetic before the lookup (1 + lookup(k)). - reads-source ignores Rust paths that occur only in comments. - if let and while let bindings shadow outer bindings only inside their body. - The mirror allow test now starts from an assertion that is reported. --- xtask/src/test_lint.rs | 394 ++++++++++++++++++++++++++++++++++------- 1 file changed, 327 insertions(+), 67 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 9b1f2f2d14..168dd8ff79 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -262,6 +262,15 @@ pub struct Ctx { pub module_cfgs: HashMap>, } +/// Whether a parent file's changed lines touch a `mod` declaration or `cfg` attribute that `gates` +/// came from. +fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap>>) -> bool { + gates + .into_iter() + .flat_map(|g| &g.sources) + .any(|(parent, lines)| changed.get(parent).is_some_and(|c| c.as_ref().is_none_or(|set| lines.iter().any(|l| set.contains(l))))) +} + /// 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); @@ -287,18 +296,36 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { 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(); - let module_cfgs = module_cfgs(&present, &|p| read_small(root, p)); + // 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 gated: Vec = present.iter().chain(&below).cloned().collect(); + let gates = module_gates(&gated, &|p| read_small(root, p)); + 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 }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { + let parent_changed = gate_changed(gates.get(&path), &changed); for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed) { counted.push(hit); } else { older += 1; } } } + for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + let Some(src) = read_small(root, path) else { continue }; + counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun)); + } finish(&counted, older, present.len(), &base) } @@ -1624,7 +1651,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { } /// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole -/// name and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so +/// 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. @@ -1642,6 +1669,7 @@ fn round_trip_call(op: &str, var: &str) -> bool { op.match_indices(&format!("{r}(")).any(|(at, _)| { 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)) }) }) @@ -2930,6 +2958,8 @@ fn reads_source_hits(file: &File) -> Vec { return vec![]; } let m = &file.m; + // The source with comments blanked and literals kept: a path in a comment is not read. + let code = mask_parts(&String::from_utf8_lossy(file.src), true, false); let mut out = vec![]; let words_and_notes = [ (&b"include_str"[..], "includes a .rs file as text"), @@ -2940,7 +2970,7 @@ fn reads_source_hits(file: &File) -> Vec { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { 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(&file.src[open + 1..close]); + let arg = norm(&code[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); @@ -3109,6 +3139,20 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option before || block_close(body, at) < before { continue; @@ -3130,6 +3174,22 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option<(usize, usize)> { + let mut depth = 0usize; + for (i, &c) in body.iter().enumerate().skip(from) { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth = depth.saturating_sub(1), + b'{' if depth == 0 => return matching(body, i).map(|close| (i, close)), + b';' | b'}' if depth == 0 => return None, + _ => {} + } + } + None +} + /// Where the innermost block holding `at` closes: its `}`, or the end of `body`. fn block_close(body: &[u8], at: usize) -> usize { let mut depth = 0usize; @@ -3240,23 +3300,67 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } -/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with -/// the offset of its attribute. `m` is the masked text of `src`. +/// A `cfg` attribute found by [`cfg_attrs`]. +struct CfgAttr { + pred: String, + /// The offset of the attribute's `cfg` or `cfg_attr`. + at: usize, + /// The offset of its closing `]`. + end: usize, + inner: bool, +} + +/// The `#[cfg(…)]`, `#![cfg(…)]` and `#[cfg_attr(, cfg(…))]` attributes in `m[from..to]`, +/// sorted by offset. A nested `cfg` becomes `any(not(),)`: it removes the item +/// only when the condition holds. `m` is the masked text of `src`. +fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + for (word, nested) in [(&b"cfg"[..], false), (&b"cfg_attr"[..], true)] { + for at in words(m, word, from, to) { + let before = m[..at].trim_ascii_end(); + let Some(hash) = before.strip_suffix(b"[").map(<[u8]>::trim_ascii_end) else { continue }; + let inner = hash.ends_with(b"#!"); + if !inner && !hash.ends_with(b"#") { + continue; + } + let open = skip_ws(m, at + word.len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') { + continue; + } + let text = pred_text(&src[open + 1..close]); + if !nested { + out.push(CfgAttr { pred: text, at, end, inner }); + continue; + } + let cuts = top_level_at(&text, ","); + let Some(&first) = cuts.first() else { continue }; + let cond = &text[..first]; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + if let Some(p) = text.get(start..cut).and_then(|p| p.strip_prefix("cfg(")).and_then(|p| p.strip_suffix(')')) { + out.push(CfgAttr { pred: format!("any(not({cond}),{p})"), at, end, inner }); + } + start = cut + 1; + } + } + } + out.sort_by_key(|a| a.at); + 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. +fn pred_text(src: &[u8]) -> String { + norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) +} + +/// 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)> { let mut out = vec![]; - for at in words(m, b"cfg", 0, m.len()) { - let before = m[..at].trim_ascii_end(); - let Some(hash) = before.strip_suffix(b"[").map(<[u8]>::trim_ascii_end) else { continue }; - let inner = hash.ends_with(b"#!"); - if !inner && !hash.ends_with(b"#") { - continue; - } - let open = skip_ws(m, at + "cfg".len()); - let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let end = skip_ws(m, close + 1); - if m.get(end) != Some(&b']') { - continue; - } + for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { // An inner attribute covers the file (or the module) it opens. let enclosing = m[..at].iter().rposition(|&c| c == b'{'); @@ -3270,8 +3374,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - // The source text: masking blanks the string literals `target_os = "macos"` needs. - out.push((norm(&src[open + 1..close]), at)); + out.push((pred, at)); } } out @@ -3292,58 +3395,168 @@ fn module_parent(path: &str) -> Option<(&str, Vec)> { Some((name, candidates)) } -/// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src` and on the -/// items and file around it, or `None` when `src` declares no such module. -fn declared_cfgs(src: &str, name: &str) -> Option> { - let m = mask(src); - let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { - let start = skip_ws(&m, at + 3); - let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') && !in_inline_mod(&m, at) - })?; - let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let mut out = vec![]; - for at in words(&m, b"cfg", item, decl) { - let open = skip_ws(&m, at + 3); - let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); - if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { - out.push(norm(&src.as_bytes()[open + 1..close])); - } - } - out.extend(cfgs_over(&m, src.as_bytes(), decl).into_iter().map(|(p, _)| p)); - Some(out) +/// Where a module file is loaded from: the file `path`, the name `name` it declares by default and +/// the inline modules `chain` (outermost first) its declaration must sit in. +struct Loaded<'a> { + path: &'a str, + name: &'a str, + chain: &'a [String], } -/// Whether `at` in the masked text `m` is inside an inline `mod { … }`, where a `mod x;` -/// loads a file under that module's directory instead of a sibling file. -fn in_inline_mod(m: &[u8], at: usize) -> bool { - m[..at].iter().enumerate().filter(|&(_, &c)| c == b'{').any(|(open, _)| { - if !matching(m, open).is_some_and(|close| close > at) { - return false; +/// 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 +/// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None` +/// when `src` loads no such file. +fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Vec)> { + let m = mask(src); + let lines = Lines::new(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let (mut each, mut at_lines) = (vec![], vec![]); + 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';') || inline_mods(&m, at) != want.chain { + continue; } - let head = m[..open].trim_ascii_end(); - let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); - let before = head[..head.len() - name].trim_ascii_end(); - name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident) + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let loads = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => { + // A `#[path]` outside inline modules is relative to the file's directory; inside them, + // to the inline modules' directory under the file's module. + let mut base = dir.to_owned(); + if !want.chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in want.chain { + base = join_path(&base, seg); + } + join_path(&base, &rel) == want.path + } + None => &m[start..end] == want.name.as_bytes(), + }; + if !loads { + continue; + } + // Inner attributes cover the file, and [`cfgs_over`] reads them. + let attrs: Vec = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); + at_lines.push(lines.of(at)); + at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); + let mut preds: Vec = attrs.into_iter().map(|a| a.pred).collect(); + for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + preds.push(p); + at_lines.push(lines.of(a)); + } + each.push(preds); + } + let preds = match each.len() { + 0 => return None, + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::>().join(","))], + }; + Some((preds, at_lines)) +} + +/// The string value of a `#[path = "…"]` attribute in `m[from..to]`. +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); + if !attr || m.get(eq) != Some(&b'=') || m.get(q) != Some(&b'"') { + return None; + } + let close = find(m, b"\"", q + 1)?; + Some(String::from_utf8_lossy(&src[q + 1..close]).into_owned()) }) } +/// `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(); + for seg in rel.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +/// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost +/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. +fn inline_mods(m: &[u8], at: usize) -> Vec { + m[..at] + .iter() + .enumerate() + .filter(|&(open, &c)| c == b'{' && matching(m, open).is_some_and(|close| close > at)) + .filter_map(|(open, _)| { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + (name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident)) + .then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()) + }) + .collect() +} + /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() +} + +/// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares +/// them, the lines of those declarations and attributes. +#[derive(Default)] +struct Gates { + preds: Vec, + sources: Vec<(String, Vec)>, +} + +/// [`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 +/// (`mod platform { mod child; }` loads `platform/child.rs`). +fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut preds, mut at) = (vec![], path.clone()); - for _ in 0..16 { - let Some((name, candidates)) = module_parent(&at) else { break }; - let Some((parent, found)) = candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, name)).map(|f| (c, f))) else { + 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; }; - preds.extend(found); - at = parent; + let mut chain: Vec = vec![]; + for _ in 0..4 { + let want = Loaded { path: &at, name: &name, chain: &chain }; + if let Some((parent, (preds, lines))) = + candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, &c, &want)).map(|f| (c, f))) + { + gates.preds.extend(preds); + gates.sources.push((parent.clone(), lines)); + at = parent; + continue 'up; + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + break; } - if !preds.is_empty() { - out.insert(path.clone(), preds); + if !gates.preds.is_empty() { + out.insert(path.clone(), gates); } } out @@ -3501,6 +3714,8 @@ mod tests { assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; 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"); } #[test] @@ -4997,9 +5212,8 @@ mod tests { assert_eq!(only("mirror", oracle), [], "two functions of the same name in different paths"); let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; assert_eq!(only("mirror", ne), [], "two inputs that must differ"); - let allowed = - "#[test]\nfn t() {\n // test-lint: allow mirror both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; - assert_eq!(only("mirror", allowed), []); + let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror scaling is linear by definition\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; + assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); } #[test] @@ -5029,6 +5243,8 @@ mod tests { assert_eq!(hits(scoped), [], "a binding in a block that has ended"); let later = "#[test]\nfn t() {\n let x = compute();\n let y = x;\n let x = 0;\n assert_eq!(y, 2);\n assert_eq!(x, 0);\n}\n"; assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one"); + let if_let = "#[test]\nfn t() {\n let x = 0;\n if let Some(x) = compute() {\n assert_eq!(x, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); } #[test] @@ -5082,15 +5298,57 @@ mod tests { #[test] fn never_run_follows_the_cfg_around_the_mod_declaration() { + let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; + let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want).map(|(p, _)| p); let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; - assert_eq!(declared_cfgs(inner, "child"), Some(vec!["target_os=\"macos\"".to_owned()])); + assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; - assert_eq!(declared_cfgs(block, "child"), None, "that `mod child;` loads platform/child.rs"); + assert_eq!(declared(block, &child), None, "that `mod child;` loads platform/child.rs"); + let platform = ["platform".to_owned()]; + let nested = Loaded { path: "src/platform/child.rs", name: "child", chain: &platform }; + assert_eq!(declared(block, &nested), Some(vec!["windows".to_owned()]), "the gate on the inline module"); let both = "#[cfg(windows)]\nmod platform {\n mod child;\n}\nmod child;\n"; - assert_eq!(declared_cfgs(both, "child"), Some(vec![]), "the root declaration, not the one in platform"); + assert_eq!(declared(both, &child), Some(vec![]), "the root declaration, not the one in platform"); let gated = "#[cfg(windows)]\nconst _: () = {\n mod child;\n};\n"; - assert_eq!(declared_cfgs(gated, "child"), Some(vec!["windows".to_owned()]), "a gated block that is not a module"); - assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); + assert_eq!(declared(gated, &child), Some(vec!["windows".to_owned()]), "a gated block that is not a module"); + assert_eq!(declared("mod child;\n", &child), Some(vec![])); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\nmod child;\n"; + assert_eq!(declared(commented, &child), Some(vec!["target_os=\"linux\"".to_owned()]), "a comment in the predicate"); + let paths = "#[cfg(windows)]\n#[path = \"windows.rs\"]\nmod imp;\n#[cfg(not(windows))]\nmod imp;\n"; + let imp = Loaded { path: "src/imp.rs", name: "imp", chain: &[] }; + assert_eq!(declared(paths, &imp), Some(vec!["not(windows)".to_owned()]), "the declaration that loads imp.rs"); + let win = Loaded { path: "src/windows.rs", name: "windows", chain: &[] }; + assert_eq!(declared(paths, &win), Some(vec!["windows".to_owned()]), "the `#[path]` override"); + let twice = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg(target_os = \"linux\")]\n#[path = \"child.rs\"]\nmod other;\n"; + assert_eq!(declared(twice, &child), Some(vec!["any(all(target_os=\"macos\"),all(target_os=\"linux\"))".to_owned()])); + let attr = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\nmod child;\n"; + assert_eq!(declared(attr, &child), Some(vec!["any(not(unix),target_os=\"macos\")".to_owned()])); + } + + #[test] + fn never_run_reads_cfg_attr_and_commented_predicates() { + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "Linux runs it"); + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", mac), [(3, "never-run")]); + let nested = "#[cfg_attr(unix, cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", nested), [(3, "never-run")], "unix holds on every CI target, so the nested cfg applies"); + let unknown = "#[cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unknown), [], "a condition that may not hold"); + } + + #[test] + fn a_changed_parent_declaration_counts_for_the_child_tests() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "mod plain;\n#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + let lib = |lines: &[usize]| -> BTreeMap>> { + [("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))].into_iter().collect() + }; + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); + assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); } #[test] @@ -5131,5 +5389,7 @@ mod tests { assert_eq!(only("reads-source", read), [(3, "reads-source")]); 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"; + assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); } } From 44c8e3451307c62f644eb1cae158d4005ba6b0ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:42:46 -0800 Subject: [PATCH 04/10] xtask: test-lint review fixes for spans, cfg_attr, shared roots and bindings - A negated .contains(...) check forbids a value and is no longer treated as a presence check; !items.is_empty() still is. - reads-source matches the last path literal of a read_to_string argument, and its span runs through the argument's closing paren. - A for pattern binding shadows an outer let inside the loop body. - Nested cfg_attr conditions are combined before the inner cfg applies. - A never-run hit counts edits to the enclosing cfg lines and to the test, not to code between them. - A parent declaration edit counts against a child's test only when the test still ran in CI at the base. - A module loaded by several roots is off only when every root leaves it out. - docs/development.md lists reads-source and never-run as failing rules. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 190 +++++++++++++++++++++++++++++++++-------- 2 files changed, 154 insertions(+), 38 deletions(-) diff --git a/docs/development.md b/docs/development.md index a1ceccaf59..c833a400e8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, and an environment variable that no CI leg sets. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 168dd8ff79..5384b51e4c 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -235,15 +235,14 @@ pub struct Hit { /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's - /// `]` for `ignore-without-reason`, else `line`. This span + /// `]` for `ignore-without-reason`, through the call's `)` for `reads-source`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. pub first: usize, pub last: usize, - /// The first line an allow comment may sit on to exempt the hit, when it differs from `first`: - /// a `never-run` hit spans an enclosing module's `cfg`, but only an allow at the test's own - /// attributes exempts it. - pub allow_from: Option, + /// Lines outside `first..=last` that also count as changes to the hit: the enclosing `cfg` + /// attributes of a `never-run` test. An allow comment there does not exempt it. + pub gates: Vec, } impl Hit { @@ -311,11 +310,20 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let gates = module_gates(&gated, &|p| read_small(root, p)); 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(); + let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; + let newly_off = + |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { let parent_changed = gate_changed(gates.get(&path), &changed); 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) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) + || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) + { counted.push(hit); } else { older += 1; @@ -324,7 +332,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { let Some(src) = read_small(root, path) else { continue }; - counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun)); + counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } finish(&counted, older, present.len(), &base) } @@ -575,7 +583,7 @@ fn hunk_range(hunk: &str) -> Option<(usize, usize)> { /// Whether `hit` covers a changed line (`None`: the whole file is new). fn touches(hit: &Hit, changed: Option<&BTreeSet>) -> bool { - changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) + changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some() || hit.gates.iter().any(|l| lines.contains(l))) } // ---- What CI sets ---- @@ -1214,7 +1222,7 @@ struct File<'a> { impl File<'_> { fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { let line = self.lines.of(at); - Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, allow_from: None } + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, gates: vec![] } } fn test_at(&self, pos: usize) -> &str { @@ -1254,7 +1262,7 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { hits.extend(reads_source_hits(&file)); let allows = allows(src, &file.m); hits.retain(|h| { - let first = if h.rule == Rule::AllUnguarded { h.line } else { h.allow_from.unwrap_or(h.first) }; + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) }); hits.sort(); @@ -1624,7 +1632,12 @@ fn weak_predicate(pred: &str) -> bool { if let Some(at) = boolean_split(pred) { return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); } + let negated = pred.starts_with('!'); let pred = pred.trim_start_matches('!'); + // A negated membership or presence check forbids a value; only `!….is_empty()` stays a presence check. + if negated && !pred.ends_with(".is_empty()") { + return false; + } if let Some(list) = pred.strip_suffix(".len()>0") { return !list.contains(['=', '<', '>']); } @@ -2976,18 +2989,29 @@ fn reads_source_hits(file: &File) -> Vec { let literal = raw.unwrap_or(&arg); let rs = match word { b"ends_with" => literal == "\".rs\"", - // A path literal anywhere in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`. - b"read_to_string" => arg.contains(".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\"")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { - out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + let mut hit = file.hit(at, Rule::ReadsSource, file.test_at(at), note.into()); + // The span runs through the argument, so a change to a path on a later line counts. + hit.last = file.lines.of(close); + out.push(hit); } } } out } +/// The last string literal in a (whitespace-free) expression, quotes included. +fn last_literal(arg: &str) -> Option<&str> { + let close = arg.rfind('"')?; + let open = arg[..close].rfind('"')?; + Some(&arg[open..=close]) +} + // ---- Mirrors, echoes, never-run tests and exact pixels ---- /// Names a `mirror` comparison may call on both sides: builders, conversions and accessors. @@ -3133,6 +3157,24 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { /// none, `Some(None)` when the reaching binding is `mut`, a pattern or has no initializer. The /// initializer comes with the offset of its `let`, where the names it reads are resolved. fn reaching_init(body: &[u8], name: &str, before: usize) -> Option> { + let found = let_init(body, name, before); + // A `for` pattern binds its names inside the loop body only, to values the loop produces. + let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| { + let Some((open, close)) = let_body(body, at + 3) else { return false }; + let head = String::from_utf8_lossy(&body[at + 3..open]); + let Some((pattern, _)) = head.split_once(" in ") else { return false }; + let pattern = norm(pattern.as_bytes()); + open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() + }); + match (loop_at, &found) { + (Some(l), Some((_, at))) if *at > l => found.map(|(init, _)| init), + (Some(_), _) => Some(None), + (None, _) => found.map(|(init, _)| init), + } +} + +/// [`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; for at in words(body, b"let", 0, before) { let start = skip_ws(body, at + 3); @@ -3148,7 +3190,7 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option n0 && (rest.is_empty() || rest.starts_with(':') || rest.starts_with('=')); if plain && &body[n0..n1] == name.as_bytes() { let init = rest.split_once('=').filter(|(ty, _)| ty.is_empty() || ty.starts_with(':')).map(|(_, init)| (init.to_owned(), at)); - found = Some(if is_mut { None } else { init }); + found = Some((if is_mut { None } else { init }, at)); } else if !plain { // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). let pattern = norm(&body[n0..stop]); let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); if !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { - found = Some(None); + found = Some((None, at)); } } } @@ -3334,15 +3376,8 @@ fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec { out.push(CfgAttr { pred: text, at, end, inner }); continue; } - let cuts = top_level_at(&text, ","); - let Some(&first) = cuts.first() else { continue }; - let cond = &text[..first]; - let mut start = first + 1; - for cut in cuts[1..].iter().copied().chain([text.len()]) { - if let Some(p) = text.get(start..cut).and_then(|p| p.strip_prefix("cfg(")).and_then(|p| p.strip_suffix(')')) { - out.push(CfgAttr { pred: format!("any(not({cond}),{p})"), at, end, inner }); - } - start = cut + 1; + for pred in cfg_attr_preds(&text, None) { + out.push(CfgAttr { pred, at, end, inner }); } } } @@ -3350,6 +3385,30 @@ fn cfg_attrs(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec { out } +/// The `cfg` predicates inside the arguments of a `cfg_attr(, …)`, each made +/// `any(not(),)`. A nested `cfg_attr` adds its condition to the enclosing +/// ones: `cfg_attr(unix, cfg_attr(test, cfg(p)))` gives `any(not(all(unix,test)),p)`. +fn cfg_attr_preds(text: &str, outer: Option<&str>) -> Vec { + let cuts = top_level_at(text, ","); + let Some(&first) = cuts.first() else { return vec![] }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut out = vec![]; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(p) = arg.strip_prefix("cfg(").and_then(|p| p.strip_suffix(')')) { + out.push(format!("any(not({cond}),{p})")); + } else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) { + out.extend(cfg_attr_preds(n, Some(&cond))); + } + start = cut + 1; + } + 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. fn pred_text(src: &[u8]) -> String { @@ -3539,11 +3598,18 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> Hash let mut chain: Vec = vec![]; for _ in 0..4 { let want = Loaded { path: &at, name: &name, chain: &chain }; - if let Some((parent, (preds, lines))) = - candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, &c, &want)).map(|f| (c, f))) - { - gates.preds.extend(preds); - gates.sources.push((parent.clone(), lines)); + // 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; } @@ -3566,7 +3632,7 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> Hash 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 first_attr = local.iter().map(|&(_, at)| at).min(); + 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(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { @@ -3577,10 +3643,9 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { if CI_TARGETS.iter().chain(windows).all(off) { let shown: Vec = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); let mut hit = v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", "))); - if let Some(at) = first_attr { - hit.allow_from = Some(hit.first); - hit.first = hit.first.min(v.file.lines.of(at)); - } + // Enclosing attributes count as separate lines, so an edit to code between them and the + // test does not count. + hit.gates = attr_lines.into_iter().filter(|&l| l < hit.first).collect(); return Some(hit); } None @@ -5355,9 +5420,14 @@ mod tests { fn never_run_hits_cover_the_attribute_that_turns_the_test_off() { let src = "#[cfg(target_os = \"macos\")]\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).map(|h| (h.first, h.line)); - assert_eq!(hit, Some((1, 4))); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line, h.gates.clone())); + assert_eq!(hit, Some((3, 4, vec![1]))); assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let helper = + "#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", helper, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[3].into_iter().collect())), "a helper between the module cfg and the test"); let two = "#[cfg(target_os = \"macos\")]\nmod mac {\n // test-lint: allow never-run checks the macOS menu bar\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n"; let left: Vec = lint_file("crates/x/src/tests.rs", two, &ctx()).iter().filter(|h| h.rule == Rule::NeverRun).map(|h| h.line).collect(); assert_eq!(left, [9], "an allow above one test leaves the next one reported"); @@ -5391,5 +5461,51 @@ mod tests { 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"; assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); + let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + let found = lint_file("crates/x/src/tests.rs", split, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); + assert_eq!((hit.line, hit.last), (3, 5), "the span runs through the path on the next line"); + assert!(touches(hit, Some(&[4].into_iter().collect()))); + } + + #[test] + fn negated_membership_checks_are_not_presence_checks() { + assert!(!weak_predicate("!errors_for(c).contains(&Error::Unexpected)")); + assert!(!weak_predicate("!map.contains_key(&k)")); + assert!(weak_predicate("!items.is_empty()")); + assert!(weak_predicate("errors_for(c).contains(&Error::Expected)")); + } + + #[test] + fn a_for_binding_shadows_the_outer_one_in_its_body() { + let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", looped), []); + let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); + } + + #[test] + fn nested_cfg_attr_gates_apply() { + let nested = "#[cfg_attr(unix, cfg_attr(test, cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", nested), [(3, "never-run")]); + let unknown = "#[cfg_attr(unix, cfg_attr(feature = \"gpu\", cfg(target_os = \"macos\")))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unknown), []); + } + + #[test] + fn a_module_loaded_by_two_roots_runs_if_either_runs_it() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod shared;\n"), + ("crates/x/src/main.rs", "mod shared;\n"), + ("crates/x/src/shared.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } } From 579fa0c247c7d0f11773d930771946d0b2ef831a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:31:47 -0800 Subject: [PATCH 05/10] xtask: test-lint mirror leaves out reads at two entries and shared arithmetic - Two calls that differ only in the entry they name (a string or integer literal, a local, a field or an indexed element) relate two entries, as in at("B") == at("A") + 1 or bounds(&s, copy) == bounds(&s, id) + dv, and are no longer reported. - The same arithmetic on both sides (rotate_deg(-270.0) * v == rotate_deg(90.0) * v) checks that two inputs agree and is no longer reported. On main, test-lint --all reports 1 mirror hit instead of 14. --- xtask/src/test_lint.rs | 72 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..baf93450e6 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -48,7 +48,9 @@ //! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; //! * `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; +//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same +//! arithmetic on both sides and two reads that differ only in the entry they name (a string or +//! integer literal, a local or an indexed element); //! * `constant-echo`: every assertion of the test compares only constants, literals and enum //! variants; //! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the @@ -3066,22 +3068,59 @@ fn head_call(op: &str) -> Option<&str> { } } -/// `assert_eq!(f(a), f(b))`: both sides start by calling the same function, so a fault in `f` can -/// move both sides together. Identical sides are `self-compare`'s. +/// The offset of the first top-level `+`, `-`, `*` or `/` in a whitespace-free operand. +fn first_arithmetic(op: &str) -> Option { + ["+", "-", "*", "/"].iter().flat_map(|o| top_level_at(op, o)).min() +} + +/// The whitespace-free source text of the arguments of the call an operand starts with, read from +/// the unmasked source so string literals keep their text. +fn head_args(f: &File, (from, to): (usize, usize)) -> Option> { + let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; + let close = matching(&f.m, open)?; + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(&f.src[a..b])).collect()) +} + +/// An argument that names an entry rather than a quantity: a string or integer literal, or a local, +/// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). +fn key_like(arg: &str) -> bool { + let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); + match arg.as_bytes().first() { + Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), + Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), + None => false, + } +} + +/// `assert_eq!(f(a), f(b) …)`: the expected side derives its value from a second call of the +/// same function with arithmetic, so a fault in `f` can move both sides together. Identical sides +/// are `self-compare`'s. Left out: the same arithmetic on both sides (`f(a) * v == f(b) * v` +/// checks that two inputs agree, as a periodicity check does), and two reads at different entries +/// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries. fn mirrors(v: &View) -> Vec { v.asserts .iter() .filter(|a| a.name.ends_with("_eq")) .filter_map(|a| { - let (l, r) = (norm(&v.file.m[a.args.first()?.0..a.args.first()?.1]), norm(&v.file.m[a.args.get(1)?.0..a.args.get(1)?.1])); + let (lr, rr) = (*a.args.first()?, *a.args.get(1)?); + let (l, r) = (norm(&v.file.m[lr.0..lr.1]), norm(&v.file.m[rr.0..rr.1])); let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); let name = head_call(l)?; - // The expected side derives its value from a second call with arithmetic; two calls - // 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()); + // Two calls compared as they are check that two inputs agree, which is a real check. + let derived = match (first_arithmetic(l), first_arithmetic(r)) { + (_, None) => false, + (Some(i), Some(j)) => l[i..] != r[j..], + (None, Some(_)) => true, + }; 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))) + if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) { + return None; + } + let (la, ra) = (head_args(v.file, lr)?, head_args(v.file, rr)?); + let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); + let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); + (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) }) .collect() } @@ -5279,6 +5318,21 @@ mod tests { assert_eq!(only("mirror", ne), [], "two inputs that must differ"); let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror scaling is linear by definition\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); + let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n"; + assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry"); + } + + #[test] + fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() { + let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n"; + assert_eq!(only("mirror", order), [], "positions of two entries in one list"); + let offset = + "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; + assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); + let period = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * v);\n}\n"; + assert_eq!(only("mirror", period), [], "the same arithmetic on both sides"); + let tails = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * w);\n}\n"; + assert_eq!(only("mirror", tails), [(3, "mirror")], "different arithmetic on each side still derives one from the other"); } #[test] From 3d2b663b9e61206d2ef31b6ad4f75f2af0719c62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:27:27 -0800 Subject: [PATCH 06/10] xtask: test-lint never-run follows #[path] modules and multiline gates never-run now finds the files that load a module through `#[path]`, including a sibling such as `graphics.rs` loading `tests_graphics.rs`, and follows them in both `--all` and changed-file mode. A changed file now reaches every file it loads, directly or through other modules, so a `cfg` added to its `mod` declaration flags the unchanged child's tests. - Every route to a module counts: inline-module routes, `#[path]` routes and several routes from one file are joined, each with its own ancestors, and a crate root keeps its own route. - A default `mod x;` matches only the file it really loads. - Every line of a multiline `cfg` attribute counts as a gate line, for the test's own gates and for the parent declarations. - The base comparison reads `#[path]` declarations from the base tree, so a moved declaration is not reported as newly off. --- xtask/src/test_lint.rs | 675 +++++++++++++++++++++++++++++++++++------ 1 file changed, 579 insertions(+), 96 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index baf93450e6..dc10c00fe7 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,43 @@ fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap, + base_gates: Option<&Gates>, + base_overrides: &Overrides, + changed: &BTreeMap>>, +) -> bool { + gate_changed(gates, changed) + || base_gates.is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent))) + || base_overrides.get(path).is_some_and(|routes| routes.iter().any(|(parent, _)| changed.contains_key(parent))) +} + /// 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() } +/// Cache successful and missing reads for one source tree. +fn cached_read(read: impl Fn(&str) -> Option) -> impl Fn(&str) -> Option { + let cache = RefCell::new(HashMap::>::new()); + move |path| cache.borrow_mut().entry(path.to_owned()).or_insert_with(|| read(path)).clone() +} + pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let opts = Options::parse(args)?; + let read_work = cached_read(|p| read_small(root, p)); 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(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + let overrides = path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))); + let module_cfgs = module_cfgs(&files, &read_work, &overrides); 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())); @@ -297,31 +320,27 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { 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(); + // Files that load a module through `#[path]`, found with `git grep` (untracked files included) + // instead of reading the tree. + let overrides = discover_path_overrides(root, None, &read_work); + let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); + let base_overrides = discover_path_overrides(root, Some(&base), &read_base); + // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` + // declaration can turn their tests off without a change to them. + let below: Vec = descendants(&present, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); - let gates = module_gates(&gated, &|p| read_small(root, p)); + let gates = module_gates(&gated, &read_work, &overrides); 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(); + let base_gates = module_gates(&gated, &read_base, &base_overrides); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - 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 newly_off = |path: &str, src: &str, hit: &Hit| !already_off(&lint_file(path, src, &base_ctx), hit); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); 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)) @@ -332,13 +351,50 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { - let Some(src) = read_small(root, path) else { continue }; + for path in below.iter().filter(|p| route_gate_changed(p, gates.get(*p), base_gates.get(*p), &base_overrides, &changed)) { + let Some(src) = read_work(path) else { continue }; counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } finish(&counted, older, present.len(), &base) } +/// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the +/// test of `hit`. Tests of one name in different inline modules are told apart by their line. +fn already_off(base: &[Hit], hit: &Hit) -> bool { + base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +} + +/// The directory holding the modules that the file `p` declares by name: its own directory for +/// `mod.rs`, `lib.rs` and `main.rs`, and the directory named after it otherwise. +fn module_dir(p: &str) -> String { + 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")) } +} + +/// The files of `files` that the files `start` load, directly or through modules in between: the +/// files under their module directories and the files their current or base `#[path]` declarations load. +fn descendants(start: &[String], files: &[String], overrides: &Overrides, base_overrides: &Overrides) -> Vec { + let mut seen: BTreeSet = start.iter().cloned().collect(); + let mut frontier: Vec = start.to_vec(); + let mut out = vec![]; + while !frontier.is_empty() { + let dirs: Vec = frontier.iter().map(|p| module_dir(p)).collect(); + let next: Vec = files + .iter() + .filter(|p| !seen.contains(*p)) + .filter(|p| { + dirs.iter().any(|d| p.starts_with(d.as_str())) + || overrides.get(*p).into_iter().chain(base_overrides.get(*p)).flatten().any(|(parent, _)| frontier.contains(parent)) + }) + .cloned() + .collect(); + seen.extend(next.iter().cloned()); + out.extend(next.iter().cloned()); + frontier = next; + } + out +} + /// The command line: `--all`, `--base `. #[derive(Debug, Default, PartialEq)] struct Options { @@ -3365,6 +3421,8 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { + let arg = arg.trim(); + let arg = arg.strip_suffix(',').unwrap_or(arg).trim_end(); return cfg_value(arg, t).map(|v| !v); } // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. @@ -3455,8 +3513,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 where its attribute starts and ends. `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 { @@ -3472,7 +3530,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 @@ -3480,10 +3538,12 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { /// The module name a file declares and the files that may declare it with `mod ;`, or `None` /// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or -/// `examples`). +/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `src` holds modules, not test targets. 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)); + let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); + let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin"); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } @@ -3511,6 +3571,10 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, let lines = Lines::new(src); let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let mut default_dir = if mod_rs { dir.to_owned() } else { join_path(dir, file.strip_suffix(".rs").unwrap_or(file)) }; + for seg in want.chain { + default_dir = join_path(&default_dir, seg); + } let (mut each, mut at_lines) = (vec![], vec![]); for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); @@ -3520,19 +3584,11 @@ 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. - let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { - base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); - } - for seg in want.chain { - base = join_path(&base, seg); - } - join_path(&base, &rel) == want.path + Some(rel) => override_path(dir, file, mod_rs, want.chain, &rel) == want.path, + None => { + &m[start..end] == want.name.as_bytes() + && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } - None => &m[start..end] == want.name.as_bytes(), }; if !loads { continue; @@ -3540,11 +3596,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: an edit inside its predicate changes it. + 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, e) 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(e)); } each.push(preds); } @@ -3556,6 +3613,90 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Some((preds, at_lines)) } +/// The file a `#[path = ""]` declaration in the file `dir/file` loads. Outside inline modules +/// `rel` is relative to the file's directory; inside them (`chain`, outermost first), to the inline +/// modules' directory under the file's module. +fn override_path(dir: &str, file: &str, mod_rs: bool, chain: &[String], rel: &str) -> String { + let mut base = dir.to_owned(); + if !chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + +/// The files that `#[path]` declarations in `src`, the file `parent`, load, each with the inline +/// modules its declaration sits in. +fn path_children(src: &str, parent: &str) -> Vec<(String, Vec)> { + let m = mask(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let mut out = vec![]; + 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 chain = inline_mods(&m, at); + out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); + } + } + out +} + +/// The files that load a module file through `#[path]`, keyed by the file they load: a sibling such +/// as `graphics.rs` loading `tests_graphics.rs` is not among the files [`module_parent`] names. +type Overrides = HashMap)>>; + +/// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources. +fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { + let with_path = match base { + Some(base) => git(root, &["grep", "-l", "-w", "path", base, "--", "*.rs"]), + None => git(root, &["grep", "--untracked", "-l", "-w", "path", "--", "*.rs"]), + } + .unwrap_or_default(); + listed_path_overrides(&with_path, base, read) +} + +/// Read paths from `git grep -l`, removing the revision prefix for a base-tree listing. +fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { + let prefix = base.map(|b| format!("{b}:")); + let sources: Vec<(String, String)> = list + .lines() + .filter_map(|p| match &prefix { + Some(prefix) => p.strip_prefix(prefix), + None => Some(p), + }) + .filter(|p| is_scanned(p)) + .filter_map(|p| read(p).map(|s| (p.to_owned(), s))) + .collect(); + path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))) +} + +/// [`Overrides`] for the files `sources`, as `(path, source)` pairs. +fn path_overrides<'a>(sources: impl IntoIterator) -> Overrides { + let mut out: Overrides = HashMap::new(); + for (parent, src) in sources { + if !src.contains("path") { + continue; + } + for (child, chain) in path_children(src, parent) { + // One entry per parent and inline modules: [`declared_cfgs`] joins the declarations of + // one file in one module. + let routes = out.entry(child).or_default(); + if !routes.iter().any(|(p, c)| p == parent && *c == chain) { + routes.push((parent.to_owned(), chain)); + } + } + } + out +} + /// The string value of a `#[path = "…"]` attribute in `m[from..to]`. fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { words(m, b"path", from, to).into_iter().find_map(|at| { @@ -3604,8 +3745,8 @@ 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`. -fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { - module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option, overrides: &Overrides) -> HashMap> { + module_gates(paths, read, overrides).into_iter().map(|(p, g)| (p, g.preds)).collect() } /// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares @@ -3617,62 +3758,85 @@ 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 -/// (`mod platform { mod child; }` loads `platform/child.rs`). -fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { - let mut out = HashMap::new(); - for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } - if !gates.preds.is_empty() { - out.insert(path.clone(), gates); - } +/// may declare its module and in the files above them through inline modules +/// (`mod platform { mod child; }` loads `platform/child.rs`), and in the files of `overrides` that +/// load it through `#[path]`. +fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option, overrides: &Overrides) -> HashMap { + let read = cached_read(read); + paths + .iter() + .filter_map(|path| { + let gates = module_gate(path, &read, overrides, 0); + (!gates.preds.is_empty()).then(|| (path.clone(), gates)) + }) + .collect() +} + +/// Resolve each route's ancestors before joining routes, with a bound for cyclic module paths. +fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Overrides, depth: usize) -> Gates { + let mut gates = Gates::default(); + if depth >= 16 { + return gates; } - out + let by_path = overrides.get(at).map_or(&[][..], Vec::as_slice); + // A crate root runs independently of any module declarations that also load it. + let Some((name, mut candidates)) = module_parent(at) else { return gates }; + let name = name.to_owned(); + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + return gates; + }; + let mut chain: Vec = vec![]; + let mut found = 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. + found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + if chain.is_empty() { + for (c, inline) in by_path { + // A candidate was read with no inline modules; another route through the + // same file still counts. + if inline.is_empty() && candidates.contains(c) { + continue; + } + let want = Loaded { path: at, name: &name, chain: inline }; + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))); + } + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + let mut each = vec![]; + for (parent, (mut preds, lines)) in found { + let ancestors = module_gate(&parent, read, overrides, depth + 1); + preds.extend(ancestors.preds); + gates.sources.push((parent, lines)); + gates.sources.extend(ancestors.sources); + each.push(preds); + } + gates.preds = match each.len() { + 0 => vec![], + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.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(); + // A change to an attribute that turns the test off counts as a change to the test, on any line + // of a multiline attribute. + 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; @@ -5366,6 +5530,18 @@ mod tests { assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); } + #[test] + fn never_run_accepts_trailing_commas_in_cfg_predicates() { + for pred in ["not(unix,)", "not( unix , )", "all(not(unix,),)", "any(not(unix,),)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [(3, "never-run")], "{pred}"); + } + for pred in ["all(unix,)", "any(unix,)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [], "{pred}"); + } + } + #[test] fn never_run_tests_are_compiled_out_on_every_ci_target() { let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; @@ -5391,6 +5567,27 @@ mod tests { assert_eq!(only("never-run", other), [], "a cfg on another item"); } + #[test] + fn module_gates_reads_each_candidate_once() { + let paths: Vec = (0..32).map(|i| format!("crates/x/src/parent/child{i}.rs")).collect(); + let parent = (0..32).map(|i| format!("mod child{i};\n")).collect::(); + let files = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n"), ("crates/x/src/parent.rs", parent.as_str())]; + let reads = RefCell::new(HashMap::::new()); + let read = |p: &str| { + *reads.borrow_mut().entry(p.to_owned()).or_default() += 1; + files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()) + }; + let gates = module_gates(&paths, &read, &Overrides::new()); + assert_eq!(gates.len(), paths.len(), "every child inherits the parent gate"); + let reads = reads.borrow(); + assert_eq!(reads.get("crates/x/src/lib.rs"), Some(&1), "a shared ancestor"); + assert_eq!(reads.get("crates/x/src/parent.rs"), Some(&1), "a shared parent"); + assert_eq!(reads.get("crates/x/src/parent/mod.rs"), Some(&1), "a missing candidate"); + for (path, count) in reads.iter() { + assert_eq!(*count, 1, "candidate {path}"); + } + } + #[test] fn never_run_follows_the_cfg_of_the_mod_declaration() { let files: HashMap<&str, &str> = [ @@ -5405,7 +5602,7 @@ mod tests { .into_iter() .map(String::from) .collect(); - let cfgs = module_cfgs(&paths, &read); + let cfgs = module_cfgs(&paths, &read, &Overrides::new()); assert_eq!(cfgs.get("crates/x/src/mac.rs").map(Vec::as_slice), Some(&["target_os=\"macos\"".to_owned()][..])); assert!(cfgs.contains_key("crates/x/src/mac/inner.rs"), "inherited through mac.rs"); assert!(!cfgs.contains_key("crates/x/src/plain.rs") && !cfgs.contains_key("crates/x/tests/it.rs")); @@ -5461,13 +5658,299 @@ mod tests { let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod plain;\n#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); let lib = |lines: &[usize]| -> BTreeMap>> { [("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))].into_iter().collect() }; assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); + let multiline: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod child;\nmod plain;\n"), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| multiline.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "a line inside a multiline predicate"); + assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[6])), "another declaration"); + let enclosing: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod platform {\n mod child;\n}\nmod plain;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| enclosing.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[3])), "a line inside the inline module's predicate"); + assert!(!gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[8])), "a declaration outside the inline module"); + } + + #[test] + fn never_run_follows_a_path_override_in_a_sibling_file() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod solids;\n"), + ("crates/x/src/solids/mod.rs", "mod graphics;\n"), + ("crates/x/src/solids/graphics.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"tests_graphics.rs\"]\nmod tests;\n"), + ("crates/x/src/solids/tests_graphics.rs", ""), + ] + .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/solids/tests_graphics.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&child), &read, &overrides); + assert_eq!(gates.get(&child).map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + let changed: BTreeMap>> = + [("crates/x/src/solids/graphics.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(&child), &changed), "a cfg added to the sibling's declaration"); + } + + #[test] + fn never_run_keeps_crate_roots_independent_of_path_overrides() { + for child in [ + "crates/x/tests/shared.rs", + "crates/x/src/lib.rs", + "crates/x/src/main.rs", + "crates/x/src/bin/tool.rs", + "crates/x/examples/demo.rs", + "crates/x/benches/speed.rs", + "crates/x/build.rs", + ] { + let declaration = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod shared;\n", child.strip_prefix("crates/x/").unwrap()); + let files = [("crates/x/other.rs", declaration.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the crate root runs independently: {child}"); + let gated = format!("#[cfg(target_os = \"macos\")]\n{test}"); + assert_eq!(hits_in(child, &gated, &ctx), [(3, "never-run")], "the root's own cfg still applies: {child}"); + } + } + + #[test] + fn a_namesake_already_off_does_not_hide_a_newly_off_test() { + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let path = "crates/x/src/child.rs"; + let base = lint_file(path, src, &ctx()); + let now = + lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, h)).map(|h| h.line).collect(); + assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); + } + + #[test] + fn never_run_follows_a_tests_module_directory_under_src() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod tests;\n"), ("crates/x/src/tests.rs", "mod fonts;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/tests/fonts.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets"); + assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src"); + } + + #[test] + fn path_override_discovery_accepts_attribute_whitespace_in_both_trees() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-path-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let files = [ + ("crates/x/src/a.rs", "#[cfg(target_os = \"macos\")]\n#[ path = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[\npath = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/decoy.rs", "// path is not a module attribute\nmod other;\n"), + ]; + for (path, src) in files { + std::fs::write(root.join(path), src).unwrap(); + } + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + for revision in [None, Some(base.as_str())] { + let read = |p: &str| match revision { + Some(base) => git(&root, &["show", &format!("{base}:{p}")]).ok(), + None => read_small(&root, p), + }; + let overrides = discover_path_overrides(&root, revision, &read); + let child = "crates/x/src/shared.rs"; + let parents: BTreeSet<&str> = overrides.get(child).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, [files[0].0, files[1].0].into_iter().collect(), "both whitespace forms: {revision:?}"); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &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")], "the discovered gates apply: {revision:?}"); + } + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn never_run_joins_inline_and_override_routes() { + for (lib, child) in [ + ("mod platform { mod child; }\nmod a;\n", "crates/x/src/platform/child.rs"), + ("mod platform { mod nested { mod child; } }\nmod a;\n", "crates/x/src/platform/nested/child.rs"), + ] { + let a = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod other;\n", child.strip_prefix("crates/x/src/").unwrap_or(child)); + let files = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", a.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the ungated inline route runs it"); + for parent in ["crates/x/src/lib.rs", "crates/x/src/a.rs"] { + let changed = [(parent.to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "both routes contribute their source lines: {parent}"); + } + } + } + + #[test] + fn never_run_keeps_default_and_override_files_separate() { + let files = [ + ("crates/x/src/lib.rs", "mod a;\n"), + ("crates/x/src/a.rs", "mod shared;\n#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod other;\n"), + ]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let paths = ["crates/x/src/shared.rs".to_owned(), "crates/x/src/a/shared.rs".to_owned()]; + let gates = module_gates(&paths, &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&paths[0], test, &ctx), [(2, "never-run")], "only the macOS override loads this file"); + assert_eq!(hits_in(&paths[1], test, &ctx), [], "the default declaration loads the file under a/"); + let changed = [("crates/x/src/a.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(!gate_changed(gates.get(&paths[0]), &changed), "the default declaration belongs to the other file"); + } + + #[test] + fn never_run_resolves_every_routes_ancestors() { + for (a, b, child) in [ + ("#[path = \"shared.rs\"]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n", "crates/x/src/shared.rs"), + ("mod shared;\n", "#[path = \"a/shared.rs\"]\nmod s;\n", "crates/x/src/a/shared.rs"), + ] { + for target in ["linux", "macos"] { + let lib = format!("#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"{target}\")]\nmod b;\n"); + let files = [("crates/x/src/lib.rs", lib.as_str()), ("crates/x/src/a.rs", a), ("crates/x/src/b.rs", b)]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let expected = if target == "linux" { vec![] } else { vec![(2, "never-run")] }; + assert_eq!(hits_in(child, test, &ctx), expected, "the second route's ancestors decide whether Linux runs it"); + for (parent, line) in [ + ("crates/x/src/a.rs", if a.starts_with("#[path") { 2 } else { 1 }), + ("crates/x/src/b.rs", 2), + ("crates/x/src/lib.rs", 2), + ("crates/x/src/lib.rs", 4), + ] { + let changed = [(parent.to_owned(), Some([line].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "every route and its ancestors: {parent}:{line}"); + } + } + } + } + + #[test] + fn removed_module_routes_count_only_newly_off_tests() { + let a = "crates/x/src/a.rs"; + let child = "crates/x/src/shared.rs"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let mac = "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"; + let work_files = [("crates/x/src/lib.rs", "mod a;\nmod b;\n"), (a, ""), ("crates/x/src/b.rs", mac)]; + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(work_files); + let paths = [child.to_owned()]; + let gates = module_gates(&paths, &read_work, &overrides); + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let hit = lint_file(child, test, &work_ctx).into_iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + for (before, ran) in [(declaration, true), (mac, false)] { + let base_files = [("crates/x/src/lib.rs", work_files[0].1), (a, before), ("crates/x/src/b.rs", mac)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = path_overrides(base_files); + let base_gates = module_gates(&paths, &read_base, &base_overrides); + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::>(); + assert!( + descendants(&[a.to_owned()], &files, &overrides, &base_overrides).contains(&child.to_owned()), + "the removed route still reaches the shared tests" + ); + for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { + let changed = [(a.to_owned(), lines)].into_iter().collect(); + assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); + let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); + assert!(parent_changed, "deletions and shifted lines still change a base route"); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), &hit), ran); + assert!( + route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), + "a base route parent counts even without inherited predicates" + ); + } + let changed = [("crates/x/src/lib.rs".to_owned(), Some([20].into_iter().collect()))].into_iter().collect(); + assert!( + route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed), + "an edited base ancestor counts even when its old line numbers do not match" + ); + } + } + + #[test] + fn base_path_overrides_follow_declarations_before_a_move() { + let a = "crates/x/src/a.rs"; + let b = "crates/x/src/b.rs"; + let child = "crates/x/src/shared.rs"; + let lib = "#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let base_files = [("crates/x/src/lib.rs", lib), (a, declaration), (b, "")]; + let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = listed_path_overrides(&format!("before:{a}\n"), Some("before"), &read_base); + let work_overrides = listed_path_overrides(&format!("{b}\n"), None, &read_work); + let paths = [child.to_owned()]; + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &work_ctx), [(2, "never-run")]); + assert_eq!(hits_in(child, test, &base_ctx), [(2, "never-run")], "the test was already off before the equally gated declaration moved"); + } + + #[test] + fn never_run_joins_two_inline_routes_from_one_file() { + let a = "#[cfg(target_os = \"macos\")]\nmod m {\n #[path = \"../shared.rs\"]\n mod s;\n}\nmod n {\n #[path = \"../shared.rs\"]\n mod s;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", a)].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 shared = "crates/x/src/a/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it"); + } + + #[test] + fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() { + let files: Vec = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"] + .into_iter() + .map(String::from) + .collect(); + let overrides = path_overrides([ + ("src/solids/graphics.rs", "#[path = \"map_art.rs\"]\nmod art;\n"), + ("src/solids/map_art.rs", "#[path = \"tests_map_art.rs\"]\nmod tests;\n"), + ]); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new()); + assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); + } + + #[test] + fn never_run_counts_every_line_of_a_multiline_test_gate() { + let src = + "#[cfg(all(\n unix,\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(&[3].into_iter().collect())), "an edit inside the predicate"); } #[test] @@ -5558,7 +6041,7 @@ mod tests { .into_iter() .collect(); let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read), ..ctx() }; + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read, &Overrides::new()), ..ctx() }; let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } From e1c1b04f25f1979ff5be4b2b3a182534a41d1a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:27:46 -0800 Subject: [PATCH 07/10] xtask: test-lint follows deleted and detached routes and decoded cfg values - A deleted file stays in the changed set and seeds the descendant walk, so a module it loaded through #[path] is checked for a lost CI route. - A parent file that no crate target loads (its mod line removed) no longer counts as an ungated route to the module it declares. - #[path] on an inline module sets the directory of the modules inside it. - git grep lists #[path] parents with -z, so non-ASCII paths are read verbatim in both trees. - cfg string values are compared decoded ("\x6cinux" is linux); raw strings stay as written. - mirror reports arithmetic on either side of the equality, and ignores comments beside lookup keys. - reads-source does not take a format! argument as the file name. - The base never-run hits are computed once per file. --- xtask/src/test_lint.rs | 253 +++++++++++++++++++++++++++++++++++------ 1 file changed, 217 insertions(+), 36 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f70326e737..0c7d793c0f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -327,7 +327,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_overrides = discover_path_overrides(root, Some(&base), &read_base); // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` // declaration can turn their tests off without a change to them. - let below: Vec = descendants(&present, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); + // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. + let seeds: Vec = changed.keys().cloned().collect(); + let below: Vec = descendants(&seeds, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); @@ -337,7 +339,15 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = |path: &str, src: &str, hit: &Hit| !already_off(&lint_file(path, src, &base_ctx), hit); + // The base's `never-run` hits, computed once per file on its first parent-attributed hit. + let base_off: RefCell>> = RefCell::new(HashMap::new()); + let newly_off = |path: &str, src: &str, hit: &Hit| { + let mut cache = base_off.borrow_mut(); + let off = cache.entry(path.to_owned()).or_insert_with(|| { + lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() + }); + !off.contains(&(hit.test.clone(), hit.line)) + }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); @@ -360,6 +370,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { /// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the /// test of `hit`. Tests of one name in different inline modules are told apart by their line. +#[cfg(test)] fn already_off(base: &[Hit], hit: &Hit) -> bool { base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) } @@ -570,15 +581,21 @@ fn parse_diff(diff: &str) -> BTreeMap>> { let mut current: Option = None; // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. let (mut header, mut new_file) = (false, false); + let mut old: Option = None; for line in diff.lines() { if line.starts_with("diff --git ") { - (header, new_file) = (true, false); + (header, new_file, old) = (true, false, None); } else if header && line.starts_with("new file mode") { new_file = true; + } else if let Some(path) = line.strip_prefix("--- ").filter(|_| header) { + old = patch_path(path).and_then(|p| p.strip_prefix("a/").map(str::to_owned)); } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); if let Some(p) = ¤t { out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } else if let Some(p) = old.take().filter(|_| path == "/dev/null") { + // A deleted file is kept, wholly changed: it may have been a route that loaded a module. + out.insert(p, None); } } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { header = false; @@ -3082,10 +3099,30 @@ fn reads_source_hits(file: &File) -> Vec { out } -/// The last string literal in a (whitespace-free) expression, quotes included. +/// The last string literal in a (whitespace-free) expression, quotes included. Inside a +/// `format!`-family call, an argument is not the file name, so the format string is returned +/// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. fn last_literal(arg: &str) -> Option<&str> { let close = arg.rfind('"')?; let open = arg[..close].rfind('"')?; + let b = arg.as_bytes(); + let mut depth = 0usize; + for i in (0..open).rev() { + match b[i] { + b')' => depth += 1, + b'(' if depth > 0 => depth -= 1, + b'(' => { + let head = arg[..i].strip_suffix('!').unwrap_or(""); + let name = head.rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).next().unwrap_or(""); + if matches!(name, "format" | "format_args") { + let first = arg[i + 1..].strip_prefix('"')?; + let end = first.find('"')?; + return Some(&arg[i + 1..i + 2 + end + 1]); + } + } + _ => {} + } + } Some(&arg[open..=close]) } @@ -3149,11 +3186,12 @@ fn first_arithmetic(op: &str) -> Option { } /// The whitespace-free source text of the arguments of the call an operand starts with, read from -/// the unmasked source so string literals keep their text. -fn head_args(f: &File, (from, to): (usize, usize)) -> Option> { +/// `code` (the source with comments blanked and string literals kept), so a comment beside a key +/// is not part of it. +fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option> { let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; let close = matching(&f.m, open)?; - Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(&f.src[a..b])).collect()) + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) } /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, @@ -3174,6 +3212,7 @@ fn key_like(arg: &str) -> bool { /// checks that two inputs agree, as a periodicity check does), and two reads at different entries /// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries. fn mirrors(v: &View) -> Vec { + let code = std::cell::OnceCell::new(); v.asserts .iter() .filter(|a| a.name.ends_with("_eq")) @@ -3183,16 +3222,18 @@ fn mirrors(v: &View) -> Vec { let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); let name = head_call(l)?; // Two calls compared as they are check that two inputs agree, which is a real check. + // Arithmetic on exactly one side, in either order, derives that side from the other call. let derived = match (first_arithmetic(l), first_arithmetic(r)) { - (_, None) => false, + (None, None) => false, (Some(i), Some(j)) => l[i..] != r[j..], - (None, Some(_)) => true, + _ => true, }; let last = name.rsplit("::").next().unwrap_or(name); if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) { return None; } - let (la, ra) = (head_args(v.file, lr)?, head_args(v.file, rr)?); + let code: &Vec = code.get_or_init(|| mask_parts(&String::from_utf8_lossy(v.file.src), true, false)); + let (la, ra) = (head_args(v.file, code, lr)?, head_args(v.file, code, rr)?); let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) @@ -3417,6 +3458,46 @@ fn windows_runs(path: &str) -> bool { path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs" } +/// The value of the contents of an ordinary Rust string literal: `\x`, `\u{…}` and the single-character +/// escapes decoded. An escape it cannot read is kept as written. +fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('0') => out.push('\0'), + Some(c @ ('\\' | '"' | '\'')) => out.push(c), + Some('x') => { + let hex: String = chars.by_ref().take(2).collect(); + match u8::from_str_radix(&hex, 16) { + Ok(v) if v < 0x80 => out.push(char::from(v)), + _ => out.push_str(&format!("\\x{hex}")), + } + } + Some('u') if chars.peek() == Some(&'{') => { + let body: String = chars.by_ref().take_while(|&c| c != '}').collect(); + match u32::from_str_radix(&body[1..].replace('_', ""), 16).ok().and_then(char::from_u32) { + Some(v) => out.push(v), + None => out.push_str(&format!("\\u{body}}}")), + } + } + Some(other) => { + out.push('\\'); + out.push(other); + } + None => out.push('\\'), + } + } + out +} + /// Whether a (whitespace-free) `cfg` predicate holds on `t`: `None` when it depends on something /// else (a feature, `debug_assertions`, an unknown key). fn cfg_value(p: &str, t: &Target) -> Option { @@ -3445,7 +3526,13 @@ fn cfg_value(p: &str, t: &Target) -> Option { 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('"'))); + // An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's + // contents are kept as written. + let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { + Some(raw) => (k, raw.trim_matches('#').trim_matches('"').to_owned()), + None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), + }); + let value = value.as_str(); match key { "test" => Some(true), "unix" => Some(t.family == "unix"), @@ -3598,7 +3685,7 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, 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';') || inline_mods(&m, at) != want.chain { + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, src.as_bytes(), at) != want.chain { continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); @@ -3661,7 +3748,7 @@ fn path_children(src: &str, parent: &str) -> Vec<(String, Vec)> { } 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 chain = inline_mods(&m, at); + let chain = inline_mods(&m, src.as_bytes(), at); out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); } } @@ -3675,18 +3762,20 @@ type Overrides = HashMap)>>; /// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources. fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { let with_path = match base { - Some(base) => git(root, &["grep", "-l", "-w", "path", base, "--", "*.rs"]), - None => git(root, &["grep", "--untracked", "-l", "-w", "path", "--", "*.rs"]), + // `-z` lists each path verbatim, NUL-terminated: without it Git quotes a non-ASCII path. + Some(base) => git(root, &["grep", "-z", "-l", "-w", "path", base, "--", "*.rs"]), + None => git(root, &["grep", "-z", "--untracked", "-l", "-w", "path", "--", "*.rs"]), } .unwrap_or_default(); listed_path_overrides(&with_path, base, read) } -/// Read paths from `git grep -l`, removing the revision prefix for a base-tree listing. +/// Read paths from `git grep -z -l` (NUL-separated), removing the revision prefix for a base-tree listing. fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option) -> Overrides { let prefix = base.map(|b| format!("{b}:")); let sources: Vec<(String, String)> = list - .lines() + .split('\0') + .filter(|p| !p.is_empty()) .filter_map(|p| match &prefix { Some(prefix) => p.strip_prefix(prefix), None => Some(p), @@ -3745,21 +3834,25 @@ fn join_path(base: &str, rel: &str) -> String { parts.join("/") } -/// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost -/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. -fn inline_mods(m: &[u8], at: usize) -> Vec { - m[..at] - .iter() - .enumerate() - .filter(|&(open, &c)| c == b'{' && matching(m, open).is_some_and(|close| close > at)) - .filter_map(|(open, _)| { - let head = m[..open].trim_ascii_end(); - let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); - let before = head[..head.len() - name].trim_ascii_end(); - (name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident)) - .then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()) - }) - .collect() +/// The directory segments of the inline `mod { … }` blocks around `at` in the masked text +/// `m` (`src` unmasked), outermost first. A `mod x;` inside them loads a file under their directory +/// instead of a sibling file. A block's directory is its name, or the value of a `#[path]` on it +/// (`#[path = "platform_impl"] mod platform { mod child; }` loads `platform_impl/child.rs`). +fn inline_mods(m: &[u8], src: &[u8], at: usize) -> Vec { + let mut dir = String::new(); + for open in (0..at).filter(|&open| m[open] == b'{' && matching(m, open).is_some_and(|close| close > at)) { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + if name == 0 || !before.ends_with(b"mod") || before[..before.len() - 3].last().copied().is_some_and(is_ident) { + continue; + } + let kw = before.len() - 3; + let item = m[..kw].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let seg = path_attr(m, src, item, kw).unwrap_or_else(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()); + dir = join_path(&dir, &seg); + } + dir.split('/').filter(|s| !s.is_empty()).map(str::to_owned).collect() } /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the @@ -3774,6 +3867,8 @@ fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option, override struct Gates { preds: Vec, sources: Vec<(String, Vec)>, + /// Whether a crate target loads the file through at least one route. + reached: bool, } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that @@ -3799,7 +3894,10 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over } let by_path = overrides.get(at).map_or(&[][..], Vec::as_slice); // A crate root runs independently of any module declarations that also load it. - let Some((name, mut candidates)) = module_parent(at) else { return gates }; + let Some((name, mut candidates)) = module_parent(at) else { + gates.reached = true; + return gates; + }; let name = name.to_owned(); let file = at.rsplit_once('/').map_or(at, |(_, f)| f); let Some(mut module_dir) = (if file == "mod.rs" { @@ -3807,15 +3905,23 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over } else { at.rsplit_once('/').map(|(d, _)| d.to_owned()) }) else { + gates.reached = true; return gates; }; let mut chain: Vec = vec![]; let mut found = vec![]; + // Whether a file that could declare the module exists: when none does, the module's parent is + // unknown and the file counts as reached. + let mut parent_read = false; 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. - found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + found.extend( + candidates + .iter() + .filter_map(|c| read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))), + ); if chain.is_empty() { for (c, inline) in by_path { // A candidate was read with no inline modules; another route through the @@ -3834,8 +3940,15 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over module_dir = up; } let mut each = vec![]; + gates.reached = found.is_empty() && !parent_read; for (parent, (mut preds, lines)) in found { let ancestors = module_gate(&parent, read, overrides, depth + 1); + // A parent that no crate target loads (a file left on disk after its `mod` line was + // removed) is not a route, so it cannot stand in for an ungated one. + if !ancestors.reached { + continue; + } + gates.reached = true; preds.extend(ancestors.preds); gates.sources.push((parent, lines)); gates.sources.extend(ancestors.sources); @@ -5537,12 +5650,16 @@ mod tests { assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n"; assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry"); + let swapped = "#[test]\nfn t() {\n assert_eq!(scale(p, 1.0) * 2.0, scale(p, 2.0));\n}\n"; + assert_eq!(only("mirror", swapped), [(3, "mirror")], "the arithmetic on the left side"); } #[test] fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() { let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n"; assert_eq!(only("mirror", order), [], "positions of two entries in one list"); + let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", commented), [], "a comment beside a key"); let offset = "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); @@ -5961,8 +6078,8 @@ mod tests { let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)]; let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); - let base_overrides = listed_path_overrides(&format!("before:{a}\n"), Some("before"), &read_base); - let work_overrides = listed_path_overrides(&format!("{b}\n"), None, &read_work); + let base_overrides = listed_path_overrides(&format!("before:{a}\0"), Some("before"), &read_base); + let work_overrides = listed_path_overrides(&format!("{b}\0"), None, &read_work); let paths = [child.to_owned()]; let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() }; @@ -5983,6 +6100,65 @@ mod tests { assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it"); } + #[test] + fn a_detached_module_is_not_an_ungated_route() { + let decl = "#[path = \"shared.rs\"]\nmod s;\n"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let shared = "crates/x/src/shared.rs".to_owned(); + for (lib, off) in [("#[cfg(target_os = \"macos\")]\nmod b;\n", true), ("mod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n", false)] { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", decl), ("crates/x/src/b.rs", decl)].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 ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let want: &[(usize, &str)] = if off { &[(2, "never-run")] } else { &[] }; + assert_eq!(hits_in(&shared, test, &ctx), want, "{lib}"); + } + } + + #[test] + fn a_path_on_an_inline_module_sets_its_directory() { + let lib = "#[cfg(target_os = \"macos\")]\n#[path = \"platform_impl\"]\nmod platform {\n mod child;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/platform_impl/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..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 cfg_values_compare_decoded_strings() { + let linux = &CI_TARGETS[0]; + assert_eq!(cfg_value("target_os=\"\\x6cinux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + } + + #[test] + fn path_override_listings_are_nul_separated() { + let files: HashMap<&str, &str> = + [("crates/x/src/a.rs", "#[path = \"s.rs\"]\nmod s;\n"), ("crates/x/src/caf\u{e9}.rs", "#[path = \"t.rs\"]\nmod t;\n")] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let got = listed_path_overrides("base:crates/x/src/a.rs\0base:crates/x/src/caf\u{e9}.rs\0", Some("base"), &read); + assert!(got.contains_key("crates/x/src/s.rs"), "{got:?}"); + assert!(got.contains_key("crates/x/src/t.rs"), "{got:?}"); + } + + #[test] + fn deleted_files_are_kept_as_changed() { + let diff = "diff --git a/crates/x/src/bin/tool.rs b/crates/x/src/bin/tool.rs\ndeleted file mode 100644\n--- a/crates/x/src/bin/tool.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-#[path = \"../shared.rs\"]\n-mod shared;\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/src/bin/tool.rs"), Some(&None), "{got:?}"); + let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); + let seeds: Vec = got.keys().cloned().collect(); + let files = ["crates/x/src/shared.rs".to_owned()]; + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base), ["crates/x/src/shared.rs"]); + } + #[test] fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() { let files: Vec = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"] @@ -6053,6 +6229,11 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read"); + let format_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", format_rs), [(3, "reads-source")], "a format string that names a .rs file"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); From 186e6db9bae18223917fe6cbb24dccbaaa68f864 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:34:08 -0800 Subject: [PATCH 08/10] xtask: test-lint reads renames, cfg_attr paths, casts and arm bindings - changed mode diffs with --no-renames, so an exact rename lists the old path as deleted and the new path as added, and both seed the route walk. - census reads a cast of the loop binding (k as usize) as the entry, and no longer reads a field or path segment named like it (config.k, m::k). - reads-source takes the file name from the final .join(...) component; a final component that is not a literal is an unknown file. - mirror keeps whitespace inside string literals when it compares lookup keys, so "A B" and "AB" are different entries. - fixture-only resolves a name bound by a match arm's pattern to that arm, not to an outer let; a guard still reads the outer binding. - never-run follows #[cfg_attr(, path = "...")] overrides: the selected path is loaded where the condition holds, and the default path elsewhere. - never-run treats tests//mod.rs as loaded by the test targets beside it, like a crate root. - exact-pixel no longer reports two rects compared by their difference (a.width() - b.width()). --- xtask/src/test_lint.rs | 266 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 245 insertions(+), 21 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 0c7d793c0f..0e3baa802e 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -343,9 +343,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_off: RefCell>> = RefCell::new(HashMap::new()); let newly_off = |path: &str, src: &str, hit: &Hit| { let mut cache = base_off.borrow_mut(); - let off = cache.entry(path.to_owned()).or_insert_with(|| { - lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() - }); + let off = cache + .entry(path.to_owned()) + .or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()); !off.contains(&(hit.test.clone(), hit.line)) }; let (mut counted, mut older) = (vec![], 0usize); @@ -560,6 +560,8 @@ fn changed_lines(root: &Path, base: &str) -> Result bool { }) } -/// Whether `s` contains the identifier `var` as a whole word. +/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or +/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`). fn reads_ident(s: &str, var: &str) -> bool { + const PRIMITIVES: &[&str] = + &["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"]; let b = s.as_bytes(); + let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident); !var.is_empty() && s.match_indices(var).any(|(at, _)| { let end = at + var.len(); - !(at > 0 && is_ident(b[at - 1])) && !b.get(end).copied().is_some_and(is_ident) + let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); + let path = at > 1 && &b[at - 2..at] == b"::"; + let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends))); + !(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast) }) } @@ -3084,8 +3093,12 @@ fn reads_source_hits(file: &File) -> Vec { let rs = match word { b"ends_with" => literal == "\".rs\"", // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, - // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. A final + // component that is not a literal (`.join(name)`) names an unknown file. + b"read_to_string" => { + let last = arg.rfind(".join(").and_then(|at| matching(arg.as_bytes(), at + 5).map(|close| &arg[at + 6..close])); + last_literal(last.unwrap_or(&arg)).is_some_and(|l| l.ends_with(".rs\"")) + } _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3191,7 +3204,35 @@ fn first_arithmetic(op: &str) -> Option { fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option> { let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; let close = matching(&f.m, open)?; - Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm_outside_literals(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) +} + +/// [`norm`] that keeps whitespace inside string literals: `"A B"` and `"AB"` are different keys. +fn norm_outside_literals(b: &[u8]) -> String { + let mut out = Vec::with_capacity(b.len()); + let mut in_str = false; + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + out.push(c); + if c == b'\\' { + if let Some(&n) = b.get(i + 1) { + out.push(n); + i += 1; + } + } else if c == b'"' { + in_str = false; + } + } else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) { + in_str = true; + out.push(c); + } else if !c.is_ascii_whitespace() { + out.push(c); + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() } /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, @@ -3321,13 +3362,67 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option l => found.map(|(init, _)| init), (Some(_), _) => Some(None), (None, _) => found.map(|(init, _)| init), } } +/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body +/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not. +fn arm_binding(body: &[u8], name: &str, before: usize) -> Option { + let mut found = None; + for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") { + // The pattern runs back to the `{` or `,` that opens the arm. + let mut depth = 0usize; + let mut start = arrow; + while start > 0 { + match body[start - 1] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => break, + b'(' | b'[' | b'{' => depth -= 1, + b',' if depth == 0 => break, + _ => {} + } + start -= 1; + } + // A guard (`Some(x) if x == n`) reads names; it does not bind them. + let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); + let pattern = norm(&body[start..guard]); + if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + continue; + } + // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. + let from = skip_ws(body, arrow + 2); + let end = match body.get(from) { + Some(b'{') => matching(body, from), + _ => { + let mut depth = 0usize; + (from..body.len()).find(|&i| match body[i] { + b'(' | b'[' | b'{' => { + depth += 1; + false + } + b')' | b']' | b'}' if depth == 0 => true, + b')' | b']' | b'}' => { + depth -= 1; + false + } + b',' => depth == 0, + _ => false, + }) + } + }; + if end.is_some_and(|end| before < end) { + found = Some(arrow); + } + } + found +} + /// [`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; @@ -3644,13 +3739,20 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { /// The module name a file declares and the files that may declare it with `mod ;`, or `None` /// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or -/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `examples` beside a crate's `src`, or a file directly in `src/bin`), and for a `mod.rs` one +/// directory below those, which their roots load (`tests/common/mod.rs`). A `tests` directory under /// `src` holds modules, not test targets. fn module_parent(path: &str) -> Option<(&str, Vec)> { let (dir, file) = path.rsplit_once('/')?; - let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); - let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin"); - if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { + let is_root_dir = |dir: &str| { + let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); + ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin") + }; + let root_dir = is_root_dir(dir); + // `tests/common/mod.rs` is loaded by the target roots beside it (`tests/smoke.rs` with + // `mod common;`), which are not listed here, so it counts as reached like a root. + let beside_roots = file == "mod.rs" && dir.rsplit_once('/').is_some_and(|(up, _)| is_root_dir(up)); + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") || beside_roots { return None; } let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; @@ -3689,22 +3791,38 @@ 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) => override_path(dir, file, mod_rs, want.chain, &rel) == want.path, + // A `cfg_attr` override loads its path where its condition holds, and the default (or a + // plain `#[path]`) elsewhere. + let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); + let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; + let fallback = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => overrides_here(&rel), None => { &m[start..end] == want.name.as_bytes() && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } }; - if !loads { - continue; - } + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let route = match (fallback, selected.is_empty(), conditional.is_empty()) { + (true, _, true) => None, + (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::>().join(","))), + (true, false, false) => { + let others: Vec<&str> = conditional.iter().filter(|(_, rel)| !overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + (!others.is_empty()).then(|| format!("not(any({}))", others.join(","))) + } + (false, true, _) => continue, + (false, false, _) => Some(format!("any({})", selected.join(","))), + }; // 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)); // Every line of a multiline attribute counts: an edit inside its predicate changes it. 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(route) = route { + preds.push(route); + at_lines.extend(lines.of(skip_ws(&m, item))..=lines.of(at)); + } for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); at_lines.extend(lines.of(a)..=lines.of(e)); @@ -3747,7 +3865,9 @@ fn path_children(src: &str, parent: &str) -> Vec<(String, Vec)> { 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 rels = + path_attr(&m, src.as_bytes(), item, at).into_iter().chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, r)| r)); + for rel in rels { let chain = inline_mods(&m, src.as_bytes(), at); out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); } @@ -3819,6 +3939,31 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { }) } +/// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and +/// path. +fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { + let mut out = vec![]; + for at in words(m, b"cfg_attr", from, to) { + if !m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) { + continue; + } + 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 cuts = top_level_at(&text, ","); + let Some(&first) = cuts.first() else { continue }; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(rel) = arg.strip_prefix("path=\"").and_then(|r| r.strip_suffix('"')) { + out.push((text[..first].to_owned(), rel.to_owned())); + } + start = cut + 1; + } + } + 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(); @@ -4028,8 +4173,14 @@ 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 and its parts make up the whole operand: `a.width() - b.width()` compares two + // rects, not one with a number. + let mut rest = &op[after..]; + while let Some(r) = RECT_PARTS.iter().chain(&[".x", ".y"]).find_map(|p| rest.strip_prefix(p)) { + rest = r; + } + let lead = op[..i].trim_start_matches(['&', '*', '(']); + if rest.trim_start_matches(')').is_empty() && !lead.contains(['+', '-', '*', '/', '%', ',']) { return true; } } @@ -4112,6 +4263,13 @@ mod tests { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n"; assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); + let cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(k as usize), k);\n }\n}\n"; + assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); + let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; + assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let field = + "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; + assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; 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"; @@ -5660,6 +5818,10 @@ mod tests { assert_eq!(only("mirror", order), [], "positions of two entries in one list"); let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; + assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); + let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; + assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not"); let offset = "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); @@ -5678,6 +5840,10 @@ mod tests { assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", arm), [], "a match arm binds its own n"); + let outer = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) if m == n => assert_eq!(n, 0),\n _ => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", outer), [(2, "fixture-only")], "a guard reads the outer n"); let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; @@ -5921,6 +6087,18 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets"); assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src"); + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/common/mod.rs\"]\nmod common;\n"), + ("crates/x/tests/smoke.rs", "mod common;\n"), + ("crates/x/tests/common/mod.rs", ""), + ] + .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 shared = "crates/x/tests/common/mod.rs".to_owned(); + let shared_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &shared_ctx), [], "a test target beside it loads the shared module on every target"); } #[test] @@ -5955,6 +6133,45 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn never_run_follows_a_path_selected_by_cfg_attr() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"live.rs\")]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n"), + ("crates/x/src/live.rs", ""), + ("crates/x/src/platform.rs", ""), + ] + .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 test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let live = "crates/x/src/live.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..ctx() }; + assert_eq!(hits_in(&live, test, &ctx), [], "Linux loads live.rs through the cfg_attr path"); + let platform = "crates/x/src/platform.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides); + assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere"); + } + + #[test] + fn changed_lines_lists_both_paths_of_an_exact_rename() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-rename-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n"; + std::fs::write(root.join("crates/x/src/bin/tool.rs"), src).unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::create_dir_all(root.join("crates/x/src/disabled")).unwrap(); + std::fs::rename(root.join("crates/x/src/bin/tool.rs"), root.join("crates/x/src/disabled/tool.rs")).unwrap(); + git(&root, &["add", "-A"]).unwrap(); + let changed = changed_lines(&root, &base).unwrap(); + assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted"); + assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn never_run_joins_inline_and_override_routes() { for (lib, child) in [ @@ -6208,6 +6425,8 @@ mod tests { assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(left_rect.width() - right_rect.width(), 0.0);"), [], "two rects compared by their difference"); + assert_eq!(px("assert_eq!(left_rect.width(), 120.0);"), [(4, "exact-pixel")]); assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); @@ -6229,6 +6448,11 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let unknown = "#[test]\nfn t() {\n let name = \"data.json\";\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(name)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", unknown), [], "a final component that is not a literal"); + let joined = + "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read"); let format_rs = From a7654fc63850be4ca7a0c42f05acbb0077e6aa2a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:17:26 -0800 Subject: [PATCH 09/10] xtask: test-lint matches base tests by place and keeps route kinds apart - never-run in changed mode lints the file as it was at the base and matches a test by its name and its place among tests of that name, so a test that was already off is not counted again when lines move. - A file reached by name inherits only the gates of named declarations, and one reached through #[path] only those of #[path] declarations. - The changed-file walk also reads the base child declarations of a #[path]-loaded file, so a removed `mod child;` still reaches the child. - reads-source classifies the outer path step, not a join nested in its argument. - mirror treats complete raw string literals as keys. - A raw cfg value keeps the quotes inside it (r#""unix""# is not unix). - census keeps word boundaries, so `k as usize` reads `k` and the local `kasusize` does not. - fixture-only finds a for loop's `in` across line breaks. --- xtask/src/test_lint.rs | 243 +++++++++++++++++++++++++++++++++-------- 1 file changed, 197 insertions(+), 46 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index fe0090fa33..40ac3b2f25 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -330,7 +330,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. let seeds: Vec = changed.keys().cloned().collect(); let below: Vec = - descendants(&seeds, &files, &overrides, &base_overrides, &read_work).into_iter().filter(|p| !changed.contains_key(p)).collect(); + descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); @@ -340,14 +340,17 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - // The base's `never-run` hits, computed once per file on its first parent-attributed hit. - let base_off: RefCell>> = RefCell::new(HashMap::new()); + // The base's `never-run` hits on the file as it was at the base (the current source when the + // file is new or moved), computed once per file on its first parent-attributed hit. + let base_off: RefCell)>> = RefCell::new(HashMap::new()); let newly_off = |path: &str, src: &str, hit: &Hit| { let mut cache = base_off.borrow_mut(); - let off = cache - .entry(path.to_owned()) - .or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()); - !off.contains(&(hit.test.clone(), hit.line)) + let (base_src, off) = cache.entry(path.to_owned()).or_insert_with(|| { + let base_src = read_base(path).unwrap_or_else(|| src.to_owned()); + let off = lint_file(path, &base_src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + (base_src, off) + }); + !already_off(off, base_src, src, hit) }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { @@ -369,11 +372,21 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { finish(&counted, older, present.len(), &base) } -/// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the -/// test of `hit`. Tests of one name in different inline modules are told apart by their line. -#[cfg(test)] -fn already_off(base: &[Hit], hit: &Hit) -> bool { - base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +/// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test +/// of `hit` in `src`. A test is matched by its name and its place among the tests of that name, so +/// lines that moved still match and tests of one name in different inline modules stay apart. +fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { + let place = test_place(src, &hit.test, hit.line); + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match place { + Some(place) => test_place(base_src, &h.test, h.line) == Some(place), + None => h.line == hit.line, + }) +} + +/// The index of the test `name` whose `fn` is on `line` among the tests of that name in `src`. +fn test_place(src: &str, name: &str, line: usize) -> Option { + let lines = Lines::new(src); + tests_in(&mask(src)).iter().filter(|t| t.name == name).position(|t| lines.of(t.fn_at) == line) } /// The directory holding the modules that the file `p` declares by name: its own directory for @@ -387,13 +400,15 @@ fn module_dir(p: &str) -> String { /// The files of `files` that the files `start` load, directly or through modules in between: the /// files under their module directories and the files their current or base `#[path]` declarations load. /// A file loaded through `#[path]` also loads the modules it declares by name from its own directory -/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read`. +/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read` and, for the +/// declarations a change removed, through `read_base`. fn descendants( start: &[String], files: &[String], overrides: &Overrides, base_overrides: &Overrides, read: &dyn Fn(&str) -> Option, + read_base: &dyn Fn(&str) -> Option, ) -> Vec { let mut seen: BTreeSet = start.iter().cloned().collect(); let mut frontier: Vec = start.to_vec(); @@ -404,7 +419,12 @@ fn descendants( return vec![]; } let dir = p.rsplit_once('/').map_or("", |(d, _)| d); - read(p).map_or(vec![], |src| declared_names(&src).into_iter().flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]).collect()) + [read(p), read_base(p)] + .into_iter() + .flatten() + .flat_map(|src| declared_names(&src)) + .flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]) + .collect() }; let dirs: Vec = frontier.iter().map(|p| module_dir(p)).chain(frontier.iter().flat_map(beside)).collect(); let next: Vec = files @@ -973,6 +993,25 @@ fn norm(b: &[u8]) -> String { String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() } +/// [`norm`], except that whitespace between two identifier characters becomes one space, so +/// `k as usize` stays three words and `kasusize` stays one. Removing the spaces gives [`norm`]. +fn norm_words(b: &[u8]) -> String { + let mut out = vec![]; + let mut gap = false; + for &c in b { + if c.is_ascii_whitespace() { + gap = true; + continue; + } + if gap && is_ident(c) && out.last().copied().is_some_and(is_ident) { + out.push(b' '); + } + gap = false; + out.push(c); + } + String::from_utf8_lossy(&out).into_owned() +} + /// Line starts, to turn byte offsets into 1-based lines. struct Lines(Vec); @@ -1545,7 +1584,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { helpers_in(from, to).is_empty() && !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)) + && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::>(), var)) }; for at in words(m, b"for", v.t.open, v.t.close) { let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue }; @@ -1788,10 +1827,10 @@ fn weak_predicate_within(pred: &str, depth: usize) -> bool { } /// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares -/// a lookup or parse with the entry itself. +/// a lookup or parse with the entry itself. `args` are written as [`norm_words`] gives them. fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { match guard_arg_count(name) { - 1 => args.first().is_some_and(|a| weak_predicate(a)), + 1 => args.first().is_some_and(|a| weak_predicate(&a.replace(' ', ""))), 2 if name.ends_with("_ne") => false, 2 => match args { [a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)), @@ -1801,7 +1840,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { } } -/// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole +/// 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 @@ -1826,20 +1865,16 @@ fn round_trip_call(op: &str, var: &str) -> bool { }) } -/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or -/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`). +/// Whether `s`, written as [`norm_words`] gives it, reads the binding `var`: a whole word that is not +/// a field or path segment (`config.k`, `m::k`), alone or cast (`k as usize`). `kasusize` is one word. fn reads_ident(s: &str, var: &str) -> bool { - const PRIMITIVES: &[&str] = - &["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"]; let b = s.as_bytes(); - let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident); !var.is_empty() && s.match_indices(var).any(|(at, _)| { let end = at + var.len(); let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); let path = at > 1 && &b[at - 2..at] == b"::"; - let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends))); - !(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast) + !(at > 0 && is_ident(b[at - 1])) && !field && !path && !b.get(end).copied().is_some_and(is_ident) }) } @@ -3137,10 +3172,11 @@ fn reads_source_hits(file: &File) -> Vec { // The final path step names the file read: the last literal of `root.join("src/lib.rs")` // or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the // extension of a final `.with_extension("json")`. A final step whose argument is not a - // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. + // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on + // the outer path count: a `.join` inside another step's argument does not. b"read_to_string" => { let step = |s: &'static str| { - arg.rfind(s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + rfind_outer(&arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) }; match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { Some((_, ".with_extension(", ext)) => ext.trim_start_matches('r').trim_matches('#') == "\"rs\"", @@ -3161,6 +3197,35 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// The offset of the last `pat` in `expr` outside every bracket and string literal. +fn rfind_outer(expr: &str, pat: &str) -> Option { + let b = expr.as_bytes(); + let (mut depth, mut in_str, mut found) = (0usize, false, None); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + if depth == 0 && b[i..].starts_with(pat.as_bytes()) { + found = Some(i); + } + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + _ => {} + } + } + i += 1; + } + found +} + /// The last string literal in a (whitespace-free) expression, quotes included. Inside a /// `format!`-family call, an argument is not the file name, so the format string is returned /// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. @@ -3284,12 +3349,22 @@ fn norm_outside_literals(b: &[u8]) -> String { String::from_utf8_lossy(&out).into_owned() } +/// The contents of a complete raw string literal written after its `r`: `"a"` and `#"a"#` give `a`, +/// and `#""a""#` gives `"a"`. `None` when `s` is not one whole literal. +fn raw_literal_body(s: &str) -> Option<&str> { + let hashes = s.len() - s.trim_start_matches('#').len(); + let close = format!("\"{}", "#".repeat(hashes)); + let body = s[hashes..].strip_prefix('"')?.strip_suffix(close.as_str())?; + (!body.contains(close.as_str())).then_some(body) +} + /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, /// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). fn key_like(arg: &str) -> bool { let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); match arg.as_bytes().first() { Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), None => false, @@ -3406,9 +3481,9 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option { // An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's // contents are kept as written. let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { - Some(raw) => (k, raw.trim_matches('#').trim_matches('"').to_owned()), + Some(raw) => (k, raw_literal_body(raw).unwrap_or(raw).to_owned()), None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), }); let value = value.as_str(); @@ -3960,8 +4035,9 @@ struct Loaded<'a> { /// items, inline modules and file around them, with the 1-based lines of those declarations and /// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None` /// when `src` loads no such file. `owns_dir` reads `parent` as loaded through `#[path]`, which -/// declares its modules in its own directory, as a `mod.rs` or a crate root does. -fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Option<(Vec, Vec)> { +/// declares its modules in its own directory, as a `mod.rs` or a crate root does. `via` keeps only +/// the declarations that load `want` by name (`Named`) or through `#[path]` (`Path`). +fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool, via: Via) -> Option<(Vec, Vec)> { let m = mask(src); let lines = Lines::new(src); let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); @@ -3993,13 +4069,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Opti let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; let fallback = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => overrides_here(&rel), + Some(rel) => via != Via::Named && overrides_here(&rel), None => { - &m[start..end] == want.name.as_bytes() + via != Via::Path + && &m[start..end] == want.name.as_bytes() && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } }; - let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| via != Via::Named && overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); let route = match (fallback, selected.is_empty(), conditional.is_empty()) { (true, _, true) => None, (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::>().join(","))), @@ -4294,7 +4371,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over // can both load it): its tests are off only when every one of them leaves them out. if via != Via::Path { found.extend(candidates.iter().filter_map(|c| { - read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, named(c))) + read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, named(c))) })); } if chain.is_empty() { @@ -4305,7 +4382,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over continue; } let want = Loaded { path: at, name: &name, chain: inline }; - found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, Via::Any))); + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, Via::Any))); } // A file loaded through `#[path]` owns its directory like a `mod.rs`: its `mod child;` // loads the `child.rs` beside it (`impl/platform.rs` loads `impl/child.rs`). @@ -4313,7 +4390,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over .keys() .filter(|k| via != Via::Path && k.as_str() != at && !owns_its_dir(k) && k.rsplit_once('/').is_some_and(|(d, _)| d == module_dir)); for owner in path_loaded { - found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true)).map(|f| (owner.clone(), f, Via::Path))); + found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true, via)).map(|f| (owner.clone(), f, Via::Path))); } } if via == Via::Path || beside_roots(at) { @@ -4519,6 +4596,8 @@ mod tests { assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let one_word = "#[test]\nfn t() {\n let kasusize = 3;\n for k in KEYS {\n assert_eq!(lookup(kasusize), k);\n }\n}\n"; + assert_eq!(census(one_word), [], "a fixed local spelled like a cast of the entry"); let field = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); @@ -6084,6 +6163,8 @@ mod tests { assert_eq!(only("mirror", order), [], "positions of two entries in one list"); let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let raw = "#[test]\nfn t() {\n assert_eq!(at(r#\"B\"#), at(r#\"A\"#) + 1);\n assert_eq!(at(r\"B\"), at(r\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", raw), [], "raw string keys"); let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; @@ -6217,7 +6298,7 @@ mod tests { #[test] fn never_run_follows_the_cfg_around_the_mod_declaration() { let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; - let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false).map(|(p, _)| p); + let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false, Via::Any).map(|(p, _)| p); let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; @@ -6339,10 +6420,25 @@ mod tests { let base = lint_file(path, src, &ctx()); let now = lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); - let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, h)).map(|h| h.line).collect(); + let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.line).collect(); assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); } + #[test] + fn a_test_off_at_the_base_is_matched_in_the_base_source() { + // At the base an inline module gate turned the test off; the change removes that gate and + // gates the parent instead, which also moves the test up a line. + let path = "crates/x/src/child.rs"; + let before = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<&str> = + now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.test.as_str()).collect(); + assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); + } + #[test] fn never_run_follows_a_tests_module_directory_under_src() { let files: HashMap<&str, &str> = @@ -6430,7 +6526,56 @@ mod tests { assert_eq!(hits_in(&below, test, &ctx), [], "the path-loaded file does not load impl/platform/child.rs"); let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; let all: Vec = files.keys().map(|p| (*p).to_owned()).collect(); - assert!(descendants(&seeds, &all, &overrides, &Overrides::new(), &read).contains(&child), "a change to platform.rs reaches child.rs"); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child), + "a change to platform.rs reaches child.rs" + ); + } + + #[test] + fn a_named_route_takes_only_the_gates_of_named_declarations() { + // `parent.rs` is loaded by name on macOS and through `#[path]` on Linux. Only the named route + // loads `parent/child.rs`; the `#[path]` route loads `child.rs` beside `parent.rs`. + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n#[cfg(target_os = \"linux\")]\n#[path = \"parent.rs\"]\nmod p2;\n"), + ("crates/x/src/parent.rs", "mod child;\n"), + ("crates/x/src/parent/child.rs", ""), + ("crates/x/src/child.rs", ""), + ] + .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 test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + for (child, expected) in [("crates/x/src/parent/child.rs", vec![(2, "never-run")]), ("crates/x/src/child.rs", vec![])] { + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(child, test, &ctx), expected, "{child}"); + } + } + + #[test] + fn a_removed_child_declaration_still_reaches_the_child() { + let work: HashMap<&str, &str> = [ + ( + "crates/x/src/lib.rs", + "#[path = \"impl/platform.rs\"]\nmod platform;\n#[cfg(target_os = \"macos\")]\n#[path = \"impl/child.rs\"]\nmod child;\n", + ), + ("crates/x/src/impl/platform.rs", ""), + ("crates/x/src/impl/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| work.get(p).map(|s| (*s).to_owned()); + let read_base = |p: &str| if p == "crates/x/src/impl/platform.rs" { Some("mod child;\n".to_owned()) } else { read(p) }; + let overrides = path_overrides(work.iter().map(|(p, s)| (*p, *s))); + let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; + let all: Vec = work.keys().map(|p| (*p).to_owned()).collect(); + let child = "crates/x/src/impl/child.rs".to_owned(); + assert!(!descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child)); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &read_base).contains(&child), + "the base `mod child;` that the change removed still leads to child.rs" + ); } #[test] @@ -6594,7 +6739,7 @@ mod tests { let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::>(); assert!( - descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None).contains(&child.to_owned()), + descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None, &|_| None).contains(&child.to_owned()), "the removed route still reaches the shared tests" ); for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { @@ -6602,7 +6747,7 @@ mod tests { assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); assert!(parent_changed, "deletions and shifted lines still change a base route"); - assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), &hit), ran); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), test, test, &hit), ran); assert!( route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), "a base route parent counts even without inherited predicates" @@ -6683,6 +6828,8 @@ mod tests { assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + assert_eq!(cfg_value("target_family=r#\"unix\"#", linux), Some(true)); + assert_eq!(cfg_value("target_family=r#\"\"unix\"\"#", linux), Some(false), "quotes inside a raw string are part of the value"); } #[test] @@ -6705,7 +6852,7 @@ mod tests { let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); let seeds: Vec = got.keys().cloned().collect(); let files = ["crates/x/src/shared.rs".to_owned()]; - assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None), ["crates/x/src/shared.rs"]); + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None, &|_| None), ["crates/x/src/shared.rs"]); } #[test] @@ -6720,7 +6867,7 @@ mod tests { ]; let overrides = path_overrides(sources); let read = |p: &str| sources.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); - let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read, &|_| None); assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); } @@ -6817,6 +6964,8 @@ mod tests { let joined = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); + let nested = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(if root.join(\"config.rs\").exists() { \"a.json\" } else { \"b.json\" })).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", nested), [], "a join inside the outer join's argument"); let extension = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(\"json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", extension), [], "a final extension that is not rs"); let to_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"lib.txt\").with_extension(\"rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; @@ -6856,6 +7005,8 @@ mod tests { fn a_for_binding_shadows_the_outer_one_in_its_body() { let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n"; assert_eq!(only("fixture-only", looped), []); + let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); } From e19e96f810de7342f8c5bd3e6d693a9ee9a83f6e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 17:06:07 -0800 Subject: [PATCH 10/10] xtask: test-lint reads base roots, module scopes and whole literals - Changed mode builds the base's target-root routes from the base tree, so a deleted tests/.rs still counts as loading tests/common/mod.rs. - A base test is matched by its name, its inline modules and its place among same-named tests in them, so removing `mod a` does not let `a::t` hide a newly off `b::t`. - reads-source looks through grouping around the read path and names a file only from a complete literal, a format!/concat! call or Path::new/PathBuf::from; `"data.json".trim_end_matches(".rs")` no longer counts as a .rs file. - mirror keys keep a raw literal whole up to its own delimiter, and a key must be one complete string literal. - for, if let, while let, let and match patterns keep word boundaries (`mut n` binds `n`), and a struct pattern's braces are not taken as the loop or if-let body. - #[path] and cfg_attr path values accept raw string literals. --- xtask/src/test_lint.rs | 320 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 289 insertions(+), 31 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 40ac3b2f25..449885209f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -293,6 +293,12 @@ fn read_small(root: &Path, path: &str) -> Option { (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } +/// The scanned files of the tree at `base`, or `None` when Git cannot list it. +fn base_files(root: &Path, base: &str) -> Option> { + let list = git(root, &["ls-tree", "-r", "-z", "--name-only", base]).ok()?; + Some(list.split('\0').filter(|p| !p.is_empty() && is_scanned(p)).map(str::to_owned).collect()) +} + /// Cache successful and missing reads for one source tree. fn cached_read(read: impl Fn(&str) -> Option) -> impl Fn(&str) -> Option { let cache = RefCell::new(HashMap::>::new()); @@ -324,7 +330,10 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // instead of reading the tree, and the target roots beside a shared `tests//mod.rs`. let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files); let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); - let base_overrides = with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &files); + // The base's target roots come from the base tree: a root the change deleted still loaded the + // shared module beside it. + let base_overrides = + with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &base_files(root, &base).unwrap_or_else(|| files.clone())); // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` // declaration can turn their tests off without a change to them. // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. @@ -373,20 +382,49 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } /// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test -/// of `hit` in `src`. A test is matched by its name and its place among the tests of that name, so -/// lines that moved still match and tests of one name in different inline modules stay apart. +/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place +/// among the tests of that name in those modules, so lines that moved still match and tests of one +/// name in different inline modules stay apart, even when a change removes one of the modules. fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { let place = test_place(src, &hit.test, hit.line); - base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match place { - Some(place) => test_place(base_src, &h.test, h.line) == Some(place), + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match &place { + Some(place) => test_place(base_src, &h.test, h.line).as_ref() == Some(place), None => h.line == hit.line, }) } -/// The index of the test `name` whose `fn` is on `line` among the tests of that name in `src`. -fn test_place(src: &str, name: &str, line: usize) -> Option { +/// The inline modules around the test `name` whose `fn` is on `line` in `src` (outermost first), +/// and its index among the tests of that name in the same modules. +fn test_place(src: &str, name: &str, line: usize) -> Option<(Vec, usize)> { let lines = Lines::new(src); - tests_in(&mask(src)).iter().filter(|t| t.name == name).position(|t| lines.of(t.fn_at) == line) + let m = mask(src); + let named: Vec<(Vec, usize)> = + tests_in(&m).iter().filter(|t| t.name == name).map(|t| (inline_modules(&m, t.fn_at), lines.of(t.fn_at))).collect(); + let (scope, _) = named.iter().find(|(_, l)| *l == line)?; + let index = named.iter().filter(|(s, _)| s == scope).position(|(_, l)| *l == line)?; + Some((scope.clone(), index)) +} + +/// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost +/// first. +fn inline_modules(m: &[u8], at: usize) -> Vec { + let mut open: Vec> = vec![]; + for (i, &c) in m.iter().enumerate().take(at) { + match c { + b'{' => { + let head = m[..i].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + let keyword = name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident); + open.push(keyword.then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned())); + } + b'}' => { + open.pop(); + } + _ => {} + } + } + open.into_iter().flatten().collect() } /// The directory holding the modules that the file `p` declares by name: its own directory for @@ -3175,13 +3213,15 @@ fn reads_source_hits(file: &File) -> Vec { // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on // the outer path count: a `.join` inside another step's argument does not. b"read_to_string" => { + // Grouping around the whole argument hides no step: `(root.join(…))`. + let arg = ungroup(arg.strip_suffix(',').unwrap_or(&arg)); let step = |s: &'static str| { - rfind_outer(&arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + rfind_outer(arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) }; match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { - Some((_, ".with_extension(", ext)) => ext.trim_start_matches('r').trim_matches('#') == "\"rs\"", - Some((_, _, last)) => last_literal(last).is_some_and(|l| l.ends_with(".rs\"")), - None => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + Some((_, ".with_extension(", ext)) => file_literal(ext) == Some("\"rs\""), + Some((_, _, last)) => file_literal(last).is_some_and(|l| l.ends_with(".rs\"")), + None => file_literal(arg).is_some_and(|l| l.ends_with(".rs\"")), } } _ => arg.trim_end_matches('#').ends_with(".rs\""), @@ -3226,6 +3266,81 @@ fn rfind_outer(expr: &str, pat: &str) -> Option { found } +/// The offset of the `)` that closes the `(` at `open` in `expr`, skipping string literals. +fn outer_close(expr: &str, open: usize) -> Option { + let b = expr.as_bytes(); + let (mut depth, mut in_str) = (0usize, false); + let mut i = open; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(i); + } + } + _ => {} + } + } + i += 1; + } + None +} + +/// A whitespace-free expression without the references and parentheses around all of it: +/// `&(root.join("a"))` gives `root.join("a")`. +fn ungroup(mut expr: &str) -> &str { + loop { + let inner = expr.trim_start_matches('&'); + match inner.strip_prefix('(') { + Some(_) if outer_close(inner, 0) == Some(inner.len() - 1) => expr = &inner[1..inner.len() - 1], + _ => return inner, + } + } +} + +/// `s` when it is one complete ordinary string literal (`"a.rs"`, not `"a"+"b"`), or the body of +/// one complete raw string literal in quotes (`r#"a.rs"#` gives `"a.rs"`). +fn whole_literal(s: &str) -> Option<&str> { + if s.starts_with('"') { + return (s.len() > 1 && string_end(s.as_bytes(), 1) == s.len() && s.ends_with('"')).then_some(s); + } + let rest = s.strip_prefix('r')?; + let hashes = rest.len() - rest.trim_start_matches('#').len(); + raw_literal_body(rest).map(|_| &rest[hashes..rest.len() - hashes]) +} + +/// The literal that names the file of a whitespace-free path expression, quotes included: one +/// complete string literal, the file literal of a `format!`-family or `concat!` call +/// ([`last_literal`]), or the same inside `Path::new(…)` or `PathBuf::from(…)`. `None` for any +/// other expression: `"data.json".trim_end_matches(".rs")` names `data.json`, not its last literal. +fn file_literal(expr: &str) -> Option<&str> { + let e = ungroup(expr.strip_suffix(',').unwrap_or(expr)); + if let Some(l) = whole_literal(e) { + return Some(l); + } + let open = e.find('(')?; + if outer_close(e, open) != Some(e.len() - 1) { + return None; + } + let head = e[..open].trim_start_matches("std::").trim_start_matches("path::"); + match head { + "format!" | "format_args!" | "concat!" => last_literal(e), + "Path::new" | "PathBuf::from" => file_literal(&e[open + 1..e.len() - 1]), + _ => None, + } +} + /// The last string literal in a (whitespace-free) expression, quotes included. Inside a /// `format!`-family call, an argument is not the file name, so the format string is returned /// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. @@ -3341,6 +3456,13 @@ fn norm_outside_literals(b: &[u8]) -> String { } else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) { in_str = true; out.push(c); + } else if c == b'r' && !(i > 0 && is_ident(b[i - 1])) && matches!(b[i + 1..].iter().find(|&&h| h != b'#'), Some(b'"')) { + // A raw literal runs to its own closing delimiter: the `"` in `r#"A" B"#` does not end it. + let mut sink = vec![]; + let end = after_ident(b, &mut sink, i, false); + out.extend_from_slice(&b[i..end]); + i = end; + continue; } else if !c.is_ascii_whitespace() { out.push(c); } @@ -3363,7 +3485,7 @@ fn raw_literal_body(s: &str) -> Option<&str> { fn key_like(arg: &str) -> bool { let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); match arg.as_bytes().first() { - Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(b'"') => whole_literal(arg).is_some(), Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), @@ -3480,10 +3602,12 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option { } // A guard (`Some(x) if x == n`) reads names; it does not bind them. let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); - let pattern = norm(&body[start..guard]); + let pattern = norm_words(&body[start..guard]); if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { continue; } @@ -3609,9 +3733,8 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u [&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); if keyword.is_some() { // `if let` and `while let` bind the pattern's names inside their body only. - if let Some((open, close)) = let_body(body, n0) { - let pattern = norm(&body[n0..open]); - let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); + if let Some((eq, open, close)) = let_body(body, n0) { + let pattern = norm_words(&body[n0..eq]); if open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { found = Some((None, at)); } @@ -3629,7 +3752,7 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u found = Some((if is_mut { None } else { init }, at)); } else if !plain { // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). - let pattern = norm(&body[n0..stop]); + let pattern = norm_words(&body[n0..stop]); let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); if !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { found = Some((None, at)); @@ -3639,9 +3762,44 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u found } -/// The braces of the body of an `if let` or `while let` whose pattern starts at `from`: the first -/// `{` outside parentheses and brackets, and its match. -fn let_body(body: &[u8], from: usize) -> Option<(usize, usize)> { +/// The `=` that ends the pattern of an `if let` or `while let` starting at `from`, and the braces of +/// its body after the scrutinee ([`block_after`]). The `=` sits outside every bracket, so the braces +/// of a struct pattern (`if let Row { n } = …`) are part of the pattern, and it is not part of `==`, +/// `=>`, `..=`, `<=`, `>=` or `!=`. +fn let_body(body: &[u8], from: usize) -> Option<(usize, usize, usize)> { + let mut depth = 0usize; + for (i, &c) in body.iter().enumerate().skip(from) { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' if depth == 0 => return None, + b')' | b']' | b'}' => depth -= 1, + b';' if depth == 0 => return None, + b'=' if depth == 0 + && !matches!(body.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| body[j]), Some(b'=' | b'.' | b'<' | b'>' | b'!')) => + { + return block_after(body, i + 1).map(|(open, close)| (i, open, close)); + } + _ => {} + } + } + None +} + +/// The depth of the brackets left open at the end of `b`. +fn bracket_depth(b: &[u8]) -> isize { + b.iter() + .map(|&c| match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }) + .sum() +} + +/// The braces of the block that follows an expression starting at `from`: the first `{` outside +/// parentheses and brackets, and its match. +fn block_after(body: &[u8], from: usize) -> Option<(usize, usize)> { let mut depth = 0usize; for (i, &c) in body.iter().enumerate().skip(from) { match c { @@ -4202,20 +4360,37 @@ fn path_overrides<'a>(sources: impl IntoIterator) -> out } -/// The string value of a `#[path = "…"]` attribute in `m[from..to]`. +/// The string value of a `#[path = "…"]` attribute in `m[from..to]`, written as an ordinary or a +/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). 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); - if !attr || m.get(eq) != Some(&b'=') || m.get(q) != Some(&b'"') { + let mut q = skip_ws(m, eq + 1); + if !attr || m.get(eq) != Some(&b'=') { return None; } - let close = find(m, b"\"", q + 1)?; - Some(String::from_utf8_lossy(&src[q + 1..close]).into_owned()) + let hashes = if m.get(q) == Some(&b'r') { + let h = m[q + 1..].iter().take_while(|&&c| c == b'#').count(); + q += 1 + h; + h + } else { + 0 + }; + if m.get(q) != Some(&b'"') { + return None; + } + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(m, &close, q + 1)?; + Some(String::from_utf8_lossy(&src[q + 1..end]).into_owned()) }) } +/// The value of a whitespace-free `path=` argument, for an ordinary or a raw string literal. +fn path_arg(arg: &str) -> Option<&str> { + whole_literal(arg.strip_prefix("path=")?).map(|l| &l[1..l.len() - 1]) +} + /// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and /// path. fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { @@ -4232,7 +4407,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, let mut start = first + 1; for cut in cuts[1..].iter().copied().chain([text.len()]) { let arg = text.get(start..cut).unwrap_or(""); - if let Some(rel) = arg.strip_prefix("path=\"").and_then(|r| r.strip_suffix('"')) { + if let Some(rel) = path_arg(arg) { out.push((text[..first].to_owned(), rel.to_owned())); } start = cut + 1; @@ -6167,6 +6342,10 @@ mod tests { assert_eq!(only("mirror", raw), [], "raw string keys"); let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); + let raw_quote = "#[test]\nfn t() {\n assert_eq!(at(r#\"A\" B\"#), at(r#\"A\"B\"#) + 1);\n}\n"; + assert_eq!(only("mirror", raw_quote), [], "a quote inside a raw key does not end it"); + let computed = "#[test]\nfn t() {\n assert_eq!(label(\"A\".to_owned() + \"B\"), label(\"C\") + 1);\n}\n"; + assert_eq!(only("mirror", computed), [(3, "mirror")], "a computed string is not an entry key"); let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not"); let offset = @@ -6211,6 +6390,13 @@ mod tests { assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one"); let if_let = "#[test]\nfn t() {\n let x = 0;\n if let Some(x) = compute() {\n assert_eq!(x, 2);\n }\n}\n"; assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); + let struct_pattern = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", struct_pattern), [], "the braces of a struct pattern are not the body"); + let else_branch = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n consume(n);\n } else {\n assert_eq!(n, 0);\n }\n}\n"; + assert_eq!(only("fixture-only", else_branch), [(2, "fixture-only")], "the `else` branch sees the outer binding"); + let mut_pattern = + "#[test]\nfn t() {\n let n = 0;\n if let Some(mut n) = compute() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mut_pattern), [], "`mut n` in an `if let` binds `n`"); } #[test] @@ -6439,6 +6625,20 @@ mod tests { assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); } + #[test] + fn a_removed_namesake_module_does_not_hide_a_newly_off_test() { + // `a::t` was off at the base and `b::t` ran; the change deletes `mod a` and gates the parent, + // so `b::t` is now the only `t` in the file. + let path = "crates/x/src/child.rs"; + let before = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.line).collect(); + assert_eq!(off, [3], "`b::t` is newly off"); + } + #[test] fn never_run_follows_a_tests_module_directory_under_src() { let files: HashMap<&str, &str> = @@ -6610,6 +6810,27 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn base_root_routes_come_from_the_base_tree() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-roots-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/tests/common")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + std::fs::write(root.join("crates/x/tests/smoke.rs"), "mod common;\n").unwrap(); + std::fs::write(root.join("crates/x/tests/common/mod.rs"), "").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::remove_file(root.join("crates/x/tests/smoke.rs")).unwrap(); + let shared = "crates/x/tests/common/mod.rs"; + let now = vec![shared.to_owned()]; + assert!(with_root_routes(Overrides::new(), &now).get(shared).is_none_or(|r| r.is_empty()), "no root loads it now"); + let then = base_files(&root, &base).unwrap(); + let routes = with_root_routes(Overrides::new(), &then); + let parents: Vec<&str> = routes.get(shared).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, ["crates/x/tests/smoke.rs"], "the deleted root loaded it at the base"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn never_run_follows_a_path_selected_by_cfg_attr() { let files: HashMap<&str, &str> = [ @@ -6977,6 +7198,15 @@ mod tests { let format_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", format_rs), [(3, "reads-source")], "a format string that names a .rs file"); + let grouped_ext = "#[test]\nfn t() {\n let s = fs::read_to_string((root.join(\"sample.rs\").with_extension(ext))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", grouped_ext), [], "grouping around the argument hides no step"); + let grouped_rs = + "#[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", grouped_rs), [(3, "reads-source")], "a grouped join that names a .rs file"); + let computed = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\".trim_end_matches(\".rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", computed), [], "a computed file name is not its last literal"); + let wrapped = "#[test]\nfn t() {\n let s = fs::read_to_string(Path::new(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", wrapped), [(3, "reads-source")], "a literal inside Path::new"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); @@ -7009,6 +7239,12 @@ mod tests { assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); + let mutable = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mutable), [], "`mut n` binds `n`"); + let destructured = "#[test]\nfn t() {\n let n = 0;\n for Row { n } in rows() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", destructured), [], "the braces of a struct pattern are not the loop body"); + let mut_after = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", mut_after), [(2, "fixture-only")], "the outer binding after a `mut` loop"); } #[test] @@ -7033,6 +7269,28 @@ mod tests { assert_eq!(only("never-run", comma), [], "a comma inside the condition's value"); let src = "#[cfg_attr(unix, path = \"a,b.rs\")]\nmod x;\n"; assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "a,b.rs".to_owned())]); + let raw = "#[cfg_attr(unix, path = r#\"a.rs\"#)]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "a.rs".to_owned())]); + } + + #[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"] { + assert_eq!(path_attr(&mask(src), src.as_bytes(), 0, src.len()).as_deref(), Some("shared.rs"), "{src}"); + } + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod a;\nmod b;\n"), + ("crates/x/src/a.rs", "#[path = r\"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\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 shared = "crates/x/src/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux"); } #[test]