xtask: test-lint reads cfg_attr path routes, numeric literals, turbofish reads and spaced cfg strings

- never-run follows `#[cfg_attr(<cond>, path = "…")]` routes: a routed file
  loads under its condition (after earlier routes fail), the default or plain
  `#[path]` file loads only when no route applies, and path_edges follows the
  routed file. Path strings are split outside literals and their escapes decoded.
- The census literal check accepts one numeric literal or fixed arithmetic on
  literals (`1`, `-2`, `1 << 4`); `1 + offset`, `1..limit` and
  `1usize - offset` count as another input.
- reads-source skips a turbofish after `fs::read_to_string` (`::<&str>`).
- cfg predicates keep whitespace inside string values (`"li nux"` is not
  `linux`), and a comma inside a string value no longer splits `any(…)`/`all(…)`.
This commit is contained in:
dotCooCoo
2026-12-01 09:52:27 -08:00
parent 03bddf6a2a
commit 28559ec558
+236 -13
View File
@@ -319,7 +319,11 @@ fn path_edges(files: &[String], read: &dyn Fn(&str) -> Option<String>) -> HashMa
continue;
}
let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) {
// A `cfg_attr` route loads its file when its condition holds.
let rels = path_attr(&m, src.as_bytes(), item, at)
.into_iter()
.chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, rel)| rel));
for rel in rels {
let target = path_target(parent, &inline_mods(&m, at), &rel);
let parents = out.entry(target).or_default();
if !parents.contains(parent) {
@@ -1753,11 +1757,30 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool {
// A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input.
// A minus sign makes a literal only in front of a number (`-2`, not `-offset`).
let s = s.strip_prefix('-').unwrap_or(s);
s.is_empty()
|| s.starts_with(['"', '\'', '|'])
|| s.starts_with("move|")
|| s.starts_with(|c: char| c.is_ascii_digit())
|| matches!(s, "true" | "false" | "None")
let mut start = 0;
let mut operands = 0;
let mut numeric = true;
for (i, c) in s.char_indices().chain([(s.len(), '+')]) {
if !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') {
continue;
}
let head = &s[start..i];
if i < s.len()
&& matches!(c, '+' | '-')
&& head
.strip_suffix(['e', 'E'])
.is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.bytes().all(|c| c.is_ascii_digit() || matches!(c, b'_' | b'.')))
{
continue;
}
if !head.is_empty() {
operands += 1;
numeric &= numeric_literal(head);
}
start = i + c.len_utf8();
}
let numeric = numeric && operands > 0;
s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None")
};
(from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| {
let mut start = name_end;
@@ -1797,6 +1820,61 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool {
})
}
/// Whether the whitespace-free `s` is one numeric literal (`1`, `0x1F`, `2.5f32`, `1_000`, `1e-3`), not
/// an expression that starts with one (`1+offset`, `1..limit`).
fn numeric_literal(s: &str) -> bool {
let b = s.as_bytes();
let radix = match b.get(..2) {
Some(b"0x") => 16,
Some(b"0o") => 8,
Some(b"0b") => 2,
_ => 10,
};
let mut i = if radix == 10 { 0 } else { 2 };
let mut digits = 0;
while let Some(&c) = b.get(i) {
if (c as char).is_digit(radix) {
digits += 1;
} else if c != b'_' {
break;
}
i += 1;
}
if digits == 0 || !b.first().is_some_and(u8::is_ascii_digit) {
return false;
}
if radix == 10 {
if b.get(i) == Some(&b'.') {
i += 1;
if i < b.len() && !b[i].is_ascii_digit() {
return false;
}
while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'_') {
i += 1;
}
}
if matches!(b.get(i), Some(b'e' | b'E')) {
i += 1;
if matches!(b.get(i), Some(b'+' | b'-')) {
i += 1;
}
let mut digits = 0;
while let Some(&c) = b.get(i) {
if c.is_ascii_digit() {
digits += 1;
} else if c != b'_' {
break;
}
i += 1;
}
if digits == 0 {
return false;
}
}
}
matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64")
}
/// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the
/// `::<…>` of a turbofish (`app.run::<Mode>(c)`). `None` when no name precedes the `(`.
fn call_name_end(b: &[u8], from: usize, open: usize) -> Option<usize> {
@@ -3490,7 +3568,11 @@ fn reads_source_hits(file: &File) -> Vec<Hit> {
continue;
}
}
let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!')));
let mut open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!')));
if word == b"read_to_string" {
// A turbofish may follow the filesystem read: `fs::read_to_string::<&str>(path)`.
open = skip_turbofish(m, open);
}
let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue };
// Whitespace inside a literal is part of the path (`"sample.r s"`).
let arg = norm_outside_literals(&code[open + 1..close], &m[open + 1..close]);
@@ -3922,7 +4004,8 @@ fn cfg_value(p: &str, t: &Target) -> Option<bool> {
if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) {
let mut parts = vec![];
let mut start = 0;
for at in top_level_at(args, ",").into_iter().chain([args.len()]) {
// A comma inside a string value does not split the arguments (`target_os = "a,unix"`).
for at in top_level_at(&String::from_utf8_lossy(&mask(args)), ",").into_iter().chain([args.len()]) {
if at > start {
parts.push(cfg_value(&args[start..at], t));
}
@@ -4063,10 +4146,12 @@ fn cfg_attr_preds(text: &str, outer: Option<&str>) -> Vec<String> {
out
}
/// A `cfg` predicate's source text without whitespace or comments. Masking would also blank the
/// string literals `target_os = "macos"` needs, so only comments are blanked.
/// A `cfg` predicate's source text without comments or the whitespace between tokens. Masking would
/// also blank the string literals `target_os = "macos"` needs, so only comments are blanked, and
/// whitespace inside a string literal is kept.
fn pred_text(src: &[u8]) -> String {
norm(&mask_parts(&String::from_utf8_lossy(src), true, false))
let text = String::from_utf8_lossy(src);
norm_outside_literals(&mask_parts(&text, true, false), &mask(&text))
}
/// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the
@@ -4146,8 +4231,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>,
continue;
}
let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
let loads = match path_attr(&m, src.as_bytes(), item, at) {
Some(rel) => path_target(parent, want.chain, &rel) == want.path,
// The condition under which a `cfg_attr` route decides the file, when one does.
// Rust takes the first `path` attribute that applies, so only the routes before a plain
// `#[path]` can take its place.
let mut routed = None;
let direct = words(&m, b"path", item, at).into_iter().find_map(|w| path_attr(&m, src.as_bytes(), w, w + 4).map(|rel| (w, rel)));
let routes = cfg_attr_paths(&m, src.as_bytes(), item, direct.as_ref().map_or(at, |(w, _)| *w));
let fallback = match &direct {
Some((_, rel)) => path_target(parent, want.chain, rel) == want.path,
None => {
// The default file of `mod name;`: `name.rs` or `name/mod.rs` under the declaring
// module's directory and the inline modules around the declaration.
@@ -4163,6 +4254,37 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>,
&& [format!("{name}.rs"), format!("{name}/mod.rs")].iter().any(|f| join_path(&base, f) == want.path)
}
};
let loads = if routes.is_empty() {
fallback
} else {
// The fallback file loads only when no route's condition holds.
let mut conds: Vec<String> = routes
.iter()
.enumerate()
.filter(|(_, (_, rel))| path_target(parent, want.chain, rel) == want.path)
.map(|(i, (c, _))| {
if i == 0 {
c.clone()
} else {
let earlier = routes[..i].iter().map(|(c, _)| format!("not({c})")).collect::<Vec<_>>();
format!("all({},{c})", earlier.join(","))
}
})
.collect();
if fallback {
let all: Vec<&str> = routes.iter().map(|(c, _)| c.as_str()).collect();
conds.push(match all.as_slice() {
[one] => format!("not({one})"),
_ => format!("not(any({}))", all.join(",")),
});
}
routed = match conds.len() {
0 => None,
1 => conds.pop(),
_ => Some(format!("any({})", conds.join(","))),
};
routed.is_some()
};
if !loads {
continue;
}
@@ -4172,6 +4294,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>,
// Every line of a multiline attribute counts.
at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end)));
let mut preds: Vec<String> = attrs.into_iter().map(|a| a.pred).collect();
if let Some(cond) = routed {
preds.push(cond);
// The lines of the `cfg_attr` attributes that route the file.
for w in words(&m, b"cfg_attr", item, at) {
let open = skip_ws(&m, w + 8);
at_lines.extend(lines.of(w)..=lines.of(matching(&m, open).unwrap_or(w)));
}
}
for (p, a, end) in cfgs_over(&m, src.as_bytes(), at) {
preds.push(p);
at_lines.extend(lines.of(a)..=lines.of(end));
@@ -4205,6 +4335,45 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<String> {
})
}
/// The `path = "…"` values inside the `#[cfg_attr(<condition>, …)]` attributes in `m[from..to]`, each
/// with its condition (`#[cfg_attr(unix, path = "x.rs")]` gives `("unix", "x.rs")`). A nested
/// `cfg_attr` joins its condition to the enclosing ones with `all(…)`.
fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> {
fn walk(text: &str, outer: Option<&str>, out: &mut Vec<(String, String)>) {
// Commas and brackets inside a string literal do not split the arguments (`"mac,impl.rs"`).
let cuts = top_level_at(&String::from_utf8_lossy(&mask(text)), ",");
let Some(&first) = cuts.first() else { return };
let cond = match outer {
Some(o) => format!("all({o},{})", &text[..first]),
None => text[..first].to_owned(),
};
let mut start = first + 1;
for cut in cuts[1..].iter().copied().chain([text.len()]) {
let arg = text.get(start..cut).unwrap_or("");
if let Some(v) = arg.strip_prefix("path=") {
// An ordinary or raw string, with its escapes decoded: `"x.rs"`, `r#"x.rs"#`, `"\x6dac.rs"`.
if let Some(rel) = cfg_string(v) {
out.push((cond.clone(), rel));
}
} else if let Some(n) = arg.strip_prefix("cfg_attr(").and_then(|p| p.strip_suffix(')')) {
walk(n, Some(&cond), out);
}
start = cut + 1;
}
}
let mut out = vec![];
for at in words(m, b"cfg_attr", from, to) {
let before = m[..at].trim_ascii_end();
if !before.strip_suffix(b"[").is_some_and(|h| h.trim_ascii_end().ends_with(b"#") && !h.trim_ascii_end().ends_with(b"#!")) {
continue;
}
let open = skip_ws(m, at + 8);
let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue };
walk(&pred_text(&src[open + 1..close]), None, &mut out);
}
out
}
/// `rel` joined to the directory `base`, with `.` and `..` resolved.
fn join_path(base: &str, rel: &str) -> String {
let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect();
@@ -4526,6 +4695,27 @@ mod tests {
assert_eq!(census(derived), [(2, "census")]);
let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n";
assert_eq!(census(successor), [], "arithmetic before the lookup checks a successor, not a round trip");
let fixed_arg = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1), Some(k));\n assert_eq!(Kind::from_id(k.id(), -2), Some(k));\n }\n}\n";
assert_eq!(census(fixed_arg), [(2, "census")], "a numeric literal is not another input");
let shifted = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1 << 4), Some(k));\n }\n}\n";
assert_eq!(census(shifted), [(2, "census")], "fixed arithmetic is not another input");
let offset = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1 + offset), Some(k));\n }\n}\n";
assert_eq!(census(offset), [], "an expression that only starts with a digit is another input");
let suffixed =
"#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1usize - offset), Some(k));\n }\n}\n";
assert_eq!(census(suffixed), [], "a suffixed number minus a variable is another input");
let range = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id(), 1..limit), Some(k));\n }\n}\n";
assert_eq!(census(range), [], "a range with a variable bound is another input");
}
#[test]
fn numeric_literals_are_one_token() {
for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] {
assert!(numeric_literal(s), "{s}");
}
for s in ["1+offset", "1..limit", "1usize-offset", "1<<4"] {
assert!(!numeric_literal(s), "{s}");
}
}
#[test]
@@ -6329,6 +6519,10 @@ mod tests {
fn reads_source_covers_read_to_string_of_rust_files() {
let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
assert_eq!(only("reads-source", read), [(3, "reads-source")]);
let turbofish = "#[test]\nfn t() {\n let s = fs::read_to_string::<&str>(\"src/lib.rs\").unwrap();\n assert!(s.contains(\"x\"));\n}\n";
assert_eq!(only("reads-source", turbofish), [(3, "reads-source")], "a turbofish before the argument");
let suffix = "#[test]\nfn t() {\n assert!(rendered.ends_with::<&str>(\".rs\"));\n}\n";
assert_eq!(only("reads-source", suffix), [], "a string suffix check");
let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
assert_eq!(only("reads-source", data), []);
let comment = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"input.rs\" */ \"data.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n";
@@ -6432,8 +6626,11 @@ mod tests {
assert_eq!(cfg_value("target_os=r#\"lin\\x75x\"#", t), Some(false), "raw contents are kept");
assert_eq!(cfg_value("target_os=\"lin\\qux\"", t), None, "an escape this does not decode");
assert_eq!(cfg_value("target_os=\"macos\"", t), Some(false));
assert_eq!(cfg_value("any(target_os=\"foo,unix,bar\")", t), Some(false), "a comma inside a string value");
let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
assert_eq!(only("never-run", escaped), []);
let spaced = "#[cfg(target_os = \"li nux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
assert_eq!(only("never-run", spaced), [(3, "never-run")], "whitespace inside a string value is kept");
}
#[test]
@@ -6469,6 +6666,32 @@ mod tests {
assert_eq!(declared_cfgs(hashed, "src/lib.rs", &child).map(|(p, _)| p), Some(vec![]));
}
#[test]
fn cfg_attr_path_attributes_load_their_file() {
let child = Loaded { path: "src/child.rs", name: "child", chain: &[] };
let declared = |src: &str| declared_cfgs(src, "src/lib.rs", &child).map(|(p, _)| p);
let routed = "#[cfg(target_os = \"macos\")]\nmod child;\n#[cfg_attr(unix, path = \"child.rs\")]\nmod alias;\n";
assert_eq!(declared(routed), Some(vec!["any(all(target_os=\"macos\"),all(unix))".to_owned()]));
let away = "#[cfg_attr(target_os = \"macos\", path = \"mac_child.rs\")]\nmod child;\n";
assert_eq!(declared(away), Some(vec!["not(target_os=\"macos\")".to_owned()]), "the default file loads only when the condition fails");
let comma = Loaded { path: "src/mac,impl.rs", name: "imp", chain: &[] };
let routed = "#[cfg_attr(target_os = \"macos\", path = \"mac,impl.rs\")]\nmod imp;\n";
assert_eq!(declared_cfgs(routed, "src/lib.rs", &comma).map(|(p, _)| p), Some(vec!["target_os=\"macos\"".to_owned()]), "a comma in the path");
let escaped = "#[cfg_attr(unix, path = \"\\x63hild.rs\")]\nmod alias;\n";
assert_eq!(declared(escaped), Some(vec!["unix".to_owned()]), "an escape in the path is decoded");
let ordered = "#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\n#[path = \"child.rs\"]\nmod alias;\n";
assert_eq!(declared(ordered), Some(vec!["not(target_os=\"macos\")".to_owned()]), "an earlier route takes the place of a plain path");
let routes = "#[cfg_attr(unix, path = \"unix.rs\")]\n#[cfg_attr(target_os = \"linux\", path = \"child.rs\")]\nmod alias;\n";
assert_eq!(declared(routes), Some(vec!["all(not(unix),target_os=\"linux\")".to_owned()]));
let later = "#[path = \"child.rs\"]\n#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\nmod alias;\n";
assert_eq!(declared(later), Some(vec![]), "a route after a plain path never applies");
let files: HashMap<&str, &str> =
[("crates/x/src/lib.rs", "#[cfg_attr(target_os = \"macos\", path = \"mac.rs\")]\nmod imp;\n")].into_iter().collect();
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
let edges = path_edges(&["crates/x/src/lib.rs".to_owned()], &read);
assert_eq!(edges.get("crates/x/src/mac.rs"), Some(&vec!["crates/x/src/lib.rs".to_owned()]));
}
#[test]
fn path_declarations_outside_the_module_directory_are_followed() {
let files: HashMap<&str, &str> = [