//! Check public types against the std-trait expectations of the Rust API Guidelines.
//! TR003 missing-debug pub struct/enum without Debug (derive or impl, any scanned file)
//! TR004 error-without-error-impl pub *Error type without Display and std::error::Error
//! TR011 hash-with-manual-eq #[derive(Hash)] with a hand-written PartialEq
//! TR012 new-without-default pub fn new() -> Self with no arguments and no Default
//! TR014 error-enum-exhaustive pub enum *Error without #[non_exhaustive]
//!
//! Build: rustc -O --edition 2021 scripts/api_traits.rs -o /tmp/api_traits
//! Usage: api_traits <FILES|DIRS|-> [--json] [--strict] [--select IDS] [--ignore IDS]
mod cli;
mod rsparse;
use cli::{Finding, Rule};
use rsparse::{attrs_before, base_name, is_pub, items, split_top, test_spans, Src};
const RULES: &[Rule] = &[
Rule { id: "TR003", name: "missing-debug", severity: "medium",
why: "C-DEBUG: every public type should implement Debug so users can log and assert on it",
fix: "#[derive(Debug)], or a manual impl that hides secrets / uses finish_non_exhaustive()" },
Rule { id: "TR004", name: "error-without-error-impl", severity: "high",
why: "C-GOOD-ERR: error types must implement Display and std::error::Error to work with ?, Box<dyn Error> and anyhow",
fix: "#[derive(thiserror::Error)] with #[error(\"..\")] per variant, or impl Display + impl std::error::Error" },
Rule { id: "TR011", name: "hash-with-manual-eq", severity: "medium",
why: "k1 == k2 must imply hash(k1) == hash(k2); a derived Hash next to a custom PartialEq usually breaks it",
fix: "implement Hash by hand over the same normalized data PartialEq compares" },
Rule { id: "TR012", name: "new-without-default", severity: "low",
why: "a no-argument constructor should also be Default (clippy::new_without_default)",
fix: "#[derive(Default)] or impl Default { fn default() -> Self { Self::new() } }" },
Rule { id: "TR014", name: "error-enum-exhaustive", severity: "low",
why: "adding a variant to an exhaustive public error enum is a breaking change",
fix: "#[non_exhaustive] on the enum (callers then need a `_ =>` arm)" },
];
const USAGE: &str = "usage: api_traits <FILES|DIRS|-> [options]
Check public structs and enums for the std traits the Rust API Guidelines expect: Debug
(TR003), Display + Error on error types (TR004), Hash consistent with PartialEq (TR011),
Default next to new() (TR012) and #[non_exhaustive] error enums (TR014). Impls anywhere in
the scanned files count, so scan the whole crate. #[cfg(test)] modules are skipped.";
fn derives(attrs: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = attrs;
while let Some(i) = rest.find("derive(") {
let inner = &rest[i + 7..];
let end = inner.find(')').unwrap_or(inner.len());
out.extend(inner[..end].split(',').map(|d| base_name(d)));
rest = &inner[end..];
}
out
}
fn main() {
let opts = cli::parse(USAGE, RULES, &[]);
let inputs = opts.inputs();
let srcs: Vec<Src> = inputs.iter().map(|i| Src::new(i.text.clone())).collect();
let parsed: Vec<_> = srcs.iter().map(items).collect();
// (trait, self type) for every impl in the crate, e.g. ("Display", "StorageError").
let impls: Vec<(String, String)> = parsed
.iter()
.flat_map(|(_, _, bs)| bs.iter().map(|b| {
let (t, s) = b.trait_and_self();
(t.map(|t| base_name(&t)).unwrap_or_default(), base_name(&s))
}))
.collect();
let has_impl = |tr: &str, ty: &str| impls.iter().any(|(t, s)| t == tr && s == ty);
let mut findings = Vec::new();
for ((input, src), (fns, types, blocks)) in inputs.iter().zip(&srcs).zip(&parsed) {
let tests = test_spans(&src.code);
let in_test = |off: usize| tests.iter().any(|&(a, b)| a < off && off < b);
let mut found = Vec::new();
let push = |found: &mut Vec<Finding>, off: usize, id: &'static str, msg: String, fix: &str| {
found.push(Finding { file: input.name.clone(), line: src.line_of(off), id, msg, fix: fix.to_string() });
};
for t in types.iter().filter(|t| !in_test(t.off)) {
let attrs = attrs_before(&src.code, t.off);
let d = derives(&attrs);
let public = is_pub(&src.code, t.off);
let derived = |x: &str| d.iter().any(|n| n == x);
if public && !derived("Debug") && !has_impl("Debug", &t.name) {
push(&mut found, t.off, "TR003", format!("pub {} {} implements neither derive(Debug) nor Debug", t.kind, t.name),
"#[derive(Debug)] (manual impl if a field must stay hidden)");
}
if public && t.name.ends_with("Error") {
let derive_err = derived("Error") || derived("Snafu"); // thiserror / snafu
let missing: Vec<&str> = [("Display", "Display"), ("Error", "std::error::Error")]
.iter()
.filter(|(tr, _)| !derive_err && !has_impl(tr, &t.name))
.map(|(_, shown)| *shown)
.collect();
if !missing.is_empty() {
push(&mut found, t.off, "TR004", format!("pub {} {} is missing {}", t.kind, t.name, missing.join(" and ")),
"#[derive(thiserror::Error, Debug)] with #[error(\"..\")] messages, or impl Display + std::error::Error");
}
if t.kind == "enum" && !attrs.contains("non_exhaustive") {
push(&mut found, t.off, "TR014", format!("pub enum {} is exhaustive: adding a variant breaks callers", t.name),
"#[non_exhaustive] above the enum");
}
}
if derived("Hash") && has_impl("PartialEq", &t.name) {
push(&mut found, t.off, "TR011", format!("{} derives Hash but implements PartialEq by hand", t.name),
"impl Hash manually over the same (normalized) fields PartialEq compares");
}
}
for f in fns.iter().filter(|f| f.name == "new" && f.params.trim().is_empty() && !in_test(f.off)) {
let Some(b) = f.impl_idx.map(|i| &blocks[i]) else { continue };
let (tr, self_ty) = b.trait_and_self();
let ty = base_name(&self_ty);
let derives_default = types.iter().any(|t| t.name == ty && derives(&attrs_before(&src.code, t.off)).iter().any(|d| d == "Default"));
let returns_self = matches!(f.ret.trim(), "Self") || base_name(&f.ret) == ty;
if tr.is_none() && is_pub(&src.code, f.off) && returns_self && !derives_default && !has_impl("Default", &ty)
&& split_top(&b.generics).is_empty() {
push(&mut found, f.off, "TR012", format!("{ty}::new() takes no arguments but {ty} has no Default"),
"#[derive(Default)] if field defaults match, else impl Default calling Self::new()");
}
}
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, f.id)));
}
cli::finish(&opts, RULES, findings, inputs.len(), "API trait")
}
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-unsafe-block-auditor
Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.