Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

safety_comments.rs

Helper script for rust-unsafe-block-auditor · 129 lines

Programming / Rustv1.0.0Updated OCT 21 20266 references8 scripts
scripts/safety_comments.rs
//! Check that every unsafe item carries its justification, and that the crate turns on the
//! lints that keep it that way.
//!   US001 missing-safety-comment  unsafe block / unsafe impl without `// SAFETY:`
//!   US002 missing-safety-doc      unsafe fn / unsafe trait without a `# Safety` doc section
//!   US018 large-unsafe-block      block longer than --max-block-lines (default 15)
//!   US026 forbid-unsafe-code      crate root with no unsafe and no #![forbid(unsafe_code)]
//!   US027 unsafe-op-lint          unsafe fns but no unsafe_op_in_unsafe_fn lint (default in 2024)
//!   US028 safety-comment-lint     unsafe blocks but no clippy::undocumented_unsafe_blocks
//!
//! Build: rustc -O --edition 2021 scripts/safety_comments.rs -o /tmp/safety_comments
//! Usage: safety_comments <FILES|DIRS|-> [--max-block-lines N] [--json] [--strict]

mod cli;
mod rsparse;
mod unsafe_items;

use cli::{Finding, Rule};
use rsparse::{items, Src};
use unsafe_items::unsafe_items;

const RULES: &[Rule] = &[
    Rule { id: "US001", name: "missing-safety-comment", severity: "medium",
           why: "every unsafe block/impl must say which invariants make it sound (clippy::undocumented_unsafe_blocks)",
           fix: "// SAFETY: <why each precondition of every unsafe operation holds here>" },
    Rule { id: "US002", name: "missing-safety-doc", severity: "medium",
           why: "an unsafe fn/trait must document the contract callers or implementors uphold (clippy::missing_safety_doc)",
           fix: "/// # Safety\\n/// <every precondition: validity, alignment, aliasing, lifetimes, thread rules>" },
    Rule { id: "US018", name: "large-unsafe-block", severity: "low",
           why: "a long unsafe block hides which operation needs which invariant and unsafe-checks safe code too",
           fix: "shrink the block to the unsafe operations; one block (and one SAFETY comment) per operation" },
    Rule { id: "US026", name: "forbid-unsafe-code", severity: "info",
           why: "a crate without unsafe can promise it stays that way",
           fix: "#![forbid(unsafe_code)] at the crate root, or [lints.rust] unsafe_code = \"forbid\"" },
    Rule { id: "US027", name: "unsafe-op-lint", severity: "info",
           why: "without it, an unsafe fn body is one big implicit unsafe block (edition 2024 warns by default)",
           fix: "#![deny(unsafe_op_in_unsafe_fn)] (or [lints.rust]) and explicit unsafe blocks inside unsafe fns" },
    Rule { id: "US028", name: "safety-comment-lint", severity: "info",
           why: "the lint keeps new unsafe blocks documented",
           fix: "#![warn(clippy::undocumented_unsafe_blocks, clippy::missing_safety_doc)] or [lints.clippy]" },
];

const USAGE: &str = "usage: safety_comments <FILES|DIRS|-> [--max-block-lines N] [options]

Report unsafe blocks and impls without a `// SAFETY:` comment (US001), unsafe fns and
traits without a `# Safety` doc section (US002), oversized unsafe blocks (US018) and
missing crate-level safety lints (US026-US028, read from the crate root file and the
[lints] tables of ancestor Cargo.toml files).

  --max-block-lines N  US018 threshold (default 15)";

/// Text of every Cargo.toml above `file`, for [lints] lookups.
fn cargo_lints(file: &str) -> String {
    let mut out = String::new();
    let mut dir = std::path::Path::new(file).canonicalize().ok().and_then(|p| p.parent().map(|d| d.to_path_buf()));
    while let Some(d) = dir {
        if let Ok(t) = std::fs::read_to_string(d.join("Cargo.toml")) {
            out.push_str(&t);
        }
        dir = d.parent().map(|p| p.to_path_buf());
    }
    out
}

fn main() {
    let opts = cli::parse(USAGE, RULES, &["--max-block-lines"]);
    let max: usize = opts.value("--max-block-lines").map_or(15, |v| v.parse().unwrap_or_else(|_| cli::die("--max-block-lines needs a number")));
    let inputs = opts.inputs();
    let mut findings = Vec::new();
    for input in &inputs {
        let src = Src::new(input.text.clone());
        let (fns, _, _) = items(&src);
        let list = unsafe_items(&src, &fns);
        let traits = rsparse::traits(&src);
        let mut found = Vec::new();
        let mut push = |off: usize, id: &'static str, msg: String| {
            found.push(Finding { file: input.name.clone(), line: src.line_of(off), id, msg, fix: String::new() });
        };
        for it in &list {
            match it.kind {
                "block" | "impl" if !it.documented => {
                    let what = if it.kind == "block" { format!("unsafe block in fn {}", it.name) } else { format!("`unsafe {}`", it.name) };
                    push(it.off, "US001", format!("{what} has no // SAFETY: comment"));
                }
                "fn" | "trait" if !it.documented => {
                    // Methods of a pub trait are public even without `pub`.
                    let in_pub_trait = traits.iter().any(|t| t.span.0 < it.off && it.off < t.span.1 && rsparse::is_pub(&src.code, t.off));
                    let public = in_pub_trait || src.code[..it.off].trim_end().ends_with("pub") || src.code[..it.off].trim_end().ends_with(')');
                    let what = if it.kind == "fn" { format!("unsafe fn {}", it.name) } else { format!("`unsafe {}`", it.name) };
                    push(it.off, "US002", format!("{what}{} has no # Safety section in its docs", if public { "" } else { " (private)" }));
                }
                _ => {}
            }
            if it.kind == "block" {
                let lines = src.line_of(it.end) - src.line_of(it.off) + 1;
                if lines > max {
                    push(it.off, "US018", format!("unsafe block in fn {} spans {lines} lines (max {max})", it.name));
                }
            }
        }
        // Crate-level lint checks: only on files that look like a crate root.
        let base = std::path::Path::new(&input.name).file_name().and_then(|n| n.to_str()).unwrap_or("");
        let root = base == "lib.rs" || base == "main.rs" || src.code.contains("#![") || input.name == "<stdin>";
        if root {
            let lints = format!("{}\n{}", src.code, if input.name == "<stdin>" { String::new() } else { cargo_lints(&input.name) });
            let has = |name: &str| lints.contains(name);
            if list.is_empty() && !has("unsafe_code") {
                push(0, "US026", "crate root has no unsafe code but does not forbid it".into());
            }
            if list.iter().any(|i| i.kind == "fn") && !has("unsafe_op_in_unsafe_fn") && input.edition < 2024 {
                push(0, "US027", "crate has unsafe fns but no unsafe_op_in_unsafe_fn lint".into());
            }
            if list.iter().any(|i| i.kind == "block") && !has("undocumented_unsafe_blocks") {
                push(0, "US028", "crate has unsafe blocks but does not enable clippy::undocumented_unsafe_blocks".into());
            }
        }
        let on = |id: &str| RULES.iter().any(|r| r.id == id && opts.enabled(r));
        findings.extend(found.into_iter().filter(|f| on(f.id) && !src.noqa(f.line.max(1), f.id)));
    }
    let findings: Vec<Finding> = findings
        .into_iter()
        .map(|mut f| {
            f.line = f.line.max(1);
            f.fix = RULES.iter().find(|r| r.id == f.id).map_or(String::new(), |r| r.fix.replace("\\n", " ").to_string());
            f
        })
        .collect();
    cli::finish(&opts, RULES, findings, inputs.len(), "safety-documentation")
}
More in Rust

rust-borrow-checker-error-explainer

Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.

rust-cargo-workspace-designer

Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.

rust-error-handling-thiserror-anyhow-designer

Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.

rust-lifetime-annotation-advisor

Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.

rust-tokio-async-service-builder

Build and review production async Rust services on Tokio 1.x and axum 0.8: runtime choice (#[tokio::main] multi_thread vs current_thread, Builder), axum routing with /{id} paths, State, extractors, IntoResponse error types, axum::serve with_graceful_shutdown, tower/tower-http middleware (TraceLayer, TimeoutLayer, CorsLayer, ConcurrencyLimitLayer, RequestBodyLimitLayer), Arc<AppState>, std vs tokio Mutex, JoinSet, TaskTracker, CancellationToken, select! cancel safety, bounded mpsc, oneshot, broadcast, watch, actors, Semaphore, timeouts, retries, spawn_blocking, sqlx PgPool, reqwest Client reuse, tracing, tests with start_paused and oneshot, Dockerfile. Fixes 'future cannot be sent between threads safely', E0373, Rc or MutexGuard held across await, 'Cannot start a runtime from within a runtime', 'Path segments must not start with :'. Ships std-only Rust scanners and a compiling axum 0.8 scaffold.

rust-trait-design-reviewer

Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.