From a7654fc63850be4ca7a0c42f05acbb0077e6aa2a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:17:26 -0800 Subject: [PATCH] xtask: test-lint matches base tests by place and keeps route kinds apart - never-run in changed mode lints the file as it was at the base and matches a test by its name and its place among tests of that name, so a test that was already off is not counted again when lines move. - A file reached by name inherits only the gates of named declarations, and one reached through #[path] only those of #[path] declarations. - The changed-file walk also reads the base child declarations of a #[path]-loaded file, so a removed `mod child;` still reaches the child. - reads-source classifies the outer path step, not a join nested in its argument. - mirror treats complete raw string literals as keys. - A raw cfg value keeps the quotes inside it (r#""unix""# is not unix). - census keeps word boundaries, so `k as usize` reads `k` and the local `kasusize` does not. - fixture-only finds a for loop's `in` across line breaks. --- xtask/src/test_lint.rs | 243 +++++++++++++++++++++++++++++++++-------- 1 file changed, 197 insertions(+), 46 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index fe0090fa33..40ac3b2f25 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -330,7 +330,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. let seeds: Vec = changed.keys().cloned().collect(); let below: Vec = - descendants(&seeds, &files, &overrides, &base_overrides, &read_work).into_iter().filter(|p| !changed.contains_key(p)).collect(); + descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); @@ -340,14 +340,17 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - // The base's `never-run` hits, computed once per file on its first parent-attributed hit. - let base_off: RefCell>> = RefCell::new(HashMap::new()); + // The base's `never-run` hits on the file as it was at the base (the current source when the + // file is new or moved), computed once per file on its first parent-attributed hit. + let base_off: RefCell)>> = RefCell::new(HashMap::new()); let newly_off = |path: &str, src: &str, hit: &Hit| { let mut cache = base_off.borrow_mut(); - let off = cache - .entry(path.to_owned()) - .or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()); - !off.contains(&(hit.test.clone(), hit.line)) + let (base_src, off) = cache.entry(path.to_owned()).or_insert_with(|| { + let base_src = read_base(path).unwrap_or_else(|| src.to_owned()); + let off = lint_file(path, &base_src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + (base_src, off) + }); + !already_off(off, base_src, src, hit) }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { @@ -369,11 +372,21 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { finish(&counted, older, present.len(), &base) } -/// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the -/// test of `hit`. Tests of one name in different inline modules are told apart by their line. -#[cfg(test)] -fn already_off(base: &[Hit], hit: &Hit) -> bool { - base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +/// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test +/// of `hit` in `src`. A test is matched by its name and its place among the tests of that name, so +/// lines that moved still match and tests of one name in different inline modules stay apart. +fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { + let place = test_place(src, &hit.test, hit.line); + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match place { + Some(place) => test_place(base_src, &h.test, h.line) == Some(place), + None => h.line == hit.line, + }) +} + +/// The index of the test `name` whose `fn` is on `line` among the tests of that name in `src`. +fn test_place(src: &str, name: &str, line: usize) -> Option { + let lines = Lines::new(src); + tests_in(&mask(src)).iter().filter(|t| t.name == name).position(|t| lines.of(t.fn_at) == line) } /// The directory holding the modules that the file `p` declares by name: its own directory for @@ -387,13 +400,15 @@ fn module_dir(p: &str) -> String { /// The files of `files` that the files `start` load, directly or through modules in between: the /// files under their module directories and the files their current or base `#[path]` declarations load. /// A file loaded through `#[path]` also loads the modules it declares by name from its own directory -/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read`. +/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read` and, for the +/// declarations a change removed, through `read_base`. fn descendants( start: &[String], files: &[String], overrides: &Overrides, base_overrides: &Overrides, read: &dyn Fn(&str) -> Option, + read_base: &dyn Fn(&str) -> Option, ) -> Vec { let mut seen: BTreeSet = start.iter().cloned().collect(); let mut frontier: Vec = start.to_vec(); @@ -404,7 +419,12 @@ fn descendants( return vec![]; } let dir = p.rsplit_once('/').map_or("", |(d, _)| d); - read(p).map_or(vec![], |src| declared_names(&src).into_iter().flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]).collect()) + [read(p), read_base(p)] + .into_iter() + .flatten() + .flat_map(|src| declared_names(&src)) + .flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]) + .collect() }; let dirs: Vec = frontier.iter().map(|p| module_dir(p)).chain(frontier.iter().flat_map(beside)).collect(); let next: Vec = files @@ -973,6 +993,25 @@ fn norm(b: &[u8]) -> String { String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() } +/// [`norm`], except that whitespace between two identifier characters becomes one space, so +/// `k as usize` stays three words and `kasusize` stays one. Removing the spaces gives [`norm`]. +fn norm_words(b: &[u8]) -> String { + let mut out = vec![]; + let mut gap = false; + for &c in b { + if c.is_ascii_whitespace() { + gap = true; + continue; + } + if gap && is_ident(c) && out.last().copied().is_some_and(is_ident) { + out.push(b' '); + } + gap = false; + out.push(c); + } + String::from_utf8_lossy(&out).into_owned() +} + /// Line starts, to turn byte offsets into 1-based lines. struct Lines(Vec); @@ -1545,7 +1584,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { helpers_in(from, to).is_empty() && !rejects(body) && !inside.is_empty() - && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) + && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::>(), var)) }; for at in words(m, b"for", v.t.open, v.t.close) { let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue }; @@ -1788,10 +1827,10 @@ fn weak_predicate_within(pred: &str, depth: usize) -> bool { } /// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares -/// a lookup or parse with the entry itself. +/// a lookup or parse with the entry itself. `args` are written as [`norm_words`] gives them. fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { match guard_arg_count(name) { - 1 => args.first().is_some_and(|a| weak_predicate(a)), + 1 => args.first().is_some_and(|a| weak_predicate(&a.replace(' ', ""))), 2 if name.ends_with("_ne") => false, 2 => match args { [a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)), @@ -1801,7 +1840,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { } } -/// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole +/// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole /// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so /// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's /// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is @@ -1826,20 +1865,16 @@ fn round_trip_call(op: &str, var: &str) -> bool { }) } -/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or -/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`). +/// Whether `s`, written as [`norm_words`] gives it, reads the binding `var`: a whole word that is not +/// a field or path segment (`config.k`, `m::k`), alone or cast (`k as usize`). `kasusize` is one word. fn reads_ident(s: &str, var: &str) -> bool { - const PRIMITIVES: &[&str] = - &["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"]; let b = s.as_bytes(); - let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident); !var.is_empty() && s.match_indices(var).any(|(at, _)| { let end = at + var.len(); let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); let path = at > 1 && &b[at - 2..at] == b"::"; - let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends))); - !(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast) + !(at > 0 && is_ident(b[at - 1])) && !field && !path && !b.get(end).copied().is_some_and(is_ident) }) } @@ -3137,10 +3172,11 @@ fn reads_source_hits(file: &File) -> Vec { // The final path step names the file read: the last literal of `root.join("src/lib.rs")` // or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the // extension of a final `.with_extension("json")`. A final step whose argument is not a - // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. + // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on + // the outer path count: a `.join` inside another step's argument does not. b"read_to_string" => { let step = |s: &'static str| { - arg.rfind(s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + rfind_outer(&arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) }; match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { Some((_, ".with_extension(", ext)) => ext.trim_start_matches('r').trim_matches('#') == "\"rs\"", @@ -3161,6 +3197,35 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// The offset of the last `pat` in `expr` outside every bracket and string literal. +fn rfind_outer(expr: &str, pat: &str) -> Option { + let b = expr.as_bytes(); + let (mut depth, mut in_str, mut found) = (0usize, false, None); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + if depth == 0 && b[i..].starts_with(pat.as_bytes()) { + found = Some(i); + } + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + _ => {} + } + } + i += 1; + } + found +} + /// The last string literal in a (whitespace-free) expression, quotes included. Inside a /// `format!`-family call, an argument is not the file name, so the format string is returned /// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. @@ -3284,12 +3349,22 @@ fn norm_outside_literals(b: &[u8]) -> String { String::from_utf8_lossy(&out).into_owned() } +/// The contents of a complete raw string literal written after its `r`: `"a"` and `#"a"#` give `a`, +/// and `#""a""#` gives `"a"`. `None` when `s` is not one whole literal. +fn raw_literal_body(s: &str) -> Option<&str> { + let hashes = s.len() - s.trim_start_matches('#').len(); + let close = format!("\"{}", "#".repeat(hashes)); + let body = s[hashes..].strip_prefix('"')?.strip_suffix(close.as_str())?; + (!body.contains(close.as_str())).then_some(body) +} + /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, /// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). fn key_like(arg: &str) -> bool { let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); match arg.as_bytes().first() { Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), None => false, @@ -3406,9 +3481,9 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option Option { // An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's // contents are kept as written. let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { - Some(raw) => (k, raw.trim_matches('#').trim_matches('"').to_owned()), + Some(raw) => (k, raw_literal_body(raw).unwrap_or(raw).to_owned()), None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), }); let value = value.as_str(); @@ -3960,8 +4035,9 @@ struct Loaded<'a> { /// items, inline modules and file around them, with the 1-based lines of those declarations and /// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None` /// when `src` loads no such file. `owns_dir` reads `parent` as loaded through `#[path]`, which -/// declares its modules in its own directory, as a `mod.rs` or a crate root does. -fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Option<(Vec, Vec)> { +/// declares its modules in its own directory, as a `mod.rs` or a crate root does. `via` keeps only +/// the declarations that load `want` by name (`Named`) or through `#[path]` (`Path`). +fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool, via: Via) -> Option<(Vec, Vec)> { let m = mask(src); let lines = Lines::new(src); let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); @@ -3993,13 +4069,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Opti let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; let fallback = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => overrides_here(&rel), + Some(rel) => via != Via::Named && overrides_here(&rel), None => { - &m[start..end] == want.name.as_bytes() + via != Via::Path + && &m[start..end] == want.name.as_bytes() && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } }; - let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| via != Via::Named && overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); let route = match (fallback, selected.is_empty(), conditional.is_empty()) { (true, _, true) => None, (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::>().join(","))), @@ -4294,7 +4371,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over // can both load it): its tests are off only when every one of them leaves them out. if via != Via::Path { found.extend(candidates.iter().filter_map(|c| { - read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, named(c))) + read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, named(c))) })); } if chain.is_empty() { @@ -4305,7 +4382,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over continue; } let want = Loaded { path: at, name: &name, chain: inline }; - found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, Via::Any))); + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, Via::Any))); } // A file loaded through `#[path]` owns its directory like a `mod.rs`: its `mod child;` // loads the `child.rs` beside it (`impl/platform.rs` loads `impl/child.rs`). @@ -4313,7 +4390,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option, overrides: &Over .keys() .filter(|k| via != Via::Path && k.as_str() != at && !owns_its_dir(k) && k.rsplit_once('/').is_some_and(|(d, _)| d == module_dir)); for owner in path_loaded { - found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true)).map(|f| (owner.clone(), f, Via::Path))); + found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true, via)).map(|f| (owner.clone(), f, Via::Path))); } } if via == Via::Path || beside_roots(at) { @@ -4519,6 +4596,8 @@ mod tests { assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let one_word = "#[test]\nfn t() {\n let kasusize = 3;\n for k in KEYS {\n assert_eq!(lookup(kasusize), k);\n }\n}\n"; + assert_eq!(census(one_word), [], "a fixed local spelled like a cast of the entry"); let field = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); @@ -6084,6 +6163,8 @@ mod tests { assert_eq!(only("mirror", order), [], "positions of two entries in one list"); let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let raw = "#[test]\nfn t() {\n assert_eq!(at(r#\"B\"#), at(r#\"A\"#) + 1);\n assert_eq!(at(r\"B\"), at(r\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", raw), [], "raw string keys"); let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; @@ -6217,7 +6298,7 @@ mod tests { #[test] fn never_run_follows_the_cfg_around_the_mod_declaration() { let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; - let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false).map(|(p, _)| p); + let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false, Via::Any).map(|(p, _)| p); let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; @@ -6339,10 +6420,25 @@ mod tests { let base = lint_file(path, src, &ctx()); let now = lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); - let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, h)).map(|h| h.line).collect(); + let off: Vec = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.line).collect(); assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); } + #[test] + fn a_test_off_at_the_base_is_matched_in_the_base_source() { + // At the base an inline module gate turned the test off; the change removes that gate and + // gates the parent instead, which also moves the test up a line. + let path = "crates/x/src/child.rs"; + let before = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<&str> = + now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.test.as_str()).collect(); + assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); + } + #[test] fn never_run_follows_a_tests_module_directory_under_src() { let files: HashMap<&str, &str> = @@ -6430,7 +6526,56 @@ mod tests { assert_eq!(hits_in(&below, test, &ctx), [], "the path-loaded file does not load impl/platform/child.rs"); let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; let all: Vec = files.keys().map(|p| (*p).to_owned()).collect(); - assert!(descendants(&seeds, &all, &overrides, &Overrides::new(), &read).contains(&child), "a change to platform.rs reaches child.rs"); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child), + "a change to platform.rs reaches child.rs" + ); + } + + #[test] + fn a_named_route_takes_only_the_gates_of_named_declarations() { + // `parent.rs` is loaded by name on macOS and through `#[path]` on Linux. Only the named route + // loads `parent/child.rs`; the `#[path]` route loads `child.rs` beside `parent.rs`. + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n#[cfg(target_os = \"linux\")]\n#[path = \"parent.rs\"]\nmod p2;\n"), + ("crates/x/src/parent.rs", "mod child;\n"), + ("crates/x/src/parent/child.rs", ""), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + for (child, expected) in [("crates/x/src/parent/child.rs", vec![(2, "never-run")]), ("crates/x/src/child.rs", vec![])] { + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(child, test, &ctx), expected, "{child}"); + } + } + + #[test] + fn a_removed_child_declaration_still_reaches_the_child() { + let work: HashMap<&str, &str> = [ + ( + "crates/x/src/lib.rs", + "#[path = \"impl/platform.rs\"]\nmod platform;\n#[cfg(target_os = \"macos\")]\n#[path = \"impl/child.rs\"]\nmod child;\n", + ), + ("crates/x/src/impl/platform.rs", ""), + ("crates/x/src/impl/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| work.get(p).map(|s| (*s).to_owned()); + let read_base = |p: &str| if p == "crates/x/src/impl/platform.rs" { Some("mod child;\n".to_owned()) } else { read(p) }; + let overrides = path_overrides(work.iter().map(|(p, s)| (*p, *s))); + let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; + let all: Vec = work.keys().map(|p| (*p).to_owned()).collect(); + let child = "crates/x/src/impl/child.rs".to_owned(); + assert!(!descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child)); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &read_base).contains(&child), + "the base `mod child;` that the change removed still leads to child.rs" + ); } #[test] @@ -6594,7 +6739,7 @@ mod tests { let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::>(); assert!( - descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None).contains(&child.to_owned()), + descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None, &|_| None).contains(&child.to_owned()), "the removed route still reaches the shared tests" ); for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { @@ -6602,7 +6747,7 @@ mod tests { assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); assert!(parent_changed, "deletions and shifted lines still change a base route"); - assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), &hit), ran); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), test, test, &hit), ran); assert!( route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), "a base route parent counts even without inherited predicates" @@ -6683,6 +6828,8 @@ mod tests { assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + assert_eq!(cfg_value("target_family=r#\"unix\"#", linux), Some(true)); + assert_eq!(cfg_value("target_family=r#\"\"unix\"\"#", linux), Some(false), "quotes inside a raw string are part of the value"); } #[test] @@ -6705,7 +6852,7 @@ mod tests { let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); let seeds: Vec = got.keys().cloned().collect(); let files = ["crates/x/src/shared.rs".to_owned()]; - assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None), ["crates/x/src/shared.rs"]); + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None, &|_| None), ["crates/x/src/shared.rs"]); } #[test] @@ -6720,7 +6867,7 @@ mod tests { ]; let overrides = path_overrides(sources); let read = |p: &str| sources.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); - let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read, &|_| None); assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); } @@ -6817,6 +6964,8 @@ mod tests { let joined = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); + let nested = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(if root.join(\"config.rs\").exists() { \"a.json\" } else { \"b.json\" })).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", nested), [], "a join inside the outer join's argument"); let extension = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(\"json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", extension), [], "a final extension that is not rs"); let to_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"lib.txt\").with_extension(\"rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; @@ -6856,6 +7005,8 @@ mod tests { fn a_for_binding_shadows_the_outer_one_in_its_body() { let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n"; assert_eq!(only("fixture-only", looped), []); + let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); }