//! Inventory every `unsafe` item, like a small cargo-geiger: kind, location, size, whether it
//! carries its justification (SAFETY comment / `# Safety` doc) and the risky operations inside.
//! Start every unsafe review here; the other scripts explain individual findings.
//!
//! Build: rustc -O --edition 2021 scripts/unsafe_inventory.rs -o /tmp/unsafe_inventory
//! Usage: unsafe_inventory <FILES|DIRS|-> [--json] [--strict]
//! Exit: 0 listed, 1 with --strict when an item lacks its justification, 2 usage error.
mod cli;
mod rsparse;
mod unsafe_items;
use rsparse::{items, Src};
use unsafe_items::{unsafe_items, UnsafeItem};
const USAGE: &str = "usage: unsafe_inventory <FILES|DIRS|-> [--json] [--strict]
List every unsafe block, unsafe fn, unsafe impl, unsafe trait and unsafe extern block with
its location, size in lines, justification status and the risky operations it contains,
then totals per file. Status: documented (SAFETY comment or # Safety doc), undocumented,
or undocumented+risky (no justification and it transmutes, zeroes, sets lengths, builds
owners from raw parts or assumes initialisation).";
/// (pattern in code, label, high risk?)
const OPS: &[(&str, &str, bool)] = &[
("transmute", "transmute", true),
("uninitialized(", "mem::uninitialized", true),
("zeroed", "mem::zeroed", true),
(".assume_init()", "assume_init", true),
("set_len(", "set_len", true),
("from_raw_parts", "from_raw_parts", true),
("from_raw(", "from_raw", true),
("_unchecked", "unchecked call", false),
("read_volatile", "volatile read", false),
("write_volatile", "volatile write", false),
(".read()", "ptr read", false),
(".write(", "ptr write", false),
(".add(", "ptr add", false),
(".offset(", "ptr offset", false),
("from_ptr(", "CStr::from_ptr", false),
("asm!", "inline asm", false),
("&mut *", "&mut from raw", false),
];
fn ops(item: &UnsafeItem) -> (Vec<&'static str>, bool) {
let mut found = Vec::new();
let mut risky = false;
for (pat, label, high) in OPS {
if item.body.contains(pat) && !found.contains(label) {
found.push(*label);
risky |= *high;
}
}
(found, risky)
}
fn status(item: &UnsafeItem, risky: bool) -> &'static str {
match (item.documented, risky) {
(true, _) => "documented",
(false, true) => "undocumented+risky",
(false, false) => "undocumented",
}
}
fn json_str(s: &str) -> String {
format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
}
fn main() {
let opts = cli::parse(USAGE, &[], &[]);
let inputs = opts.inputs();
let mut undocumented = 0;
let mut totals = [0usize; 5]; // block, fn, impl, trait, extern
let kinds = ["block", "fn", "impl", "trait", "extern"];
let mut json_files = Vec::new();
for input in &inputs {
let src = Src::new(input.text.clone());
let (fns, _, _) = items(&src);
let list = unsafe_items(&src, &fns);
let mut counts = [0usize; 5];
let mut rows = Vec::new();
for it in &list {
let k = kinds.iter().position(|k| *k == it.kind).unwrap_or(0);
counts[k] += 1;
let (found, risky) = ops(it);
let st = status(it, risky);
undocumented += usize::from(!it.documented);
let lines = src.line_of(it.end) - src.line_of(it.off) + 1;
rows.push((src.line_of(it.off), it.kind, it.name.clone(), lines, st, found));
}
for (t, c) in totals.iter_mut().zip(counts) {
*t += c;
}
if opts.json {
let items: Vec<String> = rows
.iter()
.map(|(l, k, n, lines, st, ops)| {
let ops: Vec<String> = ops.iter().map(|o| json_str(o)).collect();
format!("{{\"line\":{l},\"kind\":{},\"name\":{},\"lines\":{lines},\"status\":{},\"ops\":[{}]}}",
json_str(k), json_str(n), json_str(st), ops.join(","))
})
.collect();
let c: Vec<String> = kinds.iter().zip(counts).map(|(k, n)| format!("\"{k}\":{n}")).collect();
json_files.push(format!("{{\"file\":{},\"counts\":{{{}}},\"items\":[{}]}}", json_str(&input.name), c.join(","), items.join(",")));
continue;
}
let summary: Vec<String> = kinds.iter().zip(counts).filter(|(_, n)| *n > 0).map(|(k, n)| format!("{n} {k}")).collect();
println!("{} ({})", input.name, if summary.is_empty() { "no unsafe".to_string() } else { summary.join(", ") });
for (l, k, n, lines, st, ops) in &rows {
println!(" L{l:<5} {k:<6} {:<28} {lines:>3} line(s) {st:<19} {}", truncate(n, 28), ops.join(", "));
}
}
if opts.json {
let t: Vec<String> = kinds.iter().zip(totals).map(|(k, n)| format!("\"{k}\":{n}")).collect();
println!("{{\"files\":[{}],\"totals\":{{{}}},\"undocumented\":{undocumented}}}", json_files.join(","), t.join(","));
} else {
let total: usize = totals.iter().sum();
println!("\n{total} unsafe item(s) in {} file(s): {} undocumented.", inputs.len(), undocumented);
}
std::process::exit(if opts.strict && undocumented > 0 { 1 } else { 0 });
}
fn truncate(s: &str, n: usize) -> String {
if s.chars().count() <= n { s.to_string() } else { format!("{}...", s.chars().take(n - 3).collect::<String>()) }
}
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.