Files
vectorcraft/xtask/src/doc_tests.rs
T
dotCooCoo 4368fed0c9 xtask: the doc-test lint check reads doc attributes inside cfg_attr
`cargo xtask layers` read only `#![doc(test(attr(...)))]` written
directly, so a library root that lowered its doc tests with
`#![cfg_attr(<cond>, doc(test(attr(allow(unsafe_code)))))]` still passed
the check that its doc tests deny unsafe code.

A `doc(...)` inside `cfg_attr(...)`, at any depth, now counts. Since the
check does not evaluate the condition, such an attribute can only lower
the level: an `allow`, `warn` or `expect` of `unsafe_code` inside it
lowers it, and a `deny` or `forbid` inside it does not count, as for a
lint attribute inside `cfg_attr` within `doc(test(attr(...)))`.
2026-12-04 10:04:19 -08:00

411 lines
19 KiB
Rust

//! Every library's doc tests deny unsafe code.
//!
//! Rustdoc compiles each doc test as a crate of its own, without the workspace's `[lints]` table
//! and without the library's own `#![forbid(unsafe_code)]`, so an `unsafe` block in a doc comment
//! passes `cargo test --doc`. Rustdoc adds the attributes in `#![doc(test(attr(...)))]` to every
//! doc test, so each library root carries `#![doc(test(attr(forbid(unsafe_code))))]`, or
//! `deny` where the library itself relies on the workspace's `deny`. `cargo xtask layers` runs
//! this check.
use serde_json::Value;
use std::path::Path;
/// Crate roots larger than this are reported instead of read.
const MAX_ROOT_BYTES: u64 = 8 * 1024 * 1024;
/// The problems found in the workspace's library roots, one line each.
pub fn check(meta: &Value) -> Result<Vec<String>, String> {
let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?;
let root = Path::new(meta["workspace_root"].as_str().unwrap_or_default());
let mut out = Vec::new();
for p in pkgs {
let name = p["name"].as_str().ok_or("package without name")?;
for t in p["targets"].as_array().into_iter().flatten() {
let kinds: Vec<&str> = t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let doc_tested = t["doctest"].as_bool() == Some(true) && kinds.iter().any(|k| matches!(*k, "lib" | "rlib" | "proc-macro"));
if !doc_tested {
continue;
}
let path = t["src_path"].as_str().ok_or_else(|| format!("{name}: library target without src_path"))?;
if let Some(problem) = check_root(name, root, Path::new(path))? {
out.push(problem);
}
}
}
out.sort();
Ok(out)
}
fn check_root(name: &str, root: &Path, path: &Path) -> Result<Option<String>, String> {
let shown = path.strip_prefix(root).unwrap_or(path).display();
let len = std::fs::metadata(path).map_err(|e| format!("{shown}: {e}"))?.len();
if len > MAX_ROOT_BYTES {
return Ok(Some(format!("{name}: {shown} is larger than {MAX_ROOT_BYTES} bytes")));
}
let src = std::fs::read_to_string(path).map_err(|e| format!("{shown}: {e}"))?;
Ok(problem(&src).map(|p| format!("{name}: {shown}: {p}")))
}
/// What a library root is missing, or `None` when its doc tests deny unsafe code at least as
/// strictly as the library does.
fn problem(src: &str) -> Option<&'static str> {
let attrs = inner_attributes(src);
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))))]"),
Some(Level::Deny) => None,
_ => Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]"),
}
}
/// A lint level that rustdoc can add to every doc test.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Level {
Allow,
Deny,
Forbid,
}
/// The lint attributes that set a level, and the level each one sets for this check.
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. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and nothing lowers a
/// `forbid`. The check does not evaluate `cfg_attr` conditions. A `doc(...)` inside
/// `cfg_attr(...)` at any depth can only lower the level: `allow`, `warn` and `expect` of
/// `unsafe_code`, directly or inside a nested `cfg_attr(...)`, set it to `Allow`, and `deny`
/// and `forbid` do not count. The same rule applies to lint attributes inside `cfg_attr(...)`
/// within an unconditional `doc(...)`.
fn doc_test_level(attrs: &[String]) -> Option<Level> {
attrs.iter().fold(None, |level, a| after_doc_attr(a, level, false))
}
/// The level in force after `attr`, given the `level` before it: `attr` is a `doc(...)`, or a
/// `cfg_attr(...)` that may hold some. When `conditional` is true, only lint attributes that
/// lower the level count. Nothing lowers `forbid`.
fn after_doc_attr(attr: &str, level: Option<Level>, conditional: bool) -> Option<Level> {
if let Some(inner) = args(attr, "cfg_attr") {
return items(inner).into_iter().skip(1).fold(level, |l, a| after_doc_attr(a, l, true));
}
let mut level = level;
for test in args(attr, "doc").into_iter().flat_map(items).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 direct = LEVELS
.into_iter()
.filter(|(_, l)| !conditional || *l == Level::Allow)
.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)
{
level = Some(next);
}
}
}
}
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(')')?;
let mut depth = 0usize;
for ch in rest.chars() {
match ch {
'(' => depth += 1,
')' if depth == 0 => return None,
')' => depth -= 1,
_ => {}
}
}
(depth == 0).then_some(rest)
}
/// The comma-separated items of a list such as `deny(warnings),forbid(unsafe_code)`, split only
/// at the top level.
fn items(list: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0usize;
let mut item_start = 0;
for (k, ch) in list.char_indices().chain(std::iter::once((list.len(), ','))) {
match ch {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
if k > item_start {
out.push(&list[item_start..k]);
}
item_start = k + 1;
}
_ => {}
}
}
out
}
/// 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] == '{' {
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;
}
let start = i + 3;
let mut depth = 1usize;
let mut j = start;
while j < code.len() && depth > 0 {
match code[j] {
'[' => depth += 1,
']' => depth -= 1,
_ => {}
}
j += 1;
}
if depth > 0 {
break;
}
out.push(code[start..j - 1].iter().collect());
i = j;
}
out
}
/// `src` with line and (nested) block comments replaced by a space, and the contents of string,
/// 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());
let mut i = 0;
while i < c.len() {
let next = c.get(i + 1).copied();
let ident_before = i > 0 && (c[i - 1].is_alphanumeric() || c[i - 1] == '_');
match c[i] {
'/' if next == Some('/') => {
while i < c.len() && c[i] != '\n' {
i += 1;
}
out.push(' ');
}
'/' if next == Some('*') => {
let mut depth = 0usize;
while i < c.len() {
if c[i] == '/' && c.get(i + 1) == Some(&'*') {
depth += 1;
i += 2;
} else if c[i] == '*' && c.get(i + 1) == Some(&'/') {
depth = depth.saturating_sub(1);
i += 2;
if depth == 0 {
break;
}
} else {
i += 1;
}
}
out.push(' ');
}
'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(&'#'))) {
j += 1;
}
out.push_str("\"\"");
i = j + 1 + hashes;
}
'"' => {
let mut j = i + 1;
while j < c.len() && c[j] != '"' {
j += if c[j] == '\\' { 2 } else { 1 };
}
out.push_str("\"\"");
i = j + 1;
}
'\'' if next == Some('\\') => {
let mut j = i + 3;
while j < c.len() && c[j] != '\'' {
j += 1;
}
out.push_str("''");
i = j + 1;
}
'\'' if c.get(i + 2) == Some(&'\'') => {
out.push_str("''");
i += 3;
}
ch => {
out.push(ch);
i += 1;
}
}
}
out
}
/// 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 matches!(c.get(j), Some('b' | 'c')) {
j += 1;
}
if c.get(j) != Some(&'r') {
return None;
}
j += 1;
let hashes = c[j..].iter().take_while(|&&ch| ch == '#').count();
(c.get(j + hashes) == Some(&'"')).then_some((j + hashes, hashes))
}
/// Whether a lint list such as `unsafe_code,unused_must_use` names `unsafe_code`.
fn names_unsafe_code(list: &str) -> bool {
items(list).contains(&"unsafe_code")
}
#[cfg(test)]
mod tests {
use super::problem;
const NEEDS_DENY: Option<&str> = Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]");
const NEEDS_FORBID: Option<&str> = Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]");
#[test]
fn a_forbidding_library_needs_forbid_in_its_doc_tests() {
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
assert_eq!(problem("#![forbid(unsafe_code)]\n"), NEEDS_FORBID);
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID);
}
#[test]
fn a_library_on_the_workspace_deny_needs_deny_or_forbid() {
assert_eq!(problem("//! Docs.\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
assert_eq!(problem("#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
assert_eq!(problem("//! Docs.\npub fn f() {}\n"), NEEDS_DENY);
}
#[test]
fn comments_other_lints_and_allow_do_not_count() {
assert_eq!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_DENY);
assert_eq!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n"), NEEDS_DENY);
assert_eq!(problem("#![doc(test(attr(allow(unsafe_code))))]\n"), NEEDS_DENY);
assert_eq!(problem("#![doc(test(attr(deny(warnings))))]\n"), NEEDS_DENY);
assert_eq!(problem("#![deny(unsafe_code)]\n"), NEEDS_DENY);
assert_eq!(problem("// #![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
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);
}
#[test]
fn block_comments_and_string_literals_do_not_count() {
assert_eq!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n"), NEEDS_FORBID);
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);
}
#[test]
fn an_attribute_may_span_several_lines() {
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(\n forbid(unsafe_code)\n)))]\n"), None);
assert_eq!(problem("#![forbid(\n unsafe_code\n)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
}
#[test]
fn grouped_lint_lists_are_read_item_by_item() {
let grouped = "#![forbid(unsafe_code, unused_must_use)]\n";
assert_eq!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")), NEEDS_FORBID);
assert_eq!(problem(&format!("{grouped}#![doc(test(attr(forbid(unused_must_use, unsafe_code))))]\n")), None);
assert_eq!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
assert_eq!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n"), NEEDS_DENY);
}
#[test]
fn a_lint_inside_cfg_attr_does_not_count() {
assert_eq!(problem("#![doc(test(attr(cfg_attr(any(), deny(unsafe_code)))))]\n"), NEEDS_DENY);
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(cfg_attr(any(), forbid(unsafe_code)))))]\n"), NEEDS_FORBID);
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_doc_attribute_inside_cfg_attr_can_only_lower_the_doc_tests() {
let deny = "#![doc(test(attr(deny(unsafe_code))))]\n";
assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(allow(unsafe_code)))))]\n")), NEEDS_DENY);
assert_eq!(problem(&format!("{deny}#![cfg_attr(test, cfg_attr(all(), doc(test(attr(warn(unsafe_code))))))]\n")), NEEDS_DENY);
assert_eq!(problem("#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))))]\n"), NEEDS_DENY);
assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))))]\n")), None);
assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(allow(unsafe_code), deny(unsafe_code)))))]\n")), NEEDS_DENY);
assert_eq!(
problem(&format!(
"{deny}#![cfg_attr(all(), doc(test(attr(allow(unsafe_code)))))]\n#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))))]\n"
)),
NEEDS_DENY
);
assert_eq!(
problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(cfg_attr(test, expect(unsafe_code)), deny(unsafe_code)))))]\n")),
NEEDS_DENY
);
let both = "doc(test(attr(allow(unsafe_code)))), doc(test(attr(deny(unsafe_code))))";
assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), {both})]\n")), NEEDS_DENY);
assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))), cfg_attr(test, {both}))]\n")), NEEDS_DENY);
let allow = "doc(test(attr(allow(unsafe_code))))";
assert_eq!(problem(&format!("{deny}#![cfg_attr(all(), doc(test(attr(deny(unsafe_code)))), cfg_attr(test, {allow}))]\n")), NEEDS_DENY);
let forbid = "#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n";
assert_eq!(problem(&format!("{forbid}#![cfg_attr(all(), doc(test(attr(forbid(unsafe_code)))))]\n")), NEEDS_FORBID);
assert_eq!(problem("#![forbid(unsafe_code)]\n#![cfg_attr(all(), doc(test(attr(forbid(unsafe_code)))))]\n"), NEEDS_FORBID);
assert_eq!(problem(&format!("#![doc(test(attr(forbid(unsafe_code))))]\n#![cfg_attr(all(), {both})]\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);
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\n#![doc(test(attr(warn(unsafe_code))))]\n"), NEEDS_DENY);
assert_eq!(problem("#![doc(test(attr(allow(unsafe_code), deny(unsafe_code))))]\n"), None);
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code), allow(unsafe_code))))]\n"), None);
}
}