Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

error_flow.rs

Helper script for rust-error-handling-thiserror-anyhow-designer · 129 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references9 scripts
scripts/error_flow.rs
//! Find places where errors lose information on their way up.
//!   ERR006 map-err-discards-source  .map_err(|_| ..)
//!   ERR007 stringly-map-err         .map_err(|e| e.to_string()) / format!("..{e}")
//!   ERR011 discarded-result         let _ = call(); / call().ok();
//!   ERR012 missing-context          bare `?` on fs/parse/serde calls in fns returning anyhow
//!   ERR013 exit-instead-of-return   eprintln! + std::process::exit instead of returning an error
//!
//! Build: rustc -O --edition 2021 scripts/error_flow.rs -o /tmp/error_flow
//! Usage: error_flow <FILES|DIRS|-> [--lib|--app] [--include-tests] [--json] [--strict]

mod cli;
mod rsparse;
mod scope;

use cli::{Finding, Rule};
use rsparse::{items, one_line, Src};
use scope::{enclosing, find_all, Scope};

const RULES: &[Rule] = &[
    Rule { id: "ERR006", name: "map-err-discards-source", severity: "medium",
           why: "`|_|` throws the original error away: no source(), no cause in logs",
           fix: "keep it: .map_err(|e| MyError::Parse { input, source: e }) or a #[from] conversion with `?`" },
    Rule { id: "ERR007", name: "stringly-map-err", severity: "medium",
           why: "turning an error into a String loses its type, its source chain and its backtrace",
           fix: "wrap it in a typed variant (#[source]/#[from]) or add anyhow context: .context(\"..\")" },
    Rule { id: "ERR011", name: "discarded-result", severity: "low",
           why: "a silently ignored Result hides failures (the #[must_use] warning was only silenced)",
           fix: "handle it, propagate with `?`, or log it: if let Err(e) = f() { tracing::warn!(error = %e, \"..\") }" },
    Rule { id: "ERR012", name: "missing-context", severity: "info",
           why: "a bare `?` on I/O or parsing in anyhow code produces 'No such file or directory' without saying which file",
           fix: ".with_context(|| format!(\"reading {}\", path.display()))?" },
    Rule { id: "ERR013", name: "exit-instead-of-return", severity: "medium",
           why: "process::exit skips destructors (buffered writers, temp files) and cannot be tested or reused",
           fix: "return the error to main; `fn main() -> anyhow::Result<()>` or ExitCode prints and exits for you" },
];

const USAGE: &str = "usage: error_flow <FILES|DIRS|-> [options]

Report errors that lose information: map_err(|_| ..) (ERR006), errors turned into Strings
(ERR007), ignored Results (ERR011), bare `?` on I/O or parsing in anyhow code without
context (ERR012) and eprintln! + process::exit instead of returning (ERR013).";

/// Calls whose errors say nothing about *which* input failed.
const NEEDS_CONTEXT: &[&str] = &["fs::", "File::open", "File::create", "read_to_string", ".parse", "from_str", "from_slice", "from_reader", "serde_json::", "toml::"];

/// The expression that ends at `q` (a `?`), back to the start of its statement.
fn statement_before(code: &str, q: usize) -> &str {
    let start = code[..q].rfind([';', '{', '}']).map_or(0, |i| i + 1);
    &code[start..q]
}

fn main() {
    let usage = format!("{USAGE}\n\n{}", scope::SCOPE_HELP);
    let opts = cli::parse(&usage, RULES, &[], scope::SWITCHES);
    let inputs = opts.inputs();
    let mut findings = Vec::new();
    for input in &inputs {
        let src = Src::new(input.text.clone());
        let (fns, _, _) = items(&src);
        let scope = Scope::new(input, &src, &fns, &opts);
        let code = &src.code;
        let in_fn = |off: usize| enclosing(&fns, &src, off).map_or(String::new(), |f| format!(" in fn {}", f.name));
        let mut found = Vec::new();
        let mut push = |off: usize, id: &'static str, msg: String| {
            if !scope.skip(off) {
                found.push(Finding { file: input.name.clone(), line: src.line_of(off), id, msg, fix: String::new() });
            }
        };

        for off in find_all(code, ".map_err(") {
            let open = off + ".map_err".len();
            let close = rsparse::close_of(code, open);
            let (args, args_orig) = (code[open + 1..close - 1].trim(), src.orig[open + 1..close - 1].trim());
            let call = one_line(&src.orig[off..close]);
            if args.starts_with("|_|") {
                push(off, "ERR006", format!("`{call}`{} discards the original error", in_fn(off)));
            } else if let Some((var, body)) = args.strip_prefix('|').and_then(|a| a.split_once('|')) {
                let var = var.trim();
                let body_orig = &args_orig[args_orig.len() - body.len()..];
                let uses_var = !rsparse::word_positions(body_orig, var).is_empty();
                let stringly = body.contains(&format!("{var}.to_string()")) || body.contains("format!") && uses_var;
                if stringly && !var.is_empty() {
                    push(off, "ERR007", format!("`{call}`{} turns the error into a String", in_fn(off)));
                }
            }
        }

        for off in find_all(code, "let _ =") {
            let stmt = code[off..].split(';').next().unwrap_or("");
            if stmt.contains('(') && !stmt.contains("drop(") {
                push(off, "ERR011", format!("`{}`{} ignores a Result", one_line(stmt), in_fn(off)));
            }
        }
        for off in find_all(code, ".ok();") {
            let stmt_start = code[..off].rfind([';', '{', '}']).map_or(0, |i| i + 1);
            let stmt = code[stmt_start..off].trim();
            if !stmt.starts_with("let ") && !stmt.starts_with("return") && !stmt.contains('=') {
                push(off, "ERR011", format!("`{}.ok();`{} ignores a Result", one_line(stmt), in_fn(off)));
            }
        }

        for f in fns.iter().filter(|f| f.ret.contains("anyhow")) {
            let Some(open) = code[f.off..].find('{').map(|n| f.off + n + 1) else { continue };
            for (i, _) in f.body.match_indices('?') {
                let stmt = statement_before(&f.body, i);
                if NEEDS_CONTEXT.iter().any(|c| stmt.contains(c)) && !stmt.contains("context(") {
                    push(open + i, "ERR012", format!("bare `?` on `{}` in fn {} (anyhow): which input failed?", one_line(stmt.trim()), f.name));
                }
            }
        }

        for f in &fns {
            if f.body.contains("eprintln!") && (f.body.contains("process::exit") || f.body.contains(" exit(")) {
                push(f.off, "ERR013", format!("fn {} prints an error and calls process::exit", f.name));
            }
        }
        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)));
    }
    let fixes: Vec<Finding> = findings
        .into_iter()
        .map(|mut f| {
            f.fix = RULES.iter().find(|r| r.id == f.id).map_or(String::new(), |r| r.fix.to_string());
            f
        })
        .collect();
    cli::finish(&opts, RULES, fixes, inputs.len(), "error flow")
}
More in Rust

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-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.