//! Find function signatures that make APIs harder to use than they need to be.
//! TR009 box-dyn-error-not-send Result<T, Box<dyn Error>> (not Send + Sync), except in fn main
//! TR010 borrowed-owned-param &Vec<T>, &String, &Box<T>, &PathBuf, &OsString parameters
//! TR013 builder-missing-must-use pub fn x(self, ..) -> Self without #[must_use] on it or its type
//!
//! Build: rustc -O --edition 2021 scripts/api_signatures.rs -o /tmp/api_signatures
//! Usage: api_signatures <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, one_line, split_top, test_spans, word_positions, Src};
const RULES: &[Rule] = &[
Rule { id: "TR009", name: "box-dyn-error-not-send", severity: "medium",
why: "Box<dyn Error> without Send + Sync cannot cross threads or tokio::spawn, and anyhow cannot wrap it cheaply",
fix: "Box<dyn std::error::Error + Send + Sync + 'static> (a `BoxError` alias), or a concrete error type" },
Rule { id: "TR010", name: "borrowed-owned-param", severity: "low",
why: "&Vec<T>/&String/&Box<T>/&PathBuf/&OsString force callers to own that exact container (clippy::ptr_arg)",
fix: "&[T], &str, &T, &Path, &OsStr: strictly more callers, same body" },
Rule { id: "TR013", name: "builder-missing-must-use", severity: "low",
why: "a by-value builder method whose result is dropped silently does nothing",
fix: "#[must_use] on the builder type (covers every method) or on each method" },
];
const USAGE: &str = "usage: api_signatures <FILES|DIRS|-> [options]
Report Box<dyn Error> without Send + Sync (TR009, fn main is exempt), parameters that
borrow an owned container instead of its slice/view type (TR010, trait impls exempt since
the trait fixes the signature) and by-value builder methods without #[must_use] (TR013).
#[cfg(test)] modules are skipped.";
const OWNED: &[(&str, &str)] = &[("Vec", "&[T]"), ("String", "&str"), ("Box", "&T"), ("PathBuf", "&Path"), ("OsString", "&OsStr")];
/// Every `Box<dyn ...Error>` in `s` that lacks `Send` (borrowed `&dyn Error`, as in
/// `Error::source`, is fine and required by std).
fn non_send_dyn_errors(s: &str) -> Vec<String> {
word_positions(s, "dyn")
.into_iter()
.filter(|&i| s[..i].trim_end().ends_with("Box<"))
.filter_map(|i| {
let rest = &s[i..];
let end = rest.find(['>', ')', ',', ';', '{', '=']).unwrap_or(rest.len());
let obj = one_line(&rest[..end]);
let is_error = base_name(obj.trim_start_matches("dyn ").split('+').next().unwrap_or("")) == "Error";
(is_error && !obj.contains("Send")).then_some(obj)
})
.collect()
}
fn main() {
let opts = cli::parse(USAGE, RULES, &[]);
let inputs = opts.inputs();
let mut findings = Vec::new();
for input in &inputs {
let src = Src::new(input.text.clone());
let (fns, types, impls) = items(&src);
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();
for f in fns.iter().filter(|f| !in_test(f.off)) {
let line = src.line_of(f.off);
let block = f.impl_idx.map(|i| &impls[i]);
let trait_impl = block.is_some_and(|b| b.trait_and_self().0.is_some());
if f.name != "main" && !trait_impl {
for obj in non_send_dyn_errors(&format!("{} {}", f.params, f.ret)) {
found.push(Finding { file: input.name.clone(), line, id: "TR009",
msg: format!("fn {} uses `{obj}` without Send + Sync", f.name),
fix: format!("{} + Send + Sync + 'static", obj.trim_end_matches(" + 'static")) });
}
}
if !trait_impl {
for p in split_top(&f.params) {
let Some((name, ty)) = p.split_once(':') else { continue };
let ty = ty.trim();
let Some(inner) = ty.strip_prefix('&').map(str::trim_start) else { continue };
if inner.starts_with("mut ") || inner.starts_with('\'') {
continue; // &mut Vec<T> can grow the Vec; explicit lifetimes are deliberate
}
if let Some((owned, better)) = OWNED.iter().find(|(o, _)| base_name(inner) == *o && !inner.contains("dyn ")) {
// Name the concrete view type: &Vec<String> -> &[String], &Box<Node> -> &Node.
let arg = inner.split_once('<').map(|(_, r)| r.trim_end().trim_end_matches('>').trim());
let better = match (*owned, arg) {
("Vec", Some(a)) => format!("&[{a}]"),
("Box", Some(a)) => format!("&{a}"),
_ => better.to_string(),
};
found.push(Finding { file: input.name.clone(), line, id: "TR010",
msg: format!("fn {} parameter `{}: {ty}` borrows a {owned}", f.name, name.trim()),
fix: format!("`{}: {better}` accepts {owned} and more without changing the body", name.trim()) });
}
}
}
// By-value builder method in an inherent impl.
let receiver = split_top(&f.params).first().map(|p| p.replace(' ', "")).unwrap_or_default();
if let Some(b) = block.filter(|_| !trait_impl) {
let self_ty = base_name(&b.trait_and_self().1);
let type_must_use = types.iter().any(|t| t.name == self_ty && attrs_before(&src.code, t.off).contains("must_use"));
let by_value = receiver == "self" || receiver == "mutself";
if by_value && f.ret.trim() == "Self" && is_pub(&src.code, f.off)
&& !type_must_use && !attrs_before(&src.code, f.off).contains("must_use") {
found.push(Finding { file: input.name.clone(), line, id: "TR013",
msg: format!("builder method {self_ty}::{} returns Self by value without #[must_use]", f.name),
fix: format!("#[must_use] on struct {self_ty} (covers all its builder methods)") });
}
}
}
// Type aliases are a common home for Box<dyn Error>.
for i in word_positions(&src.code, "type") {
let stmt = src.code[i..].split(';').next().unwrap_or("");
if stmt.contains('=') && !in_test(i) {
for obj in non_send_dyn_errors(stmt) {
found.push(Finding { file: input.name.clone(), line: src.line_of(i), id: "TR009",
msg: format!("type alias uses `{obj}` without Send + Sync"),
fix: format!("{} + Send + Sync + 'static", obj.trim_end_matches(" + 'static")) });
}
}
}
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 signature")
}
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.