From 9c11c47f75cf870de92b7f8883fc8f89aab43793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:51:28 -0800 Subject: [PATCH 1/6] Doc tests: unsafe code is denied in doc tests too Rustdoc builds each doc test as its own crate, without the workspace's `unsafe_code = "deny"` and without a library's `#![forbid(unsafe_code)]`, so a doc test holding an `unsafe` block passed `cargo test --doc`. - Every library root now carries `#![doc(test(attr(forbid(unsafe_code))))]`, or `deny` in cad, eps and metafile, which rely on the workspace lint. - `cargo xtask layers` reports a library whose doc tests are missing the attribute, or use `deny` where the library forbids unsafe code. - AGENTS.md names the rule next to the `unsafe` allowlist. --- AGENTS.md | 2 +- crates/affinity/src/lib.rs | 1 + crates/apischema/src/lib.rs | 1 + crates/brush/src/lib.rs | 1 + crates/cad/src/lib.rs | 1 + crates/color/src/lib.rs | 1 + crates/doc/src/lib.rs | 1 + crates/effects/src/lib.rs | 1 + crates/engine/src/lib.rs | 1 + crates/eps/src/lib.rs | 1 + crates/format/src/lib.rs | 1 + crates/geom/src/lib.rs | 1 + crates/js/src/lib.rs | 1 + crates/mcp/src/lib.rs | 1 + crates/metafile/src/lib.rs | 1 + crates/pathops/src/lib.rs | 1 + crates/pdf/src/lib.rs | 1 + crates/plugins/src/lib.rs | 1 + crates/render/src/lib.rs | 1 + crates/scriptcheck/src/lib.rs | 1 + crates/svg/src/lib.rs | 1 + crates/testkit/src/lib.rs | 1 + crates/text/src/lib.rs | 1 + crates/three-d/src/lib.rs | 1 + crates/tools/src/lib.rs | 1 + crates/trace/src/lib.rs | 1 + crates/ui-egui/src/lib.rs | 1 + xtask/src/doc_tests.rs | 98 +++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 11 ++-- 29 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 xtask/src/doc_tests.rs diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..5f2d41d538 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -21,6 +21,7 @@ //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; #[cfg(test)] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8f077dae..8fe1cef218 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..c2be1804db 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 16e1e7f5a5..d5c30cd89b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and //! reduce to commands, so every gesture is journaled and replayable. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod cmd; pub mod file_access; diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index d8b9a96295..6813b300aa 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -34,6 +34,7 @@ //! - `ai_graph`: the records of a live graph those two write around its group. //! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. +#![doc(test(attr(deny(unsafe_code))))] mod ai_editing; mod ai_graph; diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9975527f78..c7157df94d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,6 +37,7 @@ //! already; [`save_with`] writes a version 1 document with them negated back for an older file //! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #[cfg(not(target_arch = "wasm32"))] mod atomic; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3f11c71062..8a4cb4f7fb 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -6,6 +6,7 @@ //! //! Coordinates are document points (1/72 in), y pointing down. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod anchors; pub mod arc; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a720940b06..77b3e00856 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -131,6 +131,7 @@ //! `await` (ECMA-262 2017 section 25.5, ). //! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ast; mod builtins; diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index efc9d44830..7e104e85f2 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -13,6 +13,7 @@ //! //! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod backend; mod headless; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index df23cbb073..66f3c4327b 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -26,6 +26,7 @@ //! formats. //! //! The app walks its document and maps its drawing operations to the shared writers. +#![doc(test(attr(deny(unsafe_code))))] #[cfg(test)] mod bytes; diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index da7960af0f..0190233191 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -5,6 +5,7 @@ //! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few //! anchors. See the crate README for the API overview. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod boolean; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 2dc6f1ec0a..a7118fd37a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -42,6 +42,7 @@ //! security handler, the algorithm following the compatibility ([`Encryption`]); either password //! opens an encrypted file. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod editing; mod encrypt; diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index c9c0e89521..4f79939c62 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -42,6 +42,7 @@ //! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each //! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod deferred; pub mod dialog; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4358cc180d..f2b76c525d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,6 +5,7 @@ //! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups, //! gradients, images and text (via `vectorcraft-text` glyph outlines). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod brush_fx; diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 9075c53517..f0c8528919 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -22,6 +22,7 @@ //! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the //! input's size, and no input can overflow the stack. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod analyze; mod catalog; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 222b90b25c..109b3a938a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -100,6 +100,7 @@ //! letter and word spacing become character attributes (line breaks, kerning, baseline shift, //! rotation and style names). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use craft_svg::tree::usvg; mod css; diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index fa7b39aa9d..fd86ad3c89 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -22,6 +22,7 @@ // apply here. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ai; pub mod ase; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 25e44392d6..4723f1ffcd 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -9,6 +9,7 @@ //! //! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod bitmap; mod colr; diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f561c0b7c6..37768ea651 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -7,6 +7,7 @@ //! //! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod fold; mod solid; diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..5adcecd679 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -6,6 +6,7 @@ //! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable //! by the control channel and MCP, and keeps tools testable without a UI. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; pub mod bbox; diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 7bb59c79b1..02acf76de0 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -46,6 +46,7 @@ //! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color //! left out stays a hole. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod centerline; mod contour; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a51817a7f1..948f1ad279 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4,6 +4,7 @@ //! (view/window) here and everything else to the engine. The same entry point serves menus, //! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] /// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update /// prompt shows both, and an AppImage's menu entry gets the icon. diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs new file mode 100644 index 0000000000..9ba395136c --- /dev/null +++ b/xtask/src/doc_tests.rs @@ -0,0 +1,98 @@ +//! 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, 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, 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: Vec = + src.lines().map(|l| l.chars().filter(|c| !c.is_whitespace()).collect::()).filter(|l| l.starts_with("#![")).collect(); + let forbids = attrs.iter().any(|a| a == "#![forbid(unsafe_code)]"); + let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("#![doc(test(") && a.contains(&format!("{level}(unsafe_code)"))); + if doc_test("forbid") { + None + } else if forbids { + Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]") + } else if doc_test("deny") { + None + } else { + Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]") + } +} + +#[cfg(test)] +mod tests { + use super::problem; + + #[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!(problem("#![forbid(unsafe_code)]\n").is_some_and(|p| p.contains("forbid(unsafe_code))))"))); + assert!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_some_and(|p| p.contains("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!(problem("//! Docs.\npub fn f() {}\n").is_some_and(|p| p.contains("deny(unsafe_code))))"))); + } + + #[test] + fn comments_other_lints_and_allow_do_not_count() { + assert!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n").is_some()); + assert!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n").is_some()); + assert!(problem("#![doc(test(attr(allow(unsafe_code))))]\n").is_some()); + assert!(problem("#![doc(test(attr(deny(warnings))))]\n").is_some()); + assert!(problem("#![deny(unsafe_code)]\n").is_some()); + } + + #[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); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2152369254..a09949f548 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -9,6 +9,7 @@ mod brands; mod bundle; mod cache_units; mod cursors; +mod doc_tests; mod grant_sites; mod ico; mod layers; @@ -200,7 +201,8 @@ pub fn metadata() -> Result { } fn cmd_layers() -> Result<(), String> { - let crates = layers::from_metadata(&metadata()?)?; + let meta = metadata()?; + let crates = layers::from_metadata(&meta)?; println!("Dependency layering (plan/architecture.md §3)\n"); println!("{:<28} {:<14} workspace deps", "crate", "layer"); for c in &crates { @@ -219,17 +221,18 @@ fn cmd_layers() -> Result<(), String> { .collect(); println!("{:<28} {:<14} {}", c.name, layers::describe(layers::classify(&c.name)), ws.join(", ")); } - let violations = layers::check(&crates); + let mut violations: Vec = layers::check(&crates).iter().map(ToString::to_string).collect(); + violations.extend(doc_tests::check(&meta)?); println!(); if violations.is_empty() { - println!("OK: {} crates, no layering violations.", crates.len()); + println!("OK: {} crates, no layering violations, and every library's doc tests deny unsafe code.", crates.len()); Ok(()) } else { println!("{} violation(s):", violations.len()); for v in &violations { println!(" - {v}"); } - Err(format!("{} layering violation(s)", violations.len())) + Err(format!("{} violation(s)", violations.len())) } } From e6ca6ed1a9355ce800d3a62abb9197134b557d87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:20:43 -0800 Subject: [PATCH 2/6] Doc tests: read whole attributes and skip comments in the unsafe-code check The check read crate-root attributes one physical line at a time and compared whole attribute strings. It accepted a doc-test attribute that sat inside a block comment or a string literal, rejected a valid attribute split over several lines, and did not see `unsafe_code` in a grouped list such as `#![forbid(unsafe_code, unused_must_use)]`, so it accepted `deny` in the doc tests of such a library. The check now removes comments and literal contents, reads each `#![...]` attribute up to its matching bracket, and reads lint lists item by item, in the library's own attribute and in the doc-test one. --- xtask/src/doc_tests.rs | 196 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 192 insertions(+), 4 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 9ba395136c..ef434ab8bd 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -49,10 +49,9 @@ fn check_root(name: &str, root: &Path, path: &Path) -> Result, St /// 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: Vec = - src.lines().map(|l| l.chars().filter(|c| !c.is_whitespace()).collect::()).filter(|l| l.starts_with("#![")).collect(); - let forbids = attrs.iter().any(|a| a == "#![forbid(unsafe_code)]"); - let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("#![doc(test(") && a.contains(&format!("{level}(unsafe_code)"))); + let attrs = inner_attributes(src); + let forbids = attrs.iter().any(|a| a.strip_prefix("forbid(").and_then(|rest| rest.strip_suffix(')')).is_some_and(names_unsafe_code)); + let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("doc(test(") && calls(a, level).into_iter().any(names_unsafe_code)); if doc_test("forbid") { None } else if forbids { @@ -64,6 +63,171 @@ 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. +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 i = 0; + while i + 2 < code.len() { + if 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 and character literals removed. +fn code_only(src: &str) -> String { + let c: Vec = 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' 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"`...), 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') { + 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)) +} + +/// The argument lists of every `name(...)` in `attr` that starts a list item. +fn calls<'a>(attr: &'a str, name: &str) -> Vec<&'a str> { + let mut out = Vec::new(); + let pat = format!("{name}("); + for (at, _) in attr.match_indices(&pat) { + if at > 0 && !matches!(attr.as_bytes()[at - 1], b'(' | b',') { + continue; + } + let start = at + pat.len(); + let mut depth = 1usize; + for (k, ch) in attr[start..].char_indices() { + match ch { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + out.push(&attr[start..start + k]); + break; + } + } + _ => {} + } + } + } + out +} + +/// Whether a lint list such as `unsafe_code,unused_must_use` names `unsafe_code`. +fn names_unsafe_code(list: &str) -> bool { + 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 &list[item_start..k] == "unsafe_code" { + return true; + } + item_start = k + 1; + } + _ => {} + } + } + false +} + #[cfg(test)] mod tests { use super::problem; @@ -95,4 +259,28 @@ mod tests { 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!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n").is_some()); + assert!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n").is_some()); + assert!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n").is_some()); + assert!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n").is_some()); + 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!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")).is_some_and(|p| p.contains("forbid"))); + assert_eq!(problem(&format!("{grouped}#![doc(test(attr(forbid(unused_must_use, unsafe_code))))]\n")), None); + assert!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_none()); + assert!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n").is_some()); + } } From a520deb991e51508386dfa8176f2b2f8089f8add Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:55:35 -0800 Subject: [PATCH 3/6] Doc tests: assert the exact report in the unsafe-code check's tests CI's test-lint step failed with only-weak at xtask/src/doc_tests.rs:250: every assertion in comments_other_lints_and_allow_do_not_count checked only that problem() returned Some. Such a test still passes when the check reports the wrong problem, for example when a commented-out #![forbid(unsafe_code)] is counted and the forbid message is returned instead of the deny message. The tests now compare problem() with the exact message for each case, and two cases cover a commented-out forbid on either side. The other tests in the file that checked only is_some, is_none or a substring compare the full result too. --- xtask/src/doc_tests.rs | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index ef434ab8bd..1ed8871ceb 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -232,27 +232,32 @@ fn names_unsafe_code(list: &str) -> bool { 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!(problem("#![forbid(unsafe_code)]\n").is_some_and(|p| p.contains("forbid(unsafe_code))))"))); - assert!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_some_and(|p| p.contains("forbid"))); + 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!(problem("//! Docs.\npub fn f() {}\n").is_some_and(|p| p.contains("deny(unsafe_code))))"))); + assert_eq!(problem("//! Docs.\npub fn f() {}\n"), NEEDS_DENY); } #[test] fn comments_other_lints_and_allow_do_not_count() { - assert!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n").is_some()); - assert!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n").is_some()); - assert!(problem("#![doc(test(attr(allow(unsafe_code))))]\n").is_some()); - assert!(problem("#![doc(test(attr(deny(warnings))))]\n").is_some()); - assert!(problem("#![deny(unsafe_code)]\n").is_some()); + 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] @@ -262,10 +267,10 @@ mod tests { #[test] fn block_comments_and_string_literals_do_not_count() { - assert!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n").is_some()); - assert!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n").is_some()); - assert!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n").is_some()); - assert!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n").is_some()); + 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("const Q: char = '\\'';\nconst S: &str = \"/*\";\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); } @@ -278,9 +283,9 @@ mod tests { #[test] fn grouped_lint_lists_are_read_item_by_item() { let grouped = "#![forbid(unsafe_code, unused_must_use)]\n"; - assert!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")).is_some_and(|p| p.contains("forbid"))); + 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!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_none()); - assert!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n").is_some()); + 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); } } From 8387f54b97d17d2c4f0616652d41fa09b82f5cdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:05:15 -0800 Subject: [PATCH 4/6] 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); From fb0bce30e64beab00184782924015b8fe2638555 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 20:06:43 -0800 Subject: [PATCH 5/6] Doc tests: read the unsafe-code level that the doc-test attributes leave in force The check accepted a library root when deny(unsafe_code) or forbid(unsafe_code) appeared anywhere inside #![doc(test(...))]. Two roots passed although their doc tests still allow unsafe code: - #![doc(test(attr(cfg_attr(any(), forbid(unsafe_code)))))]: the lint sits inside a cfg_attr whose condition is false, so rustdoc adds no lint to the doc tests. - #![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]: rustdoc adds both attributes in order, and the later allow overrides the deny. The check now reads only the lint attributes that are direct members of attr(...), in order, and keeps the last level for unsafe_code. A later allow, warn or expect lowers deny, and nothing lowers forbid. Tests cover each case. --- xtask/src/doc_tests.rs | 147 ++++++++++++++++++++++++++--------------- 1 file changed, 94 insertions(+), 53 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 2cc73d2ce9..6fb57db610 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -50,19 +50,87 @@ fn check_root(name: &str, root: &Path, path: &Path) -> Result, St /// strictly as the library does. fn problem(src: &str) -> Option<&'static str> { let attrs = inner_attributes(src); - let forbids = attrs.iter().any(|a| a.strip_prefix("forbid(").and_then(|rest| rest.strip_suffix(')')).is_some_and(names_unsafe_code)); - let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("doc(test(") && calls(a, level).into_iter().any(names_unsafe_code)); - if doc_test("forbid") { - None - } else if forbids { - Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]") - } else if doc_test("deny") { - None - } else { - Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]") + let forbids = attrs.iter().any(|a| args(a, "forbid").is_some_and(names_unsafe_code)); + 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. 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`. +fn doc_test_level(attrs: &[String]) -> Option { + 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)); + if let Some(next) = next + && level != Some(Level::Forbid) + { + level = Some(next); + } + } + } + } + } + level +} + +/// 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. @@ -188,51 +256,9 @@ fn raw_string_hashes(c: &[char], i: usize) -> Option<(usize, usize)> { (c.get(j + hashes) == Some(&'"')).then_some((j + hashes, hashes)) } -/// The argument lists of every `name(...)` in `attr` that starts a list item. -fn calls<'a>(attr: &'a str, name: &str) -> Vec<&'a str> { - let mut out = Vec::new(); - let pat = format!("{name}("); - for (at, _) in attr.match_indices(&pat) { - if at > 0 && !matches!(attr.as_bytes()[at - 1], b'(' | b',') { - continue; - } - let start = at + pat.len(); - let mut depth = 1usize; - for (k, ch) in attr[start..].char_indices() { - match ch { - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - out.push(&attr[start..start + k]); - break; - } - } - _ => {} - } - } - } - out -} - /// Whether a lint list such as `unsafe_code,unused_must_use` names `unsafe_code`. fn names_unsafe_code(list: &str) -> bool { - 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 &list[item_start..k] == "unsafe_code" { - return true; - } - item_start = k + 1; - } - _ => {} - } - } - false + items(list).contains(&"unsafe_code") } #[cfg(test)] @@ -303,4 +329,19 @@ mod tests { 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 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); + } } From 4e2581f63d8201932391bf39edb0d99fba7e5026 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 21:17:30 -0800 Subject: [PATCH 6/6] 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. --- xtask/src/doc_tests.rs | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 6fb57db610..ece5ccfe45 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -50,7 +50,7 @@ fn check_root(name: &str, root: &Path, path: &Path) -> Result, 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 { 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 } +/// 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 { } /// `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 = 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);