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

trait_shape.rs

Helper script for rust-trait-design-reviewer · 123 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references7 scripts
scripts/trait_shape.rs
//! Find trait and impl shapes that fight Rust's conventions.
//!   TR002 impl-into-not-from   impl Into<DocumentId> for RawId   -> impl From<RawId> for DocumentId
//!   TR005 deref-inheritance    impl Deref<Target = Document> for VersionedDocument (multi-field struct)
//!   TR006 fat-trait            pub trait with more than --max-methods required methods (default 8)
//!   TR007 single-impl-trait    private trait, one impl for a local type, never dyn or a bound
//!
//! Build: rustc -O --edition 2021 scripts/trait_shape.rs -o /tmp/trait_shape
//! Usage: trait_shape <FILES|DIRS|-> [--max-methods N] [--json] [--strict] [--select IDS] [--ignore IDS]

mod cli;
mod rsparse;

use cli::{Finding, Rule};
use rsparse::{base_name, is_pub, items, one_line, split_top, traits, word_positions, ImplBlock, Src, TypeDef};

const RULES: &[Rule] = &[
    Rule { id: "TR002", name: "impl-into-not-from", severity: "medium",
           why: "implementing From gives Into for free (blanket impl); an Into impl gives nothing back",
           fix: "impl From<Source> for Target (and TryFrom instead of TryInto)" },
    Rule { id: "TR005", name: "deref-inheritance", severity: "medium",
           why: "Deref is for smart pointers; using it to inherit a struct's methods confuses method resolution and docs",
           fix: "delegate the needed methods explicitly, expose `fn inner(&self) -> &Inner`, or share a trait" },
    Rule { id: "TR006", name: "fat-trait", severity: "low",
           why: "every implementor must write every required method; large traits are hard to implement and to evolve",
           fix: "split into smaller traits, give methods default bodies, or move helpers to an extension trait" },
    Rule { id: "TR007", name: "single-impl-trait", severity: "low",
           why: "a private trait with one local implementor and no generic use is indirection without a second user",
           fix: "make the methods inherent (`impl Type { .. }`) until a second implementor or a test fake exists" },
];

const USAGE: &str = "usage: trait_shape <FILES|DIRS|-> [--max-methods N] [options]

Report Into impls that should be From (TR002), Deref used for inheritance (TR005), traits
with too many required methods (TR006) and private single-implementor traits (TR007).
Scan the whole crate: impls and uses in other files count.

  --max-methods N      TR006 threshold: required (body-less) methods allowed (default 8)";

fn deref_target(b: &ImplBlock) -> Option<String> {
    let i = b.body.find("type Target")?;
    let rest = &b.body[i + "type Target".len()..];
    let rest = rest.trim_start().strip_prefix('=')?;
    Some(rest.split(';').next()?.trim().to_string())
}

fn main() {
    let opts = cli::parse(USAGE, RULES, &["--max-methods"]);
    let max: usize = opts.value("--max-methods").map_or(8, |v| v.parse().unwrap_or_else(|_| cli::die("--max-methods needs a number")));
    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();

    // Crate-wide facts: local type definitions, every impl, every dyn use.
    let local_types: Vec<&TypeDef> = parsed.iter().flat_map(|(_, t, _)| t).collect();
    let all_impls: Vec<(String, String)> = parsed
        .iter()
        .flat_map(|(_, _, impls)| impls.iter().filter_map(|b| match b.trait_and_self() {
            (Some(t), s) => Some((base_name(&t), base_name(&s))),
            _ => None,
        }))
        .collect();
    let all_code: String = srcs.iter().map(|s| s.code.as_str()).collect::<Vec<_>>().join("\n");

    let mut findings = Vec::new();
    for ((input, src), (fns, _, impls)) in inputs.iter().zip(&srcs).zip(&parsed) {
        let mut found = Vec::new();
        for b in impls {
            let line = src.line_of(b.off);
            let (Some(tr), self_ty) = b.trait_and_self() else { continue };
            let name = base_name(&tr);
            if name == "Into" || name == "TryInto" {
                let target = tr.split_once('<').map_or("T", |(_, r)| r.trim_end_matches('>')).trim();
                let from = if name == "Into" { "From" } else { "TryFrom" };
                found.push(Finding { file: input.name.clone(), line, id: "TR002",
                                     msg: format!("`impl {}` for {}: implement {from} instead", one_line(&tr), one_line(&self_ty)),
                                     fix: format!("impl {from}<{}> for {target}", one_line(&self_ty)) });
            }
            if name == "Deref" {
                let target = deref_target(b).unwrap_or_default();
                let fields: Vec<String> = local_types
                    .iter()
                    .find(|t| t.name == base_name(&self_ty))
                    .map_or(vec![], |t| split_top(&t.body));
                let target_local = local_types.iter().any(|t| t.name == base_name(&target) && t.kind == "struct");
                if target_local && fields.len() > 1 {
                    // The field that holds the target, for the delegation example.
                    let inner = fields
                        .iter()
                        .find_map(|f| f.split_once(':').filter(|(_, ty)| base_name(ty) == base_name(&target)))
                        .map_or("inner".to_string(), |(n, _)| n.trim().trim_start_matches("pub ").to_string());
                    found.push(Finding { file: input.name.clone(), line, id: "TR005",
                                         msg: format!("{} derefs to {target}: Deref used as inheritance on a {}-field struct", one_line(&self_ty), fields.len()),
                                         fix: format!("delegate each method callers need (`fn x(&self) -> &T {{ &self.{inner}.x }}`) or expose `fn {inner}(&self) -> &{target}`") });
                }
            }
        }
        for t in traits(src) {
            let line = src.line_of(t.off);
            let required = fns.iter().filter(|f| t.span.0 < f.off && f.off < t.span.1 && f.body.is_empty()).count();
            if is_pub(&src.code, t.off) && required > max {
                found.push(Finding { file: input.name.clone(), line, id: "TR006",
                                     msg: format!("pub trait {} has {required} required methods (max {max})", t.name), fix: String::new() });
            }
            let impls_of: Vec<&(String, String)> = all_impls.iter().filter(|(tr, _)| *tr == t.name).collect();
            let used_generically = word_positions(&all_code, &t.name).iter().any(|&i| {
                let before = all_code[..i].trim_end();
                let header = all_code[i..].split(['{', ';', ',', ')']).next().unwrap_or("");
                before.ends_with("dyn") || before.ends_with("impl") && !header.contains(" for ")
                    || before.ends_with(':') || before.ends_with('+')
            });
            if !is_pub(&src.code, t.off) && impls_of.len() == 1 && !used_generically
                && local_types.iter().any(|ty| ty.name == impls_of[0].1) {
                found.push(Finding { file: input.name.clone(), line, id: "TR007",
                                     msg: format!("private trait {} has one implementor ({}) and no generic or dyn use", t.name, impls_of[0].1),
                                     fix: format!("move its methods into `impl {} {{ .. }}`", impls_of[0].1) });
            }
        }
        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(), "trait-shape")
}
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-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.