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.
This commit is contained in:
dotCooCoo
2026-12-03 12:05:15 -08:00
parent a520deb991
commit 8387f54b97
+18 -3
View File
@@ -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<String> {
let code: Vec<char> = 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);