Doc tests: treat cfg_attr lints by what they could do, and skip raw C strings

The check did not read lint attributes inside cfg_attr at all, and it
does not evaluate cfg conditions. Two roots passed although the
condition all() is always true:

- #![cfg_attr(all(), forbid(unsafe_code))] with doc-test deny: the
  library forbids unsafe code, so its doc tests need forbid.
- #![doc(test(attr(deny(unsafe_code), cfg_attr(all(), allow(unsafe_code)))))]:
  the allow lowers the deny.

A cfg_attr now counts only in the direction that is never too lenient:
a forbid inside one asks the doc tests for forbid, and an allow, warn
or expect inside one lowers the doc tests' level. A deny or forbid
inside cfg_attr in the doc-test list still does not count.

The comment and literal scanner also skips raw C strings (cr"..."), so
text such as #![forbid(unsafe_code)] inside one is not read as an
attribute. Tests cover each case.
This commit is contained in:
dotCooCoo committed 2026-12-03 21:17:30 -08:00
1 parent fb0bce30e6
commit 4e2581f63d
1 file changed
+30 -10
+30 -10
View File
@@ -50,7 +50,7 @@ fn check_root(name: &str, root: &Path, path: &Path) -> Result<Option<String>, St
/// strictly as the library does.
fn problem(src: &str) -> Option<&'static str> {
let attrs = inner_attributes(src);
let forbids = attrs.iter().any(|a| args(a, "forbid").is_some_and(names_unsafe_code));
let forbids = attrs.iter().any(|a| sets_level(a, &["forbid"]));
match doc_test_level(&attrs) {
Some(Level::Forbid) => None,
_ if forbids => Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]"),
@@ -72,16 +72,17 @@ const LEVELS: [(&str, Level); 5] =
[("forbid", Level::Forbid), ("deny", Level::Deny), ("allow", Level::Allow), ("warn", Level::Allow), ("expect", Level::Allow)];
/// The `unsafe_code` level that the `#![doc(test(attr(...)))]` attributes leave in force, read in
/// order. Only lint attributes that are direct members of `attr(...)` count, so one inside
/// `cfg_attr(...)` is ignored. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and
/// nothing lowers a `forbid`.
/// order. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and nothing lowers a
/// `forbid`. The check does not evaluate `cfg_attr` conditions: a `deny` or `forbid` inside
/// `cfg_attr(...)` does not count, and an `allow`, `warn` or `expect` inside one lowers the level.
fn doc_test_level(attrs: &[String]) -> Option<Level> {
let mut level = None;
for doc in attrs.iter().filter_map(|a| args(a, "doc")) {
for test in items(doc).into_iter().filter_map(|i| args(i, "test")) {
for attr in items(test).into_iter().filter_map(|i| args(i, "attr")) {
for lint in items(attr) {
let next = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l));
let direct = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l));
let next = direct.or_else(|| sets_level(lint, &["allow", "warn", "expect"]).then_some(Level::Allow));
if let Some(next) = next
&& level != Some(Level::Forbid)
{
@@ -94,6 +95,15 @@ fn doc_test_level(attrs: &[String]) -> Option<Level> {
level
}
/// Whether `attr` is one of the lint attributes `names` applied to `unsafe_code`, directly or
/// inside `cfg_attr(...)`, whatever its condition.
fn sets_level(attr: &str, names: &[&str]) -> bool {
if names.iter().any(|name| args(attr, name).is_some_and(names_unsafe_code)) {
return true;
}
args(attr, "cfg_attr").is_some_and(|inner| items(inner).into_iter().skip(1).any(|a| sets_level(a, names)))
}
/// The argument list of `item` when it is exactly `name(...)`.
fn args<'a>(item: &'a str, name: &str) -> Option<&'a str> {
let rest = item.strip_prefix(name)?.strip_prefix('(')?.strip_suffix(')')?;
@@ -170,7 +180,7 @@ fn inner_attributes(src: &str) -> Vec<String> {
}
/// `src` with line and (nested) block comments replaced by a space, and the contents of string,
/// raw string and character literals removed.
/// raw string (including raw byte and raw C string) and character literals removed.
fn code_only(src: &str) -> String {
let c: Vec<char> = src.chars().collect();
let mut out = String::with_capacity(src.len());
@@ -203,7 +213,7 @@ fn code_only(src: &str) -> String {
}
out.push(' ');
}
'r' | 'b' if !ident_before && raw_string_hashes(&c, i).is_some() => {
'r' | 'b' | 'c' if !ident_before && raw_string_hashes(&c, i).is_some() => {
let (open, hashes) = raw_string_hashes(&c, i).unwrap_or((i, 0));
let mut j = open + 1;
while j < c.len() && !(c[j] == '"' && (1..=hashes).all(|k| c.get(j + k) == Some(&'#'))) {
@@ -241,11 +251,11 @@ fn code_only(src: &str) -> String {
out
}
/// For a raw string literal starting at `i` (`r"`, `r#"`, `br"`...), the index of its opening
/// quote and its number of `#`s.
/// For a raw string literal starting at `i` (`r"`, `r#"`, `br"`, `cr"`...), the index of its
/// opening quote and its number of `#`s.
fn raw_string_hashes(c: &[char], i: usize) -> Option<(usize, usize)> {
let mut j = i;
if c.get(j) == Some(&'b') {
if matches!(c.get(j), Some('b' | 'c')) {
j += 1;
}
if c.get(j) != Some(&'r') {
@@ -312,6 +322,7 @@ mod tests {
assert_eq!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n"), NEEDS_DENY);
assert_eq!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n"), NEEDS_DENY);
assert_eq!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n"), NEEDS_DENY);
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nconst S: &CStr = cr#\"\" #![forbid(unsafe_code)] \"#;\n"), None);
assert_eq!(problem("const Q: char = '\\'';\nconst S: &str = \"/*\";\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
}
@@ -337,6 +348,15 @@ mod tests {
assert_eq!(problem("#![doc(test(no_crate_inject, attr(deny(unsafe_code))))]\n"), None);
}
#[test]
fn cfg_attr_can_only_lower_the_doc_tests_or_raise_the_library() {
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(all(), allow(unsafe_code)))))]\n"), NEEDS_DENY);
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(test, cfg_attr(all(), warn(unsafe_code))))))]\n"), NEEDS_DENY);
assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID);
assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
assert_eq!(problem("#![cfg_attr(forbid, deny(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
}
#[test]
fn a_later_allow_lowers_deny_but_not_forbid() {
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]\n"), NEEDS_DENY);