diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index ca0108f955..e4d26a0b6a 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/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 5fe28b4639..be306a51c9 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 66ae287023..cba8f9301b 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -812,6 +812,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"); @@ -1018,6 +1019,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; @@ -1043,6 +1045,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())); diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f1667d2cb0..449885209f 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 @@ -79,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; @@ -240,9 +242,9 @@ pub struct Hit { /// only near `line`. pub first: usize, pub last: usize, - /// Other lines whose change counts as a change to the hit, by file: the `cfg` attributes that - /// turn a `never-run` test off, on its module or on a `mod` declaration in another file. - pub also: Vec<(String, usize, usize)>, + /// 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 { @@ -259,18 +261,30 @@ pub struct Ctx { pub helpers: HashMap>, pub ci_env: HashSet, pub module_cfgs: HashMap>, - /// Where the attributes of [`Ctx::module_cfgs`] are. - pub module_sites: HashMap>, } -/// [`Ctx::module_cfgs`] and [`Ctx::module_sites`] for `paths`. -fn module_ctx(paths: &[String], read: &dyn Fn(&str) -> Option) -> (HashMap>, HashMap>) { - let (mut cfgs, mut sites) = (HashMap::new(), HashMap::new()); - for (path, (preds, at)) in module_walk(paths, read) { - cfgs.insert(path.clone(), preds); - sites.insert(path, at); - } - (cfgs, sites) +/// 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))))) +} + +/// Whether a change touches the declarations that gate the module file `path` now +/// ([`gate_changed`]), or any file that declared it at the base: an edit there can remove a way for +/// its tests to run, and the base lines may no longer match. +fn route_gate_changed( + path: &str, + gates: Option<&Gates>, + 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`]. @@ -279,15 +293,29 @@ 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()); + 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_sites) = module_ctx(&files, &|p| read_small(root, p)); - let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs, module_sites }; + let overrides = with_root_routes(path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))), &files); + 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())); return Ok(()); @@ -298,33 +326,174 @@ 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(); - // Every file whose module a changed `mod` declaration governs is linted too, so a `cfg` added to - // `mod child;` counts against the tests in `child.rs`. - let cache: std::cell::RefCell>> = Default::default(); - let read = |p: &str| cache.borrow_mut().entry(p.to_owned()).or_insert_with(|| read_small(root, p)).clone(); - let (module_cfgs, module_sites) = module_ctx(&files, &read); - let governed: Vec = module_sites - .iter() - .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _, _)| changed.contains_key(decl))) - .map(|(p, _)| p.clone()) - .collect(); - let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs, module_sites }; + // Files that load a module through `#[path]`, found with `git grep` (untracked files included) + // instead of reading the tree, and the target roots beside a shared `tests//mod.rs`. + let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files); + let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); + // 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. + let seeds: Vec = changed.keys().cloned().collect(); + let below: Vec = + 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(); + 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 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 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 (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)? { + 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_in(&hit, &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; } } } - for (path, src) in read_all(root, &governed)? { - counted.extend(lint_file(&path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && touches_in(h, &changed))); + 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 `base_src` under the base's gates, has a `never-run` hit for the test +/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place +/// among the tests of that name in those modules, so lines that moved still match and tests of one +/// name in different inline modules stay apart, even when a change removes one of the modules. +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).as_ref() == Some(place), + None => h.line == hit.line, + }) +} + +/// 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); + 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 +/// `mod.rs`, `lib.rs`, `main.rs` and crate roots ([`owns_its_dir`]), and the directory named after +/// it otherwise. +fn module_dir(p: &str) -> String { + let dir = p.rsplit_once('/').map_or("", |(d, _)| d); + if owns_its_dir(p) { 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. +/// 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` 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(); + let mut out = vec![]; + while !frontier.is_empty() { + let beside = |p: &String| -> Vec { + if owns_its_dir(p) || !(overrides.contains_key(p) || base_overrides.contains_key(p)) { + return vec![]; + } + let dir = p.rsplit_once('/').map_or("", |(d, _)| d); + [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 + .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 names of the modules `src` declares, by file (`mod child;`) or inline (`mod platform { … }`). +fn declared_names(src: &str) -> Vec { + let m = mask(src); + words(&m, b"mod", 0, m.len()) + .into_iter() + .filter_map(|at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + (end > start && matches!(m.get(skip_ws(&m, end)), Some(b';' | b'{'))).then(|| String::from_utf8_lossy(&m[start..end]).into_owned()) + }) + .collect() +} + /// The command line: `--all`, `--base `. #[derive(Debug, Default, PartialEq)] struct Options { @@ -479,6 +648,8 @@ fn changed_lines(root: &Path, base: &str) -> Result 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; @@ -571,14 +748,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 { - let within = |lines: &BTreeSet, a: usize, b: usize| lines.range(a..=b).next().is_some(); - changed.is_none_or(|lines| within(lines, hit.first, hit.last) || hit.also.iter().any(|(p, a, b)| *p == hit.path && within(lines, *a, *b))) -} - -/// [`touches`] across files: the hit's own lines, or its [`Hit::also`] lines in any changed file. -fn touches_in(hit: &Hit, changed: &BTreeMap>>) -> bool { - let in_file = |p: &str, a: usize, b: usize| changed.get(p).is_some_and(|c| c.as_ref().is_none_or(|l| l.range(a..=b).next().is_some())); - changed.get(&hit.path).is_some_and(|c| touches(hit, c.as_ref())) || hit.also.iter().any(|(p, a, b)| in_file(p, *a, *b)) + 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 ---- @@ -861,6 +1031,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); @@ -1209,12 +1398,14 @@ struct File<'a> { tests: Vec, /// The test code ([`test_regions`]). regions: Vec<(usize, usize)>, + /// The `cfg` attributes and the items they cover ([`cfg_spans`]). + cfgs: Vec, } 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, also: vec![] } + 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 { @@ -1247,7 +1438,8 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); let exec = executed(&m, &tests); - let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; + let cfgs = cfg_spans(&m, src.as_bytes()); + let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions, cfgs }; let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); hits.extend(ignore_hits(&file)); hits.extend(sleep_hits(&file)); @@ -1430,7 +1622,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 }; @@ -1673,23 +1865,25 @@ 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) && 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, } } -/// 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 { +/// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole +/// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so +/// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's +/// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is +/// not a round trip of the entry. +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); @@ -1703,13 +1897,25 @@ 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) - // Only a path or receiver before the call: `offset + lookup(n)` is a derived value. - && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '=', '!', ',', '&']) - && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) + && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',', '&']) + && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var)) }) }) } +/// 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 { + let b = s.as_bytes(); + !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"::"; + !(at > 0 && is_ident(b[at - 1])) && !field && !path && !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()", "?"]; @@ -2978,53 +3184,13 @@ fn sleep_hits(file: &File) -> Vec { .collect() } -/// The contents of the last string literal in `s`, without its quotes. -fn last_literal(s: &str) -> Option<&str> { - let close = s.rfind('"')?; - let open = s[..close].rfind('"')?; - Some(&s[open + 1..close]) -} - -/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call that ends the path, since -/// its arguments fill placeholders inside it, otherwise the last string literal. A literal after the `format!(…)` -/// call (`PathBuf::from(format!(…)).join("lib.rs")`) ends the path instead. -fn path_literal(arg: &str) -> Option<&str> { - let Some(at) = arg.find("format!(") else { return last_literal(arg) }; - let rest = &arg[at + "format!(".len()..]; - let b = rest.as_bytes(); - let (mut depth, mut i, mut end) = (0usize, 0, None); - while i < b.len() { - match b[i] { - b'"' => { - i += 1; - while i < b.len() && b[i] != b'"' { - i += if b[i] == b'\\' { 2 } else { 1 }; - } - } - b'(' => depth += 1, - b')' if depth == 0 => { - end = Some(i); - break; - } - b')' => depth -= 1, - _ => {} - } - i += 1; - } - let call = &rest[..end.unwrap_or(rest.len())]; - if let Some(tail) = end.map(|e| &rest[e + 1..]).filter(|t| t.contains('"')) { - return path_literal(tail); - } - let open = call.find('"')?; - let close = call[open + 1..].find('"')? + open + 1; - Some(&call[open + 1..close]) -} - fn reads_source_hits(file: &File) -> Vec { if SOURCE_AUDITS.contains(&file.path) { 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"), @@ -3035,21 +3201,34 @@ 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 }; - // Comments dropped, so `/* "src/lib.rs" */` beside a JSON path is not a hit. - let arg = file.src_norm((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); let rs = match word { b"ends_with" => literal == "\".rs\"", - // The last path literal in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`, but not - // `root.join("fixtures.rs").join("input.json")` or `format!("{}/input.json", "fixtures.rs")`. - b"read_to_string" => path_literal(&arg).is_some_and(|l| l.ends_with(".rs")), + // 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. 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]))) + }; + match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { + 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\""), }; if rs { - // Through the call's `)`, so a change to a path on a later line is a change to the hit. 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); } @@ -3058,6 +3237,137 @@ 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 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. +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]) +} + // ---- Mirrors, echoes, never-run tests and exact pixels ---- /// Names a `mirror` comparison may call on both sides: builders, conversions and accessors. @@ -3112,22 +3422,108 @@ 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 +/// `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_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 == 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); + } + i += 1; + } + 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'"') => 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':')), + 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 { + let code = std::cell::OnceCell::new(); 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. + // 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, None) => false, + (Some(i), Some(j)) => l[i..] != r[j..], + _ => 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 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))) }) .collect() } @@ -3203,12 +3599,148 @@ 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| { + // `in` is found as a word outside the pattern's brackets, so a line break around it still + // ends the pattern, and the braces of `for Row { n } in …` are not the loop body. + let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false }; + let Some((open, close)) = block_after(body, kw + 2) else { return false }; + // Words stay apart, so `mut n` binds `n`. + let pattern = norm_words(&body[at + 3..kw]); + open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() + }); + // A match arm's pattern binds its names inside that arm only, and a closure's parameters + // inside its body only. + let inner = loop_at.max(arm_binding(body, name, before)).max(closure_binding(body, name, before)); + match (inner, &found) { + (Some(l), Some((_, at))) if *at > l => found.map(|(init, _)| init), + (Some(_), _) => Some(None), + (None, _) => found.map(|(init, _)| init), + } +} + +/// The offset of the parameter list of the innermost closure whose parameters bind `name` and whose +/// body holds `before`: `for_each(|n| assert_eq!(n, 1))` binds `n`. +fn closure_binding(body: &[u8], name: &str, before: usize) -> Option { + let mut found = None; + let mut i = 0; + while i < before.min(body.len()) { + if body[i] != b'|' { + i += 1; + continue; + } + // A closure's `|` follows an opening bracket, a separator, `=` or `move`; `a | b` and + // `a || b` follow an operand. + let lead = body[..i].trim_ascii_end(); + let opens = lead.last().is_none_or(|&c| matches!(c, b'(' | b'[' | b'{' | b',' | b'=' | b';')) || lead.ends_with(b"move"); + let Some(close) = body[i + 1..].iter().position(|&c| c == b'|').map(|p| p + i + 1) else { break }; + if !opens || close == i + 1 { + i = if opens { close + 1 } else { i + 1 }; + continue; + } + let params = &body[i + 1..close]; + let from = skip_ws(body, close + 1); + let end = match body.get(from) { + Some(b'{') => matching(body, from), + _ => { + let mut depth = 0usize; + (from..body.len()).find(|&k| match body[k] { + b'(' | b'[' | b'{' => { + depth += 1; + false + } + b')' | b']' | b'}' if depth == 0 => true, + b')' | b']' | b'}' => { + depth -= 1; + false + } + b',' | b';' => depth == 0, + _ => false, + }) + } + }; + if !words(params, name.as_bytes(), 0, params.len()).is_empty() && from <= before && end.is_some_and(|end| before < end) { + found = Some(i); + } + i = close + 1; + } + found +} + +/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body +/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not. +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_words(&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; for at in words(body, b"let", 0, before) { let start = skip_ws(body, at + 3); let is_mut = body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace); let n0 = if is_mut { skip_ws(body, start + 3) } else { start }; let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c)).count(); + let head = body[..at].trim_ascii_end(); + let keyword = + [&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); + if keyword.is_some() { + // `if let` and `while let` bind the pattern's names inside their body only. + 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)); + } + } + continue; + } let stop = statement_end(body, n1); if stop > before || block_close(body, at) < before { continue; @@ -3217,39 +3749,70 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> 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 = 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); + found = Some((None, at)); } } } - // A nearer `for in` binding of the name, whose block holds `before`, shadows the - // `let`: its value is unknown. - let found_at = match &found { - Some(Some((_, at))) => Some(*at), - _ => None, - }; - let shadows = |kw: &[u8], sep: &[u8]| { - words(body, kw, 0, before).into_iter().any(|at| { - let head = at + kw.len(); - let Some(open) = body[head..before].iter().position(|&c| c == b'{').map(|p| p + head) else { return false }; - let Some(split) = find(&body[..open], sep, head) else { return false }; - let pattern = &body[head..split]; - !words(pattern, name.as_bytes(), 0, pattern.len()).is_empty() - && matching(body, open).is_some_and(|close| open < before && before < close) - && found_at.is_none_or(|l| at > l) - }) - }; - if shadows(b"for", b" in ") { - return Some(None); - } found } +/// 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 { + 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; @@ -3321,6 +3884,77 @@ 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 +} + +/// The offsets of the commas in an attribute's argument list `s` that separate its arguments: +/// outside brackets and outside string literals, so `target_os = "("` and `path = "a,b.rs"` stay +/// whole. +fn attr_commas(s: &str) -> Vec { + let b = s.as_bytes(); + let (mut depth, mut i, mut out) = (0i32, 0, vec![]); + while i < b.len() { + match b[i] { + b'"' => { + // A raw string (`r#"…"#`) ends at a quote followed by as many `#` as it opened with, + // and has no escapes. + let hashes = b[..i].iter().rev().take_while(|&&c| c == b'#').count(); + let raw = b[..i - hashes].last() == Some(&b'r'); + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', if raw { hashes } else { 0 })).collect(); + i += 1; + while i < b.len() && !b[i..].starts_with(&close) { + i += if !raw && b[i] == b'\\' { 2 } else { 1 }; + } + i += close.len(); + continue; + } + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b',' if depth == 0 => out.push(i), + _ => {} + } + i += 1; + } + 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 { @@ -3328,7 +3962,7 @@ fn cfg_value(p: &str, t: &Target) -> Option { if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) { let mut parts = vec![]; let mut start = 0; - for at in top_level_at(args, ",").into_iter().chain([args.len()]) { + for at in attr_commas(args).into_iter().chain([args.len()]) { if at > start { parts.push(cfg_value(&args[start..at], t)); } @@ -3344,14 +3978,18 @@ 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"#`. - let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); - // An escape in an ordinary string (`"lin\x75x"`) is not decoded, so its value is unknown. - if p.split_once('=').is_some_and(|(_, v)| !v.starts_with('r') && v.contains('\\')) { - return None; - } + // 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_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(); match key { "test" => Some(true), "unix" => Some(t.family == "unix"), @@ -3364,33 +4002,98 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } -/// The text of a `cfg(…)` predicate without whitespace and comments; string literals keep their text. -fn cfg_text(src: &[u8]) -> String { +/// 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; + } + for pred in cfg_attr_preds(&text, None) { + out.push(CfgAttr { pred, at, end, inner }); + } + } + } + out.sort_by_key(|a| a.at); + 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 = attr_commas(text); + let Some(&first) = cuts.first() else { return vec![] }; + let cond = match outer { + Some(o) => format!("all({o},{})", &text[..first]), + None => text[..first].to_owned(), + }; + let mut out = vec![]; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(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 { norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) } -/// The 1-based line of a byte offset. -fn line_at(b: &[u8], at: usize) -> usize { - b[..at.min(b.len())].iter().filter(|&&c| c == b'\n').count() + 1 +/// The predicates of the `cfg` attributes of [`cfg_spans`] whose item holds `pos`, each with the +/// offsets where its attribute starts and ends. +fn cfgs_at(spans: &[CfgSpan], pos: usize) -> Vec<(String, usize, usize)> { + spans.iter().filter(|s| s.span.0 <= pos && pos <= s.span.1).map(|s| (s.pred.clone(), s.at, s.end)).collect() } -/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with -/// the offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { +/// A `cfg` attribute and the item it covers, from its start to its closing brace. +struct CfgSpan { + pred: String, + at: usize, + end: usize, + span: (usize, usize), +} + +/// Every `cfg` attribute in `src` ([`cfg_attrs`]) with the item it covers, read once per file and +/// queried for each test or declaration with [`cfgs_at`]. +fn cfg_spans(m: &[u8], src: &[u8]) -> Vec { 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'{'); @@ -3408,199 +4111,519 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { _ => continue, } }; - if span.0 <= pos && pos <= span.1 { - // The source text: masking blanks the string literals `target_os = "macos"` needs. - out.push((cfg_text(&src[open + 1..close]), at, end)); - } + out.push(CfgSpan { pred, at, end, span }); } out } -/// A file that may declare a module, and the inline module it must be declared in, if any. -type Candidate = (String, Option); -/// The predicates on a `mod` declaration and the first and last line of each attribute, with the -/// predicate that attribute contributes. -type Declared = (Vec, Vec<(usize, usize, String)>); -/// A file that declares a module, whether it does so in an inline module, and what it declares. -type Owner = (String, bool, Declared); +/// Whether the files directly in `dir` are crate target roots: `tests`, `benches` or `examples` +/// beside a crate's `src`, or `src/bin`. +fn is_root_dir(dir: &str) -> bool { + 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") +} + +/// Whether the modules the file `path` declares by name sit in its own directory: `mod.rs`, +/// `lib.rs`, `main.rs` and every crate root (`tests/smoke.rs`, `build.rs`). +fn owns_its_dir(path: &str) -> bool { + let file = path.rsplit_once('/').map_or(path, |(_, f)| f); + ["mod.rs", "lib.rs", "main.rs"].contains(&file) || module_parent(path).is_none() +} + +/// Whether `path` is a `mod.rs` one directory below a target directory (`tests/common/mod.rs`). +fn beside_roots(path: &str) -> bool { + path.rsplit_once('/').is_some_and(|(dir, file)| file == "mod.rs" && dir.rsplit_once('/').is_some_and(|(up, _)| is_root_dir(up))) +} + +/// The routes to each [`beside_roots`] file of `files`: every target root in the directory above it +/// (`tests/smoke.rs` for `tests/common/mod.rs`) may load it with `mod common;`. +fn root_routes(files: &[String]) -> Overrides { + let mut out: Overrides = HashMap::new(); + for child in files.iter().filter(|p| beside_roots(p)) { + let Some((up, _)) = child.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')) else { continue }; + let roots = files.iter().filter(|p| p.rsplit_once('/').is_some_and(|(d, f)| d == up && f.ends_with(".rs"))); + out.entry(child.clone()).or_default().extend(roots.map(|r| (r.clone(), vec![]))); + } + out +} + +/// `overrides` with the routes of [`root_routes`] added. +fn with_root_routes(mut overrides: Overrides, files: &[String]) -> Overrides { + for (child, routes) in root_routes(files) { + let known = overrides.entry(child).or_default(); + for route in routes { + if !known.contains(&route) { + known.push(route); + } + } + } + overrides +} /// 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`). A candidate that comes with a module name declares it inside that inline module -/// (`mod platform { mod child; }` in `src/lib.rs` for `src/platform/child.rs`); those come last. -fn module_parent(path: &str) -> Option<(&str, Vec)> { +/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `src` holds modules, not test targets. A `mod.rs` one directory below a target directory +/// (`tests/common/mod.rs`) has no candidates here: the target roots beside that directory load it +/// (`tests/smoke.rs` with `mod common;`), and [`root_routes`] lists them. +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)); - if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { + if beside_roots(path) { + return Some((dir.rsplit_once('/')?.1, vec![])); + } + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (is_root_dir(dir) && file != "mod.rs") { return None; } let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; - let files_of = |dir: &str| -> Vec { - let mut c: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{dir}/{f}")).collect(); - c.push(format!("{dir}.rs")); - c - }; - let mut candidates: Vec = files_of(parent).into_iter().map(|c| (c, None)).collect(); - if let Some((grand, inline)) = parent.rsplit_once('/') { - candidates.extend(files_of(grand).into_iter().map(|c| (c, Some(inline.to_owned())))); - } + let mut candidates: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect(); + candidates.push(format!("{parent}.rs")); 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. -#[cfg(test)] -fn declared_cfgs(src: &str, name: &str) -> Option> { - declared_cfg_spans(src, name, None).map(|(preds, _)| preds) +/// 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], } -/// [`declared_cfgs`] with the first and last line of each attribute. With `within`, only a -/// declaration inside the inline module of that name counts. -fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option { +/// 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. `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. `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 named = |at: usize, word: &str, next: u8| { + let lines = Lines::new(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = owns_dir || owns_its_dir(parent); + 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![]); + // The file's `cfg` attributes, read on the first declaration that loads `want`. + let mut spans: Option> = None; + 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(); - (&m[start..end] == word.as_bytes() && m.get(skip_ws(&m, end)) == Some(&next)).then(|| skip_ws(&m, end)) - }; - let blocks: Option> = within.map(|w| { - words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() - }); - // Every inline `mod { … }`: a declaration counts only when its innermost enclosing inline - // module is the one `within` names (or, without `within`, when it has none), since a declaration - // nested deeper loads a file under that other module's directory. - let inline: Vec<(usize, usize)> = words(&m, b"mod", 0, m.len()) - .into_iter() - .filter_map(|at| { - let start = skip_ws(&m, at + 3); - let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - let o = skip_ws(&m, end); - (end > start && m.get(o) == Some(&b'{')).then(|| matching(&m, o).map(|c| (o, c))).flatten() - }) - .collect(); - let innermost = |at: usize| inline.iter().filter(|&&(o, c)| o < at && at < c).max_by_key(|&&(o, _)| o).copied(); - let decls: Vec = words(&m, b"mod", 0, m.len()) - .into_iter() - .filter(|&at| { - named(at, name, b';').is_some() - && match (&blocks, innermost(at)) { - (None, inner) => inner.is_none(), - (Some(bs), Some(inner)) => bs.contains(&inner), - (Some(_), None) => false, - } - }) - .collect(); - let mut each = decls.iter().map(|&decl| decl_cfg_spans(&m, src, decl)); - let first = each.next()?; - let rest: Vec = each.collect(); - if rest.iter().all(|(p, _)| *p == first.0) { - let mut lines = first.1; - lines.extend(rest.into_iter().flat_map(|(_, l)| l)); - return Some((first.0, lines)); - } - // Declarations under different `cfg`s (`#[cfg(windows)] mod child;` and `#[cfg(unix)] mod child;`): - // the module is compiled where any of them holds. - let (mut alts, mut spans) = (vec![], vec![]); - for (p, l) in std::iter::once(first).chain(rest) { - alts.push(format!("all({})", p.join(","))); - spans.extend(l.into_iter().map(|(a, b, _)| (a, b))); - } - let any = format!("any({})", alts.join(",")); - let lines = spans.into_iter().map(|(a, b)| (a, b, any.clone())).collect(); - Some((vec![any], lines)) -} - -/// The predicates of the `#[cfg(…)]` attributes on the `mod` declaration at `decl` of masked `m` -/// and on the items and file around it, with the first and last line of each attribute. -fn decl_cfg_spans(m: &[u8], src: &str, decl: usize) -> Declared { - let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let (mut preds, mut lines) = (vec![], 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() { - let p = cfg_text(&src.as_bytes()[open + 1..close]); - lines.push((line_at(m, at), line_at(m, close), p.clone())); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + continue; + } + // The conditions under which the inline modules around the declaration resolve to `want.chain`. + let mut via_chain: Vec> = + inline_routes(&m, src.as_bytes(), at).into_iter().filter(|(c, _)| c == want.chain).map(|(_, k)| k).collect(); + let inline_cond = match via_chain.len() { + 0 => continue, + 1 => via_chain.pop().filter(|k| !k.is_empty()).map(|k| format!("all({})", k.join(","))), + _ => Some(format!("any({})", via_chain.iter().map(|k| format!("all({})", k.join(","))).collect::>().join(","))), + }; + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + // 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) => via != Via::Named && overrides_here(&rel), + None => { + 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)| 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(","))), + (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_at`] 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)); + } + preds.extend(inline_cond); + for (p, a, e) in cfgs_at(spans.get_or_insert_with(|| cfg_spans(&m, src.as_bytes())), at) { preds.push(p); + at_lines.extend(lines.of(a)..=lines.of(e)); } + each.push(preds); } - for (p, at, end) in cfgs_over(m, src.as_bytes(), decl) { - lines.push((line_at(m, at), line_at(m, end), p.clone())); - preds.push(p); - } - (preds, lines) + 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)) } -/// Where a module's `cfg` attributes are: the declaring file, the attribute's first and last line, -/// and its predicate. -pub type CfgSite = (String, usize, usize, String); +/// 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) +} -/// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the -/// modules above it, read through `read`, with where those attributes are. When several files -/// declare a module (`lib.rs` and `main.rs`) with different attributes, the walk stops there and -/// the module's ownership is unknown. -fn module_walk(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap, Vec)> { - let mut out = HashMap::new(); - for path in paths { - let (mut preds, mut sites, mut at) = (vec![], vec![], path.clone()); - for _ in 0..16 { - let Some((name, candidates)) = module_parent(&at) else { break }; - let found: Vec = candidates - .into_iter() - .filter_map(|(c, within)| read(&c).and_then(|s| declared_cfg_spans(&s, name, within.as_deref())).map(|f| (c, within.is_some(), f))) - .collect(); - let direct = found.iter().any(|(_, inline, _)| !inline); - let owners: Vec<&Owner> = found.iter().filter(|(_, inline, _)| !inline || !direct).collect(); - let Some(first) = owners.first() else { break }; - let sorted = |p: &[String]| { - let mut p = p.to_vec(); - p.sort(); - p - }; - let base = sorted(&first.2.0); - if !owners.iter().all(|o| sorted(&o.2.0) == base) { - break; - } - preds.extend(first.2.0.iter().cloned()); - for o in &owners { - sites.extend(o.2.1.iter().map(|(a, b, p)| (o.0.clone(), *a, *b, p.clone()))); - } - at = first.0.clone(); +/// 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 = owns_its_dir(parent); + 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; } - if !preds.is_empty() { - out.insert(path.clone(), (preds, sites)); + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + 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)); + let chains: Vec> = inline_routes(&m, src.as_bytes(), at).into_iter().map(|(chain, _)| chain).collect(); + for rel in rels { + for chain in &chains { + out.push((override_path(dir, file, mod_rs, chain, &rel), chain.clone())); + } } } out } -/// The predicates of [`module_walk`] alone. -#[cfg(test)] -fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { - module_walk(paths, read).into_iter().map(|(p, (preds, _))| (p, preds)).collect() +/// 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 { + // `-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 -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 + .split('\0') + .filter(|p| !p.is_empty()) + .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]`, 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 mut q = skip_ws(m, eq + 1); + if !attr || m.get(eq) != Some(&b'=') { + return None; + } + 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)> { + 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 = attr_commas(&text); + let Some(&first) = cuts.first() else { continue }; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(rel) = path_arg(arg) { + out.push((text[..first].to_owned(), rel.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(); + for seg in rel.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +/// 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`). A +/// `#[cfg_attr(, path = "…")]` on a block gives one route per directory: its path where +/// the condition holds, and the default elsewhere. Each route comes with the conditions it needs; +/// at most [`MAX_INLINE_ROUTES`] are kept. +fn inline_routes(m: &[u8], src: &[u8], at: usize) -> Vec<(Vec, Vec)> { + let mut routes: Vec<(String, Vec)> = vec![(String::new(), vec![])]; + 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()); + let conditional = cfg_attr_paths(m, src, item, kw); + let mut options: Vec<(String, Vec)> = conditional.iter().map(|(c, rel)| (rel.clone(), vec![c.clone()])).collect(); + let fallback = + (!conditional.is_empty()).then(|| format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::>().join(","))); + options.push((seg, fallback.into_iter().collect())); + routes = routes + .iter() + .flat_map(|(dir, conds)| options.iter().map(move |(seg, c)| (join_path(dir, seg), conds.iter().chain(c).cloned().collect()))) + .take(MAX_INLINE_ROUTES) + .collect(); + } + routes.into_iter().map(|(dir, conds)| (dir.split('/').filter(|s| !s.is_empty()).map(str::to_owned).collect(), conds)).collect() +} + +/// The most routes [`inline_routes`] follows through nested conditional directories. +const MAX_INLINE_ROUTES: usize = 16; + +/// 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, 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 +/// them, the lines of those declarations and attributes. +#[derive(Default)] +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 +/// 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, Via::Any); + (!gates.preds.is_empty()).then(|| (path.clone(), gates)) + }) + .collect() +} + +/// Which routes to a file [`module_gate`] follows: a file that is not a `mod.rs` or a crate root +/// declares its modules in a directory named after it when a `mod ;` loads it (`Named`), and +/// in its own directory when a `#[path]` loads it (`Path`). +#[derive(Clone, Copy, PartialEq)] +enum Via { + Any, + Named, + Path, +} + +/// 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, via: Via) -> Gates { + let mut gates = Gates::default(); + if depth >= 16 { + return gates; + } + let by_path = if via == Via::Named { &[][..] } else { 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 { + 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" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + gates.reached = true; + return gates; + }; + let mut chain: Vec = vec![]; + // Each file that loads the module, what it declares, and the routes to it that load the module + // from there. + 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; + // A parent that is neither a `mod.rs` nor a crate root loads the module only through its + // `mod ;` routes. + let named = |c: &str| if owns_its_dir(c) { Via::Any } else { Via::Named }; + 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. + 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, via)).map(|f| (c.clone(), f, named(c))) + })); + } + 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 via != Via::Path && 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, 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`). + let path_loaded = overrides + .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, via)).map(|f| (owner.clone(), f, Via::Path))); + } + } + if via == Via::Path || beside_roots(at) { + break; + } + 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![]; + // Through `#[path]` alone, a file no `#[path]` declaration loads is not reached. + gates.reached = found.is_empty() && !parent_read && via != Via::Path; + for (parent, (mut preds, lines), parent_via) in found { + let ancestors = module_gate(&parent, read, overrides, depth + 1, parent_via); + // 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); + 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); - let mut preds: Vec = local.iter().map(|(p, _, _)| p.clone()).collect(); + let local = cfgs_at(&v.file.cfgs, v.t.fn_at); + // A change to an attribute that turns the test off counts as a change to the test, on any line + // of a multiline attribute. + // An attribute whose predicate holds on every target CI tests on (`unix` without Windows) does + // not turn the test off, so its lines do not count. + let windows = windows_runs(v.file.path).then_some(&WINDOWS_TARGET); + let excludes = |p: &str| !CI_TARGETS.iter().chain(windows).all(|t| cfg_value(p, t) == Some(true)); + let attr_lines: Vec = + local.iter().filter(|(p, _, _)| excludes(p)).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; } - let windows = windows_runs(v.file.path).then_some(&WINDOWS_TARGET); let off = |t: &Target| preds.iter().any(|p| cfg_value(p, t) == Some(false)); 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(", "))); - // A change to an attribute that turns the test off counts as a change to the test; the - // lines between that attribute and the test do not. - let lines = &v.file.lines; - // An attribute whose predicate holds on every target CI tests on (`unix` without Windows) - // does not turn the test off. - let excludes = |p: &str| !CI_TARGETS.iter().chain(windows).all(|t| cfg_value(p, t) == Some(true)); - hit.also.extend(local.iter().filter(|(p, _, _)| excludes(p)).map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); - hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().filter(|s| excludes(&s.3)).map(|(f, a, b, _)| (f.clone(), *a, *b))); + // 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 @@ -3627,11 +4650,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; } - // A ratio or a scaled value (`a.width() / b.width()`) is not a pixel size. - if op.trim_start_matches(['&', '*']).contains(['/', '*']) { + 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(); @@ -3648,16 +4671,20 @@ 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..]; - // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` - // is a ratio, not a pixel size. - // A `)` or `,` must belong to a tuple group: in `column_for_x(rect.min.x)` and - // `f(rect.min.x, 2)` it is part of a call's arguments. - let ends = |r: &str| { - let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); - r.is_empty() || r.starts_with(']') || (r.starts_with([')', ',']) && !closes_call(b, op.len() - r.len())) - }; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { + // 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; + } + // Only grouping parentheses may surround it: in `count_items(button_rect)` the rect is a + // call's argument, and the operand is what the call returns. + let lead = op[..i].trim_start_matches(['&', '*']); + let lb = lead.as_bytes(); + let call = (1..lb.len()).any(|k| lb[k] == b'(' && (is_ident(lb[k - 1]) || matches!(lb[k - 1], b'!' | b'>'))); + let groups = lead.matches('(').count(); + let path = lead.trim_start_matches(['&', '*', '(']); + if !call && rest.len() == groups && rest.bytes().all(|c| c == b')') && !path.contains(['+', '-', '*', '/', '%', ',', '(']) { return true; } } @@ -3666,22 +4693,6 @@ fn names_rect(op: &str) -> bool { false } -/// Whether the `)` or `,` at `close` is in the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) -/// rather than in a tuple or a parenthesized group. -fn closes_call(b: &[u8], close: usize) -> bool { - let mut depth = 0i32; - for i in (0..close).rev() { - match b[i] { - b')' | b']' | b'}' => depth += 1, - b'(' | b'[' | b'{' if depth > 0 => depth -= 1, - b'(' => return i > 0 && (is_ident(b[i - 1]) || b[i - 1] == b'!' || b[i - 1] == b'>'), - b'[' | b'{' => return false, - _ => {} - } - } - false -} - /// Whether a whitespace-free operand is only numbers, alone or in `pos2`, `vec2` or `Rect` builders. fn only_numbers(op: &str) -> bool { let mut rest = op.trim_start_matches('&').replace("egui::", "").replace("emath::", ""); @@ -3751,6 +4762,26 @@ 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 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 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"); + 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] fn census_loops_over_whole_tables_are_reported() { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); @@ -3818,6 +4849,8 @@ mod tests { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); let offset = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(offset + lookup(n).unwrap(), n);\n }\n}\n"; assert_eq!(census(offset), [], "an operator before the lookup derives a value"); + let referenced = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(mask & lookup(n).unwrap(), n);\n }\n}\n"; + assert_eq!(census(referenced), [], "a bitwise and before the lookup derives a value"); let qualified = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; assert_eq!(census(qualified), [(2, "census")]); let deep = @@ -5291,9 +6324,37 @@ 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 doubling is linear here\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\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"); + 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 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 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 = + "#[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] @@ -5305,8 +6366,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 shadowed = "#[test]\nfn t() {\n let n = 1;\n for n in results() {\n assert_eq!(n, 2);\n }\n}\n"; - assert_eq!(only("fixture-only", shadowed), [], "a loop binding that shadows the fixture"); + 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"; @@ -5325,6 +6388,27 @@ 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"); + 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] + 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] @@ -5350,16 +6434,27 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", other), [], "a cfg on another item"); - let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; - assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); } #[test] - fn reads_source_spans_reach_a_path_on_a_later_line() { - let src = "#[test]\nfn t() {\n let s = fs::read_to_string(\n root.join(\"src/lib.rs\"),\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; - let found: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::ReadsSource).collect(); - assert_eq!(found.iter().map(|h| (h.line, h.first, h.last)).collect::>(), [(3, 3, 5)]); - assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the path alone"); + 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] @@ -5376,7 +6471,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")); @@ -5388,62 +6483,665 @@ 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, Via::Any).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_cfg_spans(block, "child", Some("platform")).map(|(p, _)| p), Some(vec!["windows".to_owned()])); - assert_eq!(declared_cfgs(block, "child"), None, "the nested declaration loads platform/child.rs"); - let nested = "#[cfg(windows)]\nmod child;\nmod other {\n mod child;\n}\n"; - assert_eq!(declared_cfgs(nested, "child"), Some(vec!["windows".to_owned()]), "other/child.rs is another file"); - assert_eq!(declared_cfg_spans(nested, "child", Some("other")).map(|(p, _)| p), Some(vec![])); - assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); + 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(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(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, &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, 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 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> = + [("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"); + 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 paths: Vec = files.keys().map(|p| (*p).to_owned()).collect(); + let overrides = with_root_routes(path_overrides(files.iter().map(|(p, s)| (*p, *s))), &paths); + 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"); + // Only a macOS-gated declaration in the target beside it loads the helper. + let gated: HashMap<&str, &str> = [ + ("crates/x/tests/smoke.rs", "#[cfg(target_os = \"macos\")]\nmod common;\n"), + ("crates/x/tests/other.rs", "fn main() {}\n"), + ("crates/x/tests/common/mod.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| gated.get(p).map(|s| (*s).to_owned()); + let paths: Vec = gated.keys().map(|p| (*p).to_owned()).collect(); + let overrides = with_root_routes(Overrides::new(), &paths); + let gated_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &gated_ctx), [(2, "never-run")], "the only target that loads it is macOS-only"); + let child = "crates/x/tests/common/helpers.rs".to_owned(); + let with_child: HashMap<&str, &str> = + gated.iter().map(|(p, s)| (*p, *s)).chain([("crates/x/tests/common/mod.rs", "mod helpers;\n")]).collect(); + let read = |p: &str| with_child.get(p).map(|s| (*s).to_owned()); + let child_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&child, test, &child_ctx), [(2, "never-run")], "a module below the helper inherits the gate"); + let ungated: HashMap<&str, &str> = gated.iter().map(|(p, s)| (*p, *s)).chain([("crates/x/tests/other.rs", "mod common;\n")]).collect(); + let read = |p: &str| ungated.get(p).map(|s| (*s).to_owned()); + let ungated_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &ungated_ctx), [], "another target loads it on every target"); + } + + #[test] + fn a_cfg_attr_path_on_an_inline_module_is_a_conditional_route() { + let lib = "#[cfg(target_os = \"macos\")]\n#[cfg_attr(target_os = \"macos\", path = \"generated\")]\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 test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let generated = "crates/x/src/generated/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&generated), &read, &Overrides::new()), ..self::ctx() }; + assert_eq!(hits_in(&generated, test, &ctx), [(2, "never-run")], "loaded only where the macOS override applies"); + let unix = lib.replace("#[cfg(target_os = \"macos\")]\n#[cfg_attr(target_os = \"macos\"", "#[cfg_attr(unix"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", unix.as_str())].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&generated), &read, &Overrides::new()), ..self::ctx() }; + assert_eq!(hits_in(&generated, test, &ctx), [], "the override applies on Linux and FreeBSD"); + let default = "crates/x/src/platform/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&default), &read, &Overrides::new()), ..self::ctx() }; + assert_eq!(hits_in(&default, test, &ctx), [(2, "never-run")], "the default directory is used only on Windows"); + } + + #[test] + fn a_path_loaded_file_declares_its_modules_beside_it() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"impl/platform.rs\"]\nmod platform;\n"), + ("crates/x/src/impl/platform.rs", "mod child;\n"), + ("crates/x/src/impl/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 child = "crates/x/src/impl/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..self::ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "impl/platform.rs loads impl/child.rs"); + let below = "crates/x/src/impl/platform/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&below), &read, &overrides), ..self::ctx() }; + 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, &|_| 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] + 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 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> = [ + ("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 [ + ("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, &|_| 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] { + 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), 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" + ); + } + 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}\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() }; + 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_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"); + 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] + 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, &|_| None, &|_| None), ["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"] + .into_iter() + .map(String::from) + .collect(); + let sources = [ + ("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 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, &|_| None); + 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] + fn never_run_skips_later_attributes_and_true_gates() { + let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "a comment inside the predicate"); + let unix = "#[cfg(unix)]\nmod u {\n #[cfg(target_os = \"macos\")]\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", unix, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[1].into_iter().collect())), "cfg(unix) holds on Linux and FreeBSD"); + assert!(touches(hit, Some(&[3].into_iter().collect())), "the macOS-only cfg on the test"); + } + + #[test] + fn never_run_takes_every_declaration_of_a_module() { + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n#[cfg(unix)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let both = Ctx { module_cfgs: module_cfgs(&["crates/x/src/child.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/child.rs", test, &both), [], "the unix declaration builds it on Linux"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let windows = Ctx { module_cfgs: module_cfgs(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()), ..ctx() }; + assert_eq!(hits_in("crates/x/src/child.rs", test, &windows), [(2, "never-run")]); } #[test] 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((3, 4))); - let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); - assert!(touches(hit, Some(&[1].into_iter().collect())), "a change to the cfg alone"); + 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\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + "#[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 cfg and the test"); - let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; - assert_eq!(only("never-run", commented), [], "a comment inside the predicate"); - } - - #[test] - fn never_run_counts_a_changed_mod_declaration_in_another_file() { - let files: HashMap<&str, &str> = - [("crates/x/src/lib.rs", "#[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 (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); - let ctx = Ctx { module_cfgs, module_sites, ..ctx() }; - let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; - let found = lint_file("crates/x/src/child.rs", test, &ctx); - let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); - let changed = |lines: &[usize]| BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))]); - assert!(touches_in(hit, &changed(&[1])), "the cfg on the declaration changed"); - assert!(!touches_in(hit, &changed(&[2])), "only the declaration line changed"); - } - - #[test] - fn never_run_resolves_inline_parents_and_several_owners() { - let files: HashMap<&str, &str> = [ - ("crates/x/src/lib.rs", "#[cfg(windows)]\nmod platform {\n mod child;\n}\n#[cfg(target_os = \"macos\")]\nmod shared;\n"), - ("crates/x/src/main.rs", "mod shared;\n"), - ] - .into_iter() - .collect(); - let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let paths: Vec = ["crates/x/src/platform/child.rs", "crates/x/src/shared.rs"].into_iter().map(String::from).collect(); - let cfgs = module_cfgs(&paths, &read); - assert_eq!(cfgs.get("crates/x/src/platform/child.rs").map(Vec::as_slice), Some(&["windows".to_owned()][..])); - assert!(!cfgs.contains_key("crates/x/src/shared.rs"), "main.rs compiles it on every target"); + 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"); } #[test] @@ -5455,16 +7153,19 @@ 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!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio"); + 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"); 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"); - assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed on"); - assert_eq!(px("assert_eq!(cell_at(button_rect.min.x, 3), 2);"), [], "a coordinate passed on before another argument"); - assert_eq!(px("assert_eq!((button_rect.min.x, button_rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); + assert_eq!(px("assert_eq!(count_items(button_rect), 3);"), [], "a rect passed to a call"); + assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed to a call"); + assert_eq!(px("assert_eq!((button_rect.width()), 120.0);"), [(4, "exact-pixel")], "grouping parentheses"); + assert_eq!(px("assert_eq!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); } @@ -5475,19 +7176,42 @@ 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 commented = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"src/lib.rs\" */ \"fixture.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; - assert_eq!(only("reads-source", commented), [], "a path in a comment"); - let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; - assert_eq!(only("reads-source", dir), [], "a directory whose name ends in .rs"); - let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/input.json\", \"fixtures.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; - assert_eq!(only("reads-source", formatted), [], "a format argument that ends in .rs"); - let formatted_rs = + 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 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 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"; + assert_eq!(only("reads-source", to_rs), [(3, "reads-source")], "a final extension of rs"); + let ext_var = "#[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", ext_var), [], "a final extension that is not a literal"); + 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", formatted_rs), [(3, "reads-source")]); - let joined_json = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures.rs\", root)).join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; - assert_eq!(only("reads-source", joined_json), [], "a join after the format call ends the path"); - let joined_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures\", root)).join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; - assert_eq!(only("reads-source", joined_rs), [(3, "reads-source")]); + 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(); + 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] @@ -5500,44 +7224,87 @@ mod tests { } #[test] - fn never_run_reads_escaped_values_as_unknown() { - let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; - assert_eq!(only("never-run", escaped), []); + 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 never_run_takes_every_declaration_of_a_module() { - let files: HashMap<&str, &str> = - [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n#[cfg(unix)]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + 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"); + 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] + fn a_closure_parameter_shadows_the_outer_binding_in_its_body() { + let closure = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|n| assert_eq!(n, 1));\n}\n"; + assert_eq!(only("fixture-only", closure), []); + let block = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(move |n| {\n assert_eq!(n, 1);\n });\n}\n"; + assert_eq!(only("fixture-only", block), [], "a block body"); + let captured = "#[test]\nfn t() {\n let n = 0;\n results().into_iter().for_each(|m| assert_eq!(n, 0));\n}\n"; + assert_eq!(only("fixture-only", captured), [(2, "fixture-only")], "an unshadowed name is the captured fixture"); + } + + #[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), []); + let bracket = "#[cfg(any(target_os = \"(\", unix))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", bracket), [], "a bracket inside a string value"); + let comma = "#[cfg_attr(target_os = \",\", cfg(windows))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + 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 (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); - let both = Ctx { module_cfgs, module_sites, ..ctx() }; + 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("crates/x/src/child.rs", test, &both), [], "the unix declaration builds it on Linux"); - let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n")].into_iter().collect(); - let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); - let windows = Ctx { module_cfgs, module_sites, ..ctx() }; - assert_eq!(hits_in("crates/x/src/child.rs", test, &windows), [(2, "never-run")]); + assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux"); } #[test] - fn never_run_does_not_count_a_cfg_true_on_every_target() { - let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(unix)]\nmod child;\n")].into_iter().collect(); + 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 (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); - let unix = Ctx { module_cfgs, module_sites, ..ctx() }; - let test = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; - let found = lint_file("crates/x/src/child.rs", test, &unix); - let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); - let changed = BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some([1].into_iter().collect()))]); - assert!(!touches_in(hit, &changed), "cfg(unix) holds on Linux and FreeBSD"); - let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n")].into_iter().collect(); - let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); - let mac = Ctx { module_cfgs, module_sites, ..ctx() }; - let found = lint_file("crates/x/src/child.rs", test, &mac); - let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); - assert!(touches_in(hit, &changed), "a macOS-only module cfg"); + 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), []); } }