//! Shared helpers for the borrow-checker scripts: input, JSON output, cargo JSON lines.
//! Not an entry point; each script pulls it in with `mod common;`.
#![allow(dead_code)] // not every script uses every helper
use std::io::Read;
use std::process;
/// Print `msg` to stderr and exit with code 2 (usage or input error).
pub fn die(msg: &str) -> ! {
eprintln!("error: {msg}");
process::exit(2);
}
/// Read a file, or stdin when `path` is "-".
pub fn read_input(path: &str) -> String {
let mut text = String::new();
let result = if path == "-" {
std::io::stdin().read_to_string(&mut text).map(|_| ())
} else {
std::fs::read_to_string(path).map(|t| text = t)
};
if let Err(e) = result {
die(&format!("cannot read {path}: {e}"));
}
text
}
/// Quote and escape a string for JSON output.
pub fn json_str(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// `["a","b"]` from a list of strings.
pub fn json_list(items: &[String]) -> String {
let parts: Vec<String> = items.iter().map(|s| json_str(s)).collect();
format!("[{}]", parts.join(","))
}
/// Decode the JSON string value of the first `"key":"..."` in `line`.
/// Enough for cargo/rustc `--message-format=json`, whose `rendered` field holds the
/// exact text rustc prints, so one text parser handles both formats.
pub fn json_string_field(line: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
let mut out = String::new();
let mut chars = line[start..].chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => match chars.next()? {
'n' => out.push('\n'),
't' => out.push('\t'),
'r' => out.push('\r'),
'b' => out.push('\u{8}'),
'f' => out.push('\u{c}'),
'u' => {
let hi = hex4(&mut chars)?;
let code = if (0xD800..0xDC00).contains(&hi) {
// surrogate pair: 😀
if chars.next()? != '\\' || chars.next()? != 'u' {
return None;
}
let lo = hex4(&mut chars)?;
0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00)
} else {
hi
};
out.push(char::from_u32(code).unwrap_or('\u{fffd}'));
}
other => out.push(other), // \" \\ \/
},
c => out.push(c),
}
}
None
}
fn hex4(chars: &mut std::str::Chars) -> Option<u32> {
let s: String = chars.by_ref().take(4).collect();
u32::from_str_radix(&s, 16).ok()
}
/// Turn cargo/rustc JSON lines into the plain text rustc would print; plain text passes through.
pub fn normalize(input: &str) -> String {
let mut out = String::new();
for line in input.lines() {
let t = line.trim_start();
if t.starts_with('{') && t.contains("\"rendered\"") {
if let Some(r) = json_string_field(t, "rendered") {
out.push_str(&r);
out.push('\n');
}
} else if !t.starts_with('{') {
out.push_str(line);
out.push('\n');
}
}
out
}
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.