From 2e1b575fdca0d620c1d9a379e3b855236a16ec3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:09:12 -0800 Subject: [PATCH] xtask: test-lint census rule reads loop labels, radix bounds and closure names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #10585. The census rule now: - treats a labeled `for` (`'inner: for _ in 0..0`) like an unlabeled one when deciding whether its body runs; - reads hex, octal and binary range bounds (`0x0..0x1`) and borrowed or parenthesized array literals (`&[1]`, `(&[1])`) as loop sources; - does not count a path call (`other::run()`) as a call to a local closure; - counts an async closure's future as run by `block_on` only when it is the whole argument of `block_on` itself, not of `discard_block_on` or of a longer expression, and allows a space before the parenthesis; - finds the `let` keyword without splitting a name such as `inlet_fn`; - accepts a trailing comma after a closure stored in `Some(…)`. --- xtask/src/test_lint.rs | 103 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 91 insertions(+), 12 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e517292e73..1c69802987 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2442,17 +2442,32 @@ fn numeric_literal(s: &str) -> bool { matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") } -/// The value of a decimal integer literal such as `3`, `-4`, `1_000` or `2u8`. +/// The value of an integer literal such as `3`, `-4`, `1_000`, `2u8` or `0x1F`. fn integer_literal(s: &str) -> Option { let (sign, digits) = s.strip_prefix('-').map_or((1, s), |rest| (-1, rest)); + let (radix, unprefixed) = [("0x", 16), ("0o", 8), ("0b", 2)] + .iter() + .find_map(|&(prefix, radix)| digits.strip_prefix(prefix).map(|rest| (radix, rest))) + .unwrap_or((10, digits)); let body = ["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"] .iter() - .find_map(|suffix| digits.strip_suffix(suffix)) - .unwrap_or(digits); - if !numeric_literal(digits) || !body.bytes().all(|c| c.is_ascii_digit() || c == b'_') { + .find_map(|suffix| unprefixed.strip_suffix(suffix)) + .unwrap_or(unprefixed); + if !numeric_literal(digits) || body.is_empty() || !body.chars().all(|c| c.is_digit(radix) || c == '_') { return None; } - body.replace('_', "").parse::().ok().map(|n| sign * n) + i128::from_str_radix(&body.replace('_', ""), radix).ok().map(|n| sign * n) +} + +/// The text after the last `let` keyword in `head` that a binding follows (`let x`, not the `let` +/// inside a name such as `inlet_fn`). +fn after_let(head: &str) -> Option<&str> { + let b = head.as_bytes(); + head.match_indices("let") + .map(|(at, _)| at) + .filter(|&at| (at == 0 || !is_ident(b[at - 1])) && b.get(at + 3).is_some_and(u8::is_ascii_whitespace)) + .last() + .map(|at| &head[at + 3..]) } /// Whether the source of the `for … in ` head `head` yields at least one item, for an @@ -2461,8 +2476,15 @@ fn integer_literal(s: &str) -> Option { fn literal_source_yields(head: &[u8]) -> Option { let &kw = words(head, b"in", 3, head.len()).first()?; let mut source: String = String::from_utf8_lossy(&head[kw + 2..]).chars().filter(|c| !c.is_whitespace()).collect(); - while source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { - source = source[1..source.len() - 1].to_owned(); + // A borrowed array literal (`&[a, b]`, `&mut [x; 0]`) yields as many items as the array. + loop { + if let Some(rest) = source.strip_prefix('&') { + source = rest.strip_prefix("mut").filter(|r| r.starts_with(['[', '('])).unwrap_or(rest).to_owned(); + } else if source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { + source = source[1..source.len() - 1].to_owned(); + } else { + break; + } } if source.starts_with('[') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { let items = &source[1..source.len() - 1]; @@ -2556,6 +2578,12 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } } let prefix = b[head..open].trim_ascii(); + // A loop label (`'outer: for …`) comes before the keyword. + let prefix = prefix + .strip_prefix(b"'") + .map(|rest| rest.split_at(rest.iter().take_while(|&&c| is_ident(c)).count())) + .and_then(|(label, rest)| rest.strip_prefix(b":").filter(|r| !label.is_empty() && r.first() != Some(&b':'))) + .map_or(prefix, <[u8]>::trim_ascii_start); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active) { @@ -2759,7 +2787,9 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as .into_iter() .filter(|&at| { let open = skip_ws(b, at + name.len()); - if b[..at].trim_ascii_end().last() == Some(&b'.') || b.get(open) != Some(&b'(') { + // A method (`other.run()`) or a path (`other::run()`) names something else. + let before = b[..at].trim_ascii_end(); + if before.last() == Some(&b'.') || before.ends_with(b"::") || b.get(open) != Some(&b'(') { return false; } if words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { @@ -2771,7 +2801,14 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as let Some(close) = matching(b, open) else { return false }; let next = skip_ws(b, close + 1); let awaited = b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); - awaited || b[..at].trim_ascii_end().ends_with(b"block_on(") + // The future is the whole argument of `block_on` itself, not of a name that ends with it + // (`discard_block_on`), and not part of a longer expression that may never poll it. + let paren = b[..at].trim_ascii_end().len().checked_sub(1).filter(|&p| b[p] == b'('); + let blocked = paren.is_some_and(|p| { + b[..p].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && matching(b, p).is_some_and(|c| matches!(b[close + 1..c].trim_ascii(), b"" | b",")) + }); + awaited || blocked }) .collect() } @@ -2869,7 +2906,7 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); let close = matching(b, i).unwrap_or(to); - let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); + let binding = head.strip_suffix('=').and_then(after_let); let stored = binding.is_none() && stored_closure(b, head, close, to); let Some(name) = binding.and_then(|binding| pattern_names(binding).last()).or_else(|| stored.then(String::new)) else { continue }; let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); @@ -2899,8 +2936,10 @@ fn stored_closure(b: &[u8], head: &str, close: usize, to: usize) -> bool { let last = segments.next().unwrap_or_default(); let owner = segments.next().unwrap_or_default(); let constructor = matches!(last, "Some" | "Ok" | "Err") || (last == "new" && matches!(owner, "Box" | "Rc" | "Arc")); - let Some(binding) = rest.trim_end().strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { return false }; - let paren = skip_ws(b, close + 1); + let Some(binding) = rest.trim_end().strip_suffix('=').and_then(after_let) else { return false }; + // A trailing comma may follow the closure (`Some(|| { … },)`). + let after = skip_ws(b, close + 1); + let paren = if b.get(after) == Some(&b',') { skip_ws(b, after + 1) } else { after }; let semi = skip_ws(b, paren + 1); constructor && binding.starts_with(char::is_whitespace) @@ -10311,6 +10350,46 @@ mod tests { ); } + #[test] + fn census_reads_labels_radixes_paths_and_let_names() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("for _ in 0x0..0x1 { app.run(c); } assert!(menu(c).is_some());"), [], "a hex range with one item runs its body"); + assert_eq!( + census("'inner: for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled empty loop does not run its body" + ); + assert_eq!( + census("let run = || app.run(c); other::run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a path call does not call the local closure" + ); + assert_eq!( + census("let run = async || app.run(c); discard_block_on(run()); assert!(menu(c).is_some());"), + [(2, "census")], + "a callee that only ends in block_on does not run the future" + ); + assert_eq!( + census("let run = async || app.run(c); block_on (run()); assert!(menu(c).is_some());"), + [], + "block_on with a space before its parenthesis runs the future" + ); + assert_eq!(census("for _ in &[1] { app.run(c); } assert!(menu(c).is_some());"), [], "a borrowed array literal with one item runs its body"); + assert_eq!(census("'inner: for _ in (&[1]) { app.run(c); } assert!(menu(c).is_some());"), [], "a parenthesized borrowed array runs its body"); + assert_eq!( + census("let run = async || app.run(c); block_on(run().into_stream().take(0).count()); assert!(menu(c).is_some());"), + [(2, "census")], + "a future that is only part of block_on's argument may never be polled" + ); + assert_eq!(census("let inlet_fn =|| { app.run(c); }; inlet_fn(); assert!(menu(c).is_some());"), [], "a closure name that contains let"); + assert_eq!( + census("let mut input = c; let _saved = Some(|| { input = fallback(); },); app.run(input); assert!(menu(c).is_some());"), + [], + "a stored closure with a trailing comma never runs" + ); + } + #[test] fn census_needs_evidence_that_the_call_runs_on_the_entry() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n");