//! Explain one borrow-checker error code or pattern: meaning, ranked fixes, related patterns.
//!
//! Build: rustc -O --edition 2021 scripts/explain_code.rs -o /tmp/explain_code
//! Usage: explain_code E0502 | BCK002 | iterate-and-mutate | --list [--json]
//! Exit: 0 explained, 2 unknown code or usage error.
mod catalog;
mod common;
use catalog::{find_code, find_pattern, tier_name, Fix, Pattern, CODES, PATTERNS, RUNTIME_PATTERNS};
use common::{die, json_str};
const USAGE: &str = "usage: explain_code <CODE|PATTERN> [--json]
explain_code --list [--json]
Explain a Rust borrow/ownership error code (E0382, E0499, E0502, E0505, E0507,
E0515, E0597, E0716, E0373, ...; `lifetime` and `not-send` for the uncoded
'lifetime may not live long enough' / 'future cannot be sent' errors) or a
pattern id/name from parse_diagnostics (BCK001..BCK030, iterate-and-mutate, ...).
Fixes are ranked by tier: restructure > std api > own the data > shared
ownership > last resort. unsafe is never offered as a fix.
options:
--list list every code and pattern
--json machine-readable output
-h, --help";
fn fixes_text(fixes: &[Fix]) -> String {
fixes
.iter()
.enumerate()
.map(|(i, f)| format!(" {}. [{}] {}\n", i + 1, tier_name(f.tier), f.text))
.collect()
}
fn fixes_json(fixes: &[Fix]) -> String {
let items: Vec<String> = fixes
.iter()
.map(|f| format!("{{\"tier\":{},\"text\":{}}}", json_str(tier_name(f.tier)), json_str(f.text)))
.collect();
format!("[{}]", items.join(","))
}
fn pattern_json(p: &Pattern) -> String {
let codes: Vec<String> = p.codes.iter().map(|c| c.to_string()).collect();
format!(
"{{\"id\":{},\"name\":{},\"codes\":{},\"why\":{},\"fixes\":{}}}",
json_str(p.id), json_str(p.name), common::json_list(&codes), json_str(p.why), fixes_json(p.fixes)
)
}
fn list(json: bool) {
let all_patterns = PATTERNS.iter().chain(RUNTIME_PATTERNS);
if json {
let codes: Vec<String> = CODES
.iter()
.map(|c| format!("{{\"code\":{},\"title\":{}}}", json_str(c.code), json_str(c.title)))
.collect();
let pats: Vec<String> = all_patterns
.map(|p| format!("{{\"id\":{},\"name\":{}}}", json_str(p.id), json_str(p.name)))
.collect();
println!("{{\"codes\":[{}],\"patterns\":[{}]}}", codes.join(","), pats.join(","));
return;
}
println!("Error codes:");
for c in CODES {
println!(" {:<9} {}", c.code, c.title);
}
println!("\nPatterns:");
let mut pats: Vec<&Pattern> = all_patterns.collect();
pats.sort_by_key(|p| p.id);
for p in pats {
println!(" {} {:<36} {}", p.id, p.name, p.codes.join(", "));
}
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let json = args.iter().any(|a| a == "--json");
if args.iter().any(|a| a == "-h" || a == "--help") {
println!("{USAGE}");
return;
}
if args.iter().any(|a| a == "--list") {
return list(json);
}
let keys: Vec<&String> = args.iter().filter(|a| !a.starts_with("--")).collect();
let [key] = keys.as_slice() else { die(&format!("expected one code or pattern\n\n{USAGE}")) };
let key = key.trim().trim_start_matches("error[").trim_end_matches(']');
if let Some(code) = find_code(key) {
let related: Vec<&Pattern> = PATTERNS.iter().filter(|p| p.codes.contains(&code.code)).collect();
if json {
let rel: Vec<String> = related.iter().map(|p| pattern_json(p)).collect();
println!(
"{{\"code\":{},\"title\":{},\"meaning\":{},\"fixes\":{},\"patterns\":[{}]}}",
json_str(code.code), json_str(code.title), json_str(code.meaning), fixes_json(code.fixes), rel.join(",")
);
return;
}
println!("{}: {}\n\n{}\n\nFixes, best first:\n{}", code.code, code.title, code.meaning, fixes_text(code.fixes));
if !related.is_empty() {
println!("Patterns that produce {}:", code.code);
for p in related {
println!(" {} {}: {}", p.id, p.name, p.why);
}
}
if code.code.starts_with('E') {
println!("\nFull compiler text: rustc --explain {}", code.code);
}
} else if let Some(p) = find_pattern(key) {
if json {
println!("{}", pattern_json(p));
return;
}
println!("{} {} ({})\n\n{}\n\nFixes, best first:\n{}", p.id, p.name, p.codes.join(", "), p.why, fixes_text(p.fixes));
} else {
die(&format!("unknown code or pattern '{key}'; run with --list to see what is covered"));
}
}
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.
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.