From 8387f54b97d17d2c4f0616652d41fa09b82f5cdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:05:15 -0800 Subject: [PATCH] Doc tests: count only crate-level attributes in the unsafe-code check The check read every #![...] attribute in a library root, including ones inside a module's braces. A root with mod tests { #![doc(test(attr(deny(unsafe_code))))] } and no crate-level attribute passed, although an attribute inside a module does not apply to the crate's other doc tests. A #![forbid(unsafe_code)] inside a module was also read as the library forbidding unsafe code. Attributes inside braces are now skipped, with a test for each case. --- xtask/src/doc_tests.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 1ed8871ceb..2cc73d2ce9 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -63,14 +63,21 @@ fn problem(src: &str) -> Option<&'static str> { } } -/// The body of every `#![...]` attribute in `src`, without whitespace, read across line breaks. -/// Comments are skipped, and string and character literals are read as empty. +/// The body of every crate-level `#![...]` attribute in `src`, without whitespace, read across +/// line breaks. Attributes inside braces (a module, a function) are skipped, comments are +/// skipped, and string and character literals are read as empty. fn inner_attributes(src: &str) -> Vec { let code: Vec = code_only(src).chars().filter(|c| !c.is_whitespace()).collect(); let mut out = Vec::new(); + let mut braces = 0usize; let mut i = 0; while i + 2 < code.len() { - if code[i] != '#' || code[i + 1] != '!' || code[i + 2] != '[' { + if code[i] == '{' { + braces += 1; + } else if code[i] == '}' { + braces = braces.saturating_sub(1); + } + if braces > 0 || code[i] != '#' || code[i + 1] != '!' || code[i + 2] != '[' { i += 1; continue; } @@ -260,6 +267,14 @@ mod tests { assert_eq!(problem("#![forbid(unsafe_code)]\n// #![doc(test(attr(forbid(unsafe_code))))]\n"), NEEDS_FORBID); } + #[test] + fn attributes_inside_a_module_do_not_count() { + assert_eq!(problem("mod tests {\n #![doc(test(attr(deny(unsafe_code))))]\n}\n"), NEEDS_DENY); + assert_eq!(problem("#![forbid(unsafe_code)]\nmod a { #![doc(test(attr(forbid(unsafe_code))))] }\n"), NEEDS_FORBID); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a { #![forbid(unsafe_code)] }\n"), None); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a {\n fn f() {}\n}\n"), None); + } + #[test] fn spacing_and_other_attributes_in_the_list_are_accepted() { assert_eq!(problem("#![doc(test(attr(deny(warnings), forbid( unsafe_code ))))]\n#![forbid(unsafe_code)]\n"), None);