Rust Engineering Standard

v1.2 · Pinned (Latest)

Agent-ready linting, formatting, safety, dependency, and verification standard for Rust repositories using rustc, Clippy, rustfmt, Cargo lints, and cargo-deny.

Agent access · Pure Markdown (no HTML)

Coding agents can fetch /standards/rust/v1.2.md directly (or pinned https://fitchhub.com/standards/rust/v1.2.md), or request this page URL with Accept: text/markdown to receive pure Markdown without HTML.

Version 1.2 · 1 December 2026

  • Canonical agent-readable Markdown (always the latest version): https://fitchhub.com/standards/rust.md
  • Pinned release Markdown (this version only): https://fitchhub.com/standards/rust/v1.2.md

This standard governs Rust workspace design, linting, formatting, dependency policy, and verification. It applies to agents adopting or updating these checks and to engineers reviewing their work.

Apply strict checks by default. Relax an applicable check only when the best reasonable compliant implementation harms a supported contract or adds disproportionate complexity without a meaningful safety or correctness benefit.

Treat the baseline as a floor, not a ceiling. Keep stronger local checks that work. Show the user driving the work where those checks add value so they can be considered for this standard.

Quality-tool versions are minimums, never pins or ceilings. Use current releases for the quality job, with Rust 1.100.1 or later. A repository can pin the selected toolchain for reproducibility. The package.rust-version field makes a separate compatibility promise for libraries covered by Section 6.1.

Raise regressions directly to the user driving the work. Present concrete evidence before weakening a requirement or adding a workaround. A passing build alone does not establish that behavior is correct.

Each adopting repository supplies its own manifests, supported target and feature combinations, and acceptance commands.

  1. Quality, current-date grounding, and authority
  2. Quality exceptions
  3. Code design and behavioral contracts
  4. Workspace coverage, editions, and toolchains
  5. Compiler, Cargo, and Clippy requirements
  6. Composable profiles
  7. Formatting, dependencies, and artifacts
  8. Verification and enforcement integrity
  9. Adoption, upgrades, and escalation
  10. Acceptance and maintenance

1. Quality, current-date grounding, and authority

Link to 1. Quality, current-date grounding, and authority

1.1 Quality criteria

Link to 1.1 Quality criteria
CriterionRequired outcome
CorrectnessSupported inputs, failures, and state transitions preserve the public contract.
MaintainabilityEach invariant has an owner. Changing it does not require finding undocumented copies.
ReadabilityNames, types, and control flow explain who owns data and where an operation can fail.
ConsistencyEquivalent operations use the same contracts for errors, resource ownership, and persistence.
ReuseConsumers share the authoritative type or operation without depending on unrelated policy.
EfficiencyAllocations, copies, locks, and scheduling costs fit the measured workload.

1.2 Current-date, native-first engineering

Link to 1.2 Current-date, native-first engineering

Inspect the installed tools before proposing wrappers or custom lint engines. Use rustc -W help, cargo clippy --explain <lint>, rustfmt --help=config, and rustdoc -W help. Check the installed crate source and documentation for the version in Cargo.lock. Reproduce surprising behavior with the repository's actual target and features.

Prefer Edition 2024 and the native checks available in Rust 1.100.1. Use [lints.cargo] for manifest checks, CARGO_BUILD_WARNINGS=deny for acceptance, and #[expect(..., reason = "...")] for reviewed exceptions. In clippy.toml, use replacement = "..." in a disallowed-methods entry to name the approved alternative.

The quality job must run Rust 1.100.1 or later. Read rust-toolchain.toml for the selected compiler. For libraries covered by Section 6.1, read package.rust-version for the minimum supported Rust version (MSRV). Adopt a new library API only if that compiler supports it.

1.3 Requirements, discretion, and escalation

Link to 1.3 Requirements, discretion, and escalation

Must identifies a requirement. Should identifies a recommendation for the stated context. May identifies a permitted choice. Apply the baseline and compose the profiles that describe the code. Mapping an embedded crate to its target triple or a CLI to its output stream preserves enforcement. Neither mapping requires an exception.

Disabling a check, raising a limit, or excluding supported code reduces coverage regardless of whether the change lives in a manifest, attribute, script, or CI job. A relaxation beyond a defined profile requires Section 2. Adoption alone does not authorize merging, deploying, altering product contracts, or overwriting unrelated work. Escalate regressions under Section 9.4 and preserve effective stronger checks under Section 9.5.

2. Quality exceptions

Link to 2. Quality exceptions

Compare realistic alternatives, including a straightforward compliant implementation. An exception is eligible only if that implementation would harm a supported contract (including safety, compatibility, or measured performance), or add disproportionate complexity without a meaningful safety or correctness benefit. A deadline, a long diagnostic list, and a preference for the old code do not qualify.

2.2 Decision process

Link to 2.2 Decision process

Reproduce the finding on the affected target and features. Compare the best compliant implementation with the proposed exception in code review. Identify the contract at risk and the type, boundary check, or test that protects it. Limit the exception to the item, target, or feature that needs it.

2.3 Structural, panic, and unsafe exception evidence

Link to 2.3 Structural, panic, and unsafe exception evidence

For cognitive_complexity or too_many_arguments, show the actual decision structure or signature. Compare a cohesive extraction. Identify the shared borrow, ordering constraint, or ABI the extraction would obscure or break. Line count alone does not establish harm.

For panic, unwrap, and indexing exceptions, prove the invariant in the types or at the input boundary. Explain why it still holds at the operation. A passing example does not prove an index is always in range or a string offset is always a character boundary.

For unsafe, account for aliasing, provenance, alignment, lifetime, initialization, ABI, and thread safety where applicable. Link each obligation to the caller precondition or implementation that establishes it. A // SAFETY: comment is evidence to audit, not proof of soundness.

2.4 Scope, attributes, and automated suppression enforcement

Link to 2.4 Scope, attributes, and automated suppression enforcement

Put #[expect(lint, reason = "concrete invariant or contract")] directly on the affected item. For example, #[expect(clippy::too_many_arguments, reason = "matches the registered callback signature")]. If a diagnostic fires only on a specific target or feature, use #[cfg_attr(..., expect(..., reason = "..."))] with the same condition.

For an exemption that applies to a whole crate, module, or function body, use an inner #![allow(..., reason = "...")] attribute. For example, an FFI crate can use #![allow(unsafe_code, reason = "owns the vendor ABI calls and handle lifetimes")]. If a configuration-dependent finding requires an outer #[allow(..., reason = "...")], pair it with #[expect(clippy::allow_attributes, reason = "...")]. When #[cfg_attr(...)] supplies the outer allow, put the expectation under the same condition.

Keep clippy::allow_attributes to flag outer allow attributes in favor of expect. It skips inner #![allow] attributes. Keep clippy::allow_attributes_without_reason to check both forms of allow and expect for a reason. Both Clippy checks respect the configured MSRV (Rust 1.81 or later for this enforcement). Keep unfulfilled_lint_expectations to flag an expectation when the checker runs but the finding no longer occurs.

Use code review to check that each reason explains the actual invariant. Reject blanket suppressions such as #![allow(warnings)] and #[allow(clippy::all)], undocumented suppressions, and groups of unused-code suppressions that hide scaffolding.

A multi-crate workspace may add a small cargo metadata manifest check to verify [lints] workspace = true beyond what cargo::missing_lints_inheritance checks.

2.5 Non-negotiable boundaries

Link to 2.5 Non-negotiable boundaries
  • Preserve checker exit codes and diagnostics. Do not filter findings or silently drop [lints] workspace = true.
  • Do not turn failures the caller must handle into .unwrap() or panic!(), or discard them with a silent if let Ok(_), drop(...), or let _ =. Use drop(...) or let _ = only for the intentional outcome discards defined in Section 3.2.
  • Do not fabricate an unsafe impl Send or unsafe impl Sync to satisfy an executor.
  • Do not hide production code behind #[cfg(not(test))] to bypass verification.
  • Do not weaken assertions, delete a failing case, or replace the real boundary with a mock that implements the expected result.

3. Code design and behavioral contracts

Link to 3. Code design and behavioral contracts

3.1 Shared contracts, types, and reuse

Link to 3.1 Shared contracts, types, and reuse

Give each domain contract one authoritative crate or module. Use a newtype for a validated identifier, and an enum when only named states are valid. Share the parser and type across callers rather than interpreting raw strings or integers independently.

Libraries should expose typed error enums, for example with thiserror. Applications and CLIs may aggregate failures with anyhow at their outer boundary. Do not expose Result<T, String>, Result<T, ()>, or Box<dyn Error> in public library APIs unless an external trait contract requires it. Implement Default only when the value represents a valid initial state.

In compilers, code generators, serializers, and cache-key builders, define the order of the output. Iterate a BTreeMap, a BTreeSet, or sorted keys. Iterating a HashMap or HashSet directly can change emitted bytes and cache digests across runs with identical inputs. Crates that require deterministic output may enable clippy::iter_over_hash_type to check for loops.

3.2 Ownership, borrowing, fallibility, and conversions

Link to 3.2 Ownership, borrowing, fallibility, and conversions

Accept &str, &[T], or &Path when a function needs only a view. Justify a deep .clone() by the distinct owner that needs the copy. Use Arc::clone(&x) and Rc::clone(&x) for reference-count increments (clone_on_ref_ptr). Introduce Arc<Mutex<T>> for an actual shared mutation contract, not to silence the borrow checker. Do not manufacture a 'static lifetime with Box::leak.

Keep production paths panic-free. Propagate fallible work with ?. Use .get(), .first(), iterators, or slice patterns to handle missing elements. For UTF-8, use .get(..n), checked character boundaries, or character iterators instead of &s[..n]. Prefer From for lossless conversions and TryFrom for checked conversions. Choose checked or saturating arithmetic according to the domain rather than hiding overflow with as.

Retain underlying errors with #[source], #[from], or .context(...). Do not erase the cause with .map_err(|_| ...) or silently discard a failure the caller can handle. Use a guard that rolls back in Drop so ? and early returns run the same cleanup.

Never discard a result with .ok();. clippy::unused_result_ok flags the unused conversion to Option. When the contract permits discarding the outcome, choose the form by type:

  • For a non-Copy result, call drop(expr); at the intended discard point. Use this form when the type has drop glue (a destructor on the value or one of its fields). For example, drop(std::fs::remove_dir_all(&scratch)); discards an io::Result<()> when scratch-directory cleanup is best effort. let _ = expr; triggers let_underscore_drop in that case. For a non-Copy result without a destructor, such as Result<(), UnitError> with a non-Copy unit struct as the error, both forms pass. Prefer drop(expr); for consistency.
  • For a Copy result marked #[must_use], write let _ = expr;. drop(expr) triggers dropping_copy_types. For example, let _ = write!(string, "{value}"); discards a Result<(), std::fmt::Error> when both formatting value and writing to the String are infallible. Other examples include OnceLock::set on a Copy value when an earlier initialization is acceptable, and AtomicUsize::compare_exchange when either outcome satisfies the caller.

3.3 Behavioral preservation and banned compliance shims

Link to 3.3 Behavioral preservation and banned compliance shims
ContractPreserve when changing code to satisfy a check
Errors and panicsError variants, cause chains, exit status, and recovery at fallible boundaries.
Data and serializationWire names, representations, numeric ranges, UTF-8 boundaries, and compatibility with stored data.
Ownership, drops, and stateBorrow duration, destruction order, cleanup, and visibility of committed state.
Concurrency and asyncLock ordering, cancellation, backpressure, task completion, and ordering guarantees.
unsafe, ABI, and FFILayout, calling convention, pointer validity, ownership transfer, and unwind boundaries.
Distribution and featuresPublic API, MSRV, published dependencies, supported feature sets, and target triples.

Do not replace an unwrap with a silent if let Ok(...), keep unused bindings or dead scaffolding with let _ = unused_var; or #[allow(dead_code)], or derive a bogus Default. Do not invent a parameter bag or split a function solely to pass a threshold. Do not dodge a cast diagnostic with std::mem::transmute. todo!() and unimplemented!() are not finished behavior. #[cfg(not(test))] is not a fix for a failing test.

3.4 Decomposition and module boundaries

Link to 3.4 Decomposition and module boundaries

Split responsibilities at a contract a caller can understand independently. Keep a cohesive match or state transition together when extraction would scatter its invariants. Start private. Use pub(crate) when another module in the crate needs access. Enable dead_code_pub_in_binary in binary crate roots (Section 6.2). Enable unreachable_pub and unnameable_types in publishable or externally consumed library crate roots (Section 6.1). Match owned enum variants explicitly. Without a _ => arm, adding a variant makes the compiler identify each consumer that needs review.

3.5 Practices to correct

Link to 3.5 Practices to correct
Finding in the adoption scopeCorrection
A parser returns a string that every caller validates again.Return a validated domain type and a typed parse error.
An extra clone ends a borrow conflict.Inspect who needs ownership. Split the borrow or move the value at its last use.
A mutex serializes independent work.Give the state one owner or borrow disjoint fields before introducing synchronization.
A placeholder match arm returns success.Handle the variant or return an error the caller can act on.
An error message contains a formatted cause but no source.Wrap the original error so callers can inspect or report the chain.
A helper exists only to move a warning.Restore the cohesive operation and resolve the underlying finding.

4. Workspace coverage, editions, and toolchains

Link to 4. Workspace coverage, editions, and toolchains

4.1 Source, target, and feature coverage matrix

Link to 4.1 Source, target, and feature coverage matrix
Code or configurationRequired coverage
Library, binaries, tests, benches, examplesOn a target with std and test, --workspace --all-targets checks these Cargo target kinds for one triple. For bare-metal targets without test, use Section 6.5. Run Clippy on every supported OS target. Add architecture coverage for supported triples. Cross-compilation does not execute tests.
FeaturesCheck the default build, supported no-default builds, and supported combinations. Use --all-features only when the features coexist.
Documentation examplesRun doctests separately when using nextest. Verify the feature and target assumptions in examples.
build.rsDeclare file and environment inputs as specified in Section 7.3. Require deterministic output and zero network calls.
Proc macrosCheck the host-built macro crate and exercise its expansions in consuming crates on the supported targets.
Generated, vendored, and patched codeRecord origin, version or revision, owner, and freshness check. Test the real generated output or resolved [patch.crates-io] path.

Run Clippy on a native runner for each supported OS. If you ship on Windows and macOS, check both. A single OS leaves other #[cfg(...)] modules unchecked for dead code, undocumented unsafe blocks, and incompatible extern declarations.

From another host, cargo clippy --target <triple> can check pure-Rust crates when the target's rust-std is installed. Native dependencies change that requirement. A -sys build script that invokes cc, cmake, pkg-config, or bindgen fails if it lacks the required cross toolchain or target headers. When you retire an OS or architecture, delete its dead #[cfg(...)] modules and remove its triple from rust-toolchain.toml targets.

Packages in [workspace] exclude, such as standalone test fixtures or fuzz targets, are not workspace members. --workspace, cargo fmt --all, and cargo::missing_lints_inheritance do not cover them as members. Check each active excluded package with --manifest-path, or document which integration tests compile it on demand.

4.2 Edition 2024, resolver 3, and toolchain pin vs MSRV

Link to 4.2 Edition 2024, resolver 3, and toolchain pin vs MSRV

Default to edition = "2024". Set [workspace] resolver = "3" explicitly in a virtual workspace: the members' edition does not select the virtual workspace's resolver. For private packages, inherit [workspace.package] publish = false with publish.workspace = true.

rust-toolchain.toml pins the compiler for developers and the quality job. Only publishable or externally consumed libraries (Section 6.1) need a package.rust-version guarantee and a separate build and test job when that MSRV is older than the quality compiler. Resolver 3 defaults resolver.incompatible-rust-versions to "fallback" and prefers MSRV-compatible dependencies. That preference does not prove a library builds on its MSRV. Do not pass the quality job's CARGO_BUILD_WARNINGS=deny to an older-MSRV build.

For a publish = false private application workspace, verify the pinned toolchain. Omit an older package.rust-version that the application neither supports nor tests. Clippy reads that field as its MSRV even when rust-toolchain.toml pins a newer compiler. The default clippy::incompatible_msrv warning then flags calls to newer standard-library APIs. A stale MSRV also suppresses checks whose suggestions need a newer compiler, including non_std_lazy_statics, allow_attributes, manual_is_variant_and, and filter_map_next.

4.3 Workspace lint and dependency inheritance

Link to 4.3 Workspace lint and dependency inheritance

[workspace.lints.*] has no effect on a member until its manifest declares [lints] workspace = true. Cargo rejects local lint keys alongside workspace = true in the same package lint table. Apply a profile through scoped crate or module attributes or a targeted quality command. Do not detach a member to customize it.

cargo::missing_lints_inheritance detects a missing table, not an empty or independent one. Verify inheritance in each participating manifest.

Declare shared internal and external dependencies in [workspace.dependencies]. Inherit each one with name.workspace = true in member manifests. Add only package-specific features or optional = true there. Cargo 1.100.1 reports unreferenced root entries with cargo::unused_workspace_dependencies. No native lint reports a member's direct version string in place of .workspace = true. Check member manifests during adoption and dependency reviews.

5. Compiler, Cargo, and Clippy requirements

Link to 5. Compiler, Cargo, and Clippy requirements

5.1 Toolchain version floors and warning enforcement

Link to 5.1 Toolchain version floors and warning enforcement

These minimum versions were verified on 1 December 2026. Install current releases, inspect changes in defaults and schemas, and record the selected versions. An optional tool's floor applies when the repository uses it.

ToolMinimum for the quality jobBasis
rustc, cargo>= 1.100.11.100.0 stabilized [lints.cargo]. Version 1.100.1 fixed a const Iterator inference regression. Use the corresponding rustdoc.
Clippy>= 0.1.100Bundled with the supported Rust toolchain.
rustfmt>= 1.11.0Stable formatter bundled with the supported Rust toolchain.
cargo-deny>= 0.22.20.22.1 fixed multi-version unsound and unmaintained advisory handling. Building from source requires Rust 1.95 or later.
cargo-nextest (conditional)>= 0.9.152Includes the 0.9.150 security floor.
cargo-shear (optional)>= 1.14.1Additional dependency-use checks, including development dependencies.
cargo-hack (conditional)>= 0.6.46Feature-combination coverage.
cargo-semver-checks (conditional)>= 0.51.0Public API comparison. Requires Rust 1.93 or later.
cargo-audit (optional)>= 0.23.0Lockfile and auditable binary scans.

In the current quality job (Rust >= 1.100.1), use CARGO_BUILD_WARNINGS=deny with cargo clippy, cargo check, cargo test, and cargo doc when you run them. Cargo 1.97 stabilized this setting. The config equivalent is [build] warnings = "deny". Keep the setting scoped to the quality job. Cargo 1.97 through 1.99 reports lints.cargo as an unused manifest key. This warning is unstructured. Even with CARGO_BUILD_WARNINGS=deny, that warning alone leaves the exit code at 0. Older MSRV compilers have different warning sets. Expectations for newer lints can trigger unfulfilled_lint_expectations and fail a compatibility build that denies warnings.

  1. It denies local-package compiler, Clippy, rustdoc, and [lints.cargo] manifest lint warnings. cargo clippy -- -D warnings can exit 0 on a cargo::* manifest warning because the trailing flags go to the compiler.
  2. It reuses Cargo's artifact cache without re-keying dependency builds. Global RUSTFLAGS="-D warnings" changes compile-unit identity, including dependencies, and reaches host build scripts and proc macros unless --target is passed.
  3. It preserves the compiler flags in .cargo/config.toml. Setting RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS in the environment overrides both [build].rustflags and [target.<triple>].rustflags. The build can silently lose -C target-cpu=native, linker flags, or a target's stack-size setting.
  4. Ordinary recommendations can remain "warn" locally and still fail acceptance. Keep hard invariants at "deny" even locally: clippy::correctness, unsafe_code outside the boundaries in Section 6.3, unsafe_op_in_unsafe_fn, unused_must_use, non_ascii_idents, clippy::undocumented_unsafe_blocks, and rustdoc::broken_intra_doc_links.

CARGO_BUILD_WARNINGS=deny does not turn cargo::warning= messages from build scripts into errors. It also does not deny compiler warnings inside doctest bodies. Use #![deny(warnings)] in a doctest to reject warnings such as a call to a deprecated function. This attribute does not enable lints that rustdoc allows in doctests. For example, use #![deny(unused_variables)] to reject unused variables.

For compact agent diagnostics, use --message-format=short. Switch to --message-format=human for spans and help, or --message-format=json for a structured consumer. Cargo has no --message-format=agent.

In rust-analyzer, set "rust-analyzer.check.command": "clippy". rust-analyzer.check.allTargets inherits cargo.allTargets, which defaults to true. Editor feedback neither replaces the acceptance job nor ensures that member manifests inherit workspace lints.

5.2 Base lint configuration and priority rules

Link to 5.2 Base lint configuration and priority rules

Start with Appendix A. Never write all = { level = "warn", priority = -1 }. In Clippy 0.1.100, clippy::all aliases clippy::default: 67 deny-by-default correctness lints and 428 warn-by-default suspicious, complexity, perf, and style lints. Setting all 495 to warn downgrades every correctness lint.

Keep correctness = { level = "deny", priority = -1 }. Give suspicious, complexity, perf, and style the same priority with level warn. Individual lint settings default to priority 0 and take precedence. clippy::lint_groups_priority denies ambiguous group priority by default.

Opt in to the individual pedantic, restriction, and nursery lints in Appendix A.1. Never enable those groups wholesale. Pedantic includes false positives and noisy style checks (Section 5.4). Restriction includes conflicting requirements (clippy::blanket_clippy_restriction_lints). Nursery includes lints that still produce false positives.

Set rustdoc::broken_intra_doc_links to "deny" to reject unresolved links locally. Keep rustdoc::private_doc_tests in the library profile (Section 6.1), outside the workspace baseline. rustdoc 1.100.1 already warns on private_intra_doc_links, invalid_html_tags, invalid_rust_codeblocks, invalid_markdown_table, and bare_urls. CARGO_BUILD_WARNINGS=deny enforces those defaults without repeating them in Cargo.toml.

Check stability before adding lints. In rustc 1.100.1, rustc -W help lists 14 unstable lints: eight allow-by-default, two warn-by-default, and four deny-by-default. The allow-by-default lints include must_not_suspend, implicit_provenance_casts, non_exhaustive_omitted_patterns, and unqualified_local_imports. Likewise, rustdoc -W help lists rustdoc::missing_doc_code_examples. Listing a lint does not make it usable on stable: naming these can trigger unknown_lints. Test the setting on the actual stable compiler. Use underscore names in Cargo.toml. Cargo 1.99 and later warn on hyphenated lint names.

5.3 Structural thresholds and test allowances

Link to 5.3 Structural thresholds and test allowances
clippy.toml settingValueApplication
cognitive-complexity-threshold20Inspect branches and nested decisions before extracting code.
max-fn-params-bools1Replace ambiguous flags with a domain enum when callers must distinguish modes.
too-many-arguments-threshold7 (Clippy default)Keep separate parameters when an ABI or independent borrows require them.

Leave excessive-nesting-threshold unset. Clippy counts mod, impl, and fn blocks in excessive_nesting. A threshold of 4 flags a single for loop with one if inside an inline mod and impl.

clippy.toml test settingValueEffect in recognized test code
allow-unwrap-in-teststrueAllow a test to fail on a missing value.
allow-expect-in-teststrueAllow a failure message with test context.
allow-indexing-slicing-in-teststrueAllow direct fixture access. The key is not allow-indexing-in-tests.
allow-panic-in-teststrueAllow explicit failure on an unexpected test path.
allow-print-in-teststrueAllow captured test output.
allow-dbg-in-testsfalseCatch leftover debugging probes in tests too.

allow-indexing-slicing-in-tests = true does not exempt clippy::string_slice. Even in tests, use .get(..n) or character-boundary APIs instead of &s[..n] on a string.

Clippy 0.1.100 applies allow-*-in-tests to #[test] functions, bare #[cfg(test)] modules, and compiler input paths starting with tests/. It misses compound attributes such as #[cfg(all(test, target_os = "macos"))]. Stack #[cfg(test)] above #[cfg(target_os = "macos")] so the allowances reach helpers inside the module.

In a multi-crate workspace, crates/<member>/tests/*.rs does not start with tests/. The #[test] functions get the allowances, but ordinary helpers alongside them can still trigger unwrap_used and indexing_slicing. Return Result from helpers and use ? in the test, or put a helper that needs test-only allowances in a bare #[cfg(test)] module.

5.4 Deliberate baseline choices

Link to 5.4 Deliberate baseline choices
Setting or omissionReason and remaining protection
correctness = "deny"Preserve deny-by-default findings during local iteration. Never set all = "warn".
unsafe_code = "deny"Reject accidental unsafe code while permitting reviewed opt-ins or the systems workspace policy in Section 6.3.
Omit wholesale clippy::pedanticThe group enables noisy style and FFI findings. In Clippy 0.1.100, clippy::invalid_upcast_comparisons also wrongly reports (hr as i32) < 0 for hr: u64 as always false. The narrowing cast can wrap (rust-lang/rust-clippy#7648).
Omit clippy::lossy_float_literalClippy 0.1.100 flags 2_147_483_648.0_f32 and suggests 2_147_483_600_f32. The suggested decimal obscures the exact power of two (2^31). Both literals compile to the same f32 bits, 0x4f000000 (rust-lang/rust-clippy#7404).
Omit clippy::collection_is_never_readA collection of Arc handles can keep resources alive across an FFI poll call without any reads. Removing it can free or close the resources during the call.
Omit clippy::use_selfThis nursery lint forces style changes with no safety or correctness benefit.
Omit excessive-nesting-thresholdClippy counts mod, impl, and fn blocks as nesting. Review decision structure with cognitive_complexity instead.
Omit wildcard_enum_match_arm globallyIt also flags _ => on external #[non_exhaustive] enums such as std::io::ErrorKind, suggesting lists of 40 or more variants. Omit wildcards on owned enums and review exhaustiveness there.
Omit panic_in_result_fnIt rejects assert_eq! in #[test] fn() -> Result<...> even with allow-panic-in-tests = true. Use panic with the test profile.
Omit unwrap_in_resultNarrower than unwrap_used: it misses Option::unwrap() inside a Result function. Use unwrap_used and expect_used across production paths.
Omit tests_outside_test_moduleIt flags workspace integration tests under crates/<member>/tests/*.rs despite their dedicated integration-test targets.
Omit rustc's unused_crate_dependencies workspace-wideIt reports unused dependencies across lib, bin, and test targets of the same package. Use cargo::unused_dependencies and optional cargo-shear.
Keep cast_lossless, cast_possible_truncation, cast_possible_wrap, cast_precision_loss, cast_sign_lossPedantic cast checks expose silent range, precision, and sign changes. Use Section 6.3 for proven register, graphics, or pixel conversions.
Omit dead_code_pub_in_binary workspace-wideCargo builds library unit tests as executables. The lint then flags public library items unused by the test harness and breaks warning-denying Clippy, test, and nextest runs. Enable it only in binary crate roots (Section 6.2). See rust-lang/rust#159078.
Omit get_unwrapIts automatic fix changes *v.get(1).unwrap() to v[1], which violates indexing_slicing. unwrap_used already catches the production unwrap. allow-unwrap-in-tests exempts unwrap_used in recognized tests. get_unwrap still fires inside #[test] functions.
Omit error_impl_errorError is an idiomatic public type name, as in std::io::Error, serde_json::Error, and syn::Error.
Omit empty_structs_with_bracketsChanging pub struct Marker {} to pub struct Marker; introduces a public constant in the value namespace and can break consumers.
Omit str_to_stringChoosing between to_string() and to_owned() on str is a style preference with no safety or performance benefit.
Omit clippy::let_underscore_must_useFor Copy results such as write! to a String or OnceLock<usize>::set, this lint rejects let _ =, the form unused_result_ok recommends. unused_must_use, unused_result_ok, unwrap_used, expect_used, and dropping_copy_types flag the usual alternatives. There is no test exemption. Keep let_underscore_lock, clippy::let_underscore_future, and let_underscore_drop for locks, futures, and values with destructors.
Omit clippy::case_sensitive_file_extension_comparisonsClippy checks string literal arguments to .ends_with on &str and String without checking for a path. It skips receivers with a recognized case conversion such as .to_ascii_lowercase(). A dot followed by one to five ASCII letters or digits qualifies if it contains a letter and all letters have the same case. The warning on name.ends_with(".i32") suggests changing the meaning of a case-sensitive LLVM intrinsic name. clippy::suspicious already includes clippy::path_ends_with_ext for Path::ends_with(".ext"). For case-insensitive path checks, compare Path::extension() with eq_ignore_ascii_case.
Scope unreachable_pub and unnameable_types to Section 6.1These lints check the API visible to callers outside a library. Workspace-wide unreachable_pub flags pub helpers inside private modules of publish = false crates even when the crate uses them. dead_code and the binary profile's dead_code_pub_in_binary check for unused items.
Omit clippy::read_zero_byte_vec and clippy::maybe_infinite_iterread_zero_byte_vec can mistake a domain .read(&mut Vec<u8>) that grows the buffer for a zero-byte read. maybe_infinite_iter can miss termination in take_while.
Omit clippy::transmute_undefined_repr and clippy::needless_pass_by_ref_muttransmute_undefined_repr has open false positives. needless_pass_by_ref_mut can miss mutations gated by #[cfg(...)] on another target.
Omit obsolete overridesmodule_name_repetitions moved to restriction in Rust 1.84. Rust 1.91 removed string_to_string. implicit_clone covers the case. str_to_string remains a restriction lint.

5.5 Common native-lint traps and idiomatic resolutions

Link to 5.5 Common native-lint traps and idiomatic resolutions
FindingResolution
unnecessary_safety_comment finds SAFETY: in a doc comment.Document caller obligations under # Safety. Put // SAFETY: immediately at the unsafe operation whose preconditions it establishes.
clippy.toml repeats msrv.For libraries with an MSRV (Section 6.1), set package.rust-version as the single source of truth.
An inner #![allow] passes allow_attributes.Use allow_attributes_without_reason to check for a reason. Reject blanket suppressions in code review (Section 2.4).
cargo::unused_dependencies misses dependencies.It skips [dev-dependencies] and single-target --bin runs. Check the whole workspace. Use cargo-shear for additional coverage.
cargo::unused_dependencies flags a dependency used on only one OS or target.Move the dependency to [target.'cfg(...)'.dependencies] with the condition that gates its use. Do not suppress the lint.
let _ = expr; triggers let_underscore_drop on a value with a destructor.Bind a named guard for the required scope. To discard a non-Copy result, call drop(expr);. This form is required for immediate discard of a result with drop glue. Prefer it for a non-Copy result without a destructor, such as Result<(), UnitError>, even though let _ = expr; also passes.
drop(expr); triggers dropping_copy_types on a Copy result.For an intentional discard, use let _ = expr;. Examples include write! to a String, OnceLock<usize>::set, and AtomicUsize::compare_exchange (Section 3.2).
rustdoc::private_intra_doc_links flags an intentional link from crate-root docs to a private or pub(crate) module in a publish = false crate.Build internal docs with --document-private-items so the link has a target. rustdoc 1.100.1 still warns that public docs would omit it. Scope #![allow(rustdoc::private_intra_doc_links, reason = "...")] to the internal crate or module whose docs need the link. Keep the warning for publishable libraries.
map_err_ignore finds a discarded cause.Store the underlying error as a source or attach context. A new string is not an error chain.
An expectation for clippy::... passes cargo check.cargo check does not run Clippy. Run cargo clippy on the relevant target and features to check the expectation.
cargo-deny rejects a wildcard path dependency.allow-wildcard-paths = true applies to publish = false crates. Publishable crates need an actual version requirement.

5.6 Project-specific architectural bans (clippy.toml)

Link to 5.6 Project-specific architectural bans (clippy.toml)

Use disallowed-methods, disallowed-types, disallowed-macros, or disallowed-fields for a repository-owned boundary. Specify a fully qualified path, give the contract in reason, and name the alternative in replacement. List concrete APIs, not a wildcard such as std::fs::*. Use entries only where the dependency and the replacement are present.

Example additions for a Tokio worker that owns a filesystem interface and requires bounded queues:

disallowed-methods = [
  { path = "std::mem::transmute", reason = "Use the checked representation conversion for this wire type" },
  { path = "std::thread::sleep", reason = "Do not block a worker thread", replacement = "tokio::time::sleep" },
  { path = "tokio::sync::mpsc::unbounded_channel", reason = "The queue must apply backpressure", replacement = "tokio::sync::mpsc::channel" },
  { path = "std::fs::read", reason = "Read through the worker's filesystem interface" },
]
disallowed-types = [
  { path = "tokio::sync::mpsc::UnboundedSender", reason = "Bound producer memory", replacement = "tokio::sync::mpsc::Sender" },
]

6. Composable profiles

Link to 6. Composable profiles

6.1 Library crates

Link to 6.1 Library crates

Use this profile only for publishable or externally consumed libraries. An internal library crate in a private application workspace does not need this profile.

Enable the public API checks in the library crate root (src/lib.rs):

#![warn(
    missing_docs,
    missing_debug_implementations,
    unreachable_pub,
    unnameable_types
)]
#![warn(
    clippy::missing_errors_doc,
    clippy::missing_panics_doc,
    clippy::doc_markdown
)]
#![warn(
    rustdoc::missing_crate_level_docs,
    rustdoc::unescaped_backticks,
    rustdoc::redundant_explicit_links,
    rustdoc::private_doc_tests
)]

Describe failures in terms of what the caller can do. Use typed error enums (thiserror) and minimize dependency features. Never depend on Tokio's "full" feature in a library. For publishable internal dependencies, specify both version and path so the published manifest resolves at the registry.

Build public docs with CARGO_BUILD_WARNINGS=deny cargo doc --workspace --locked --no-deps. Omit --document-private-items so the build checks the docs your users see. rustdoc::private_intra_doc_links flags public links to private items.

rustdoc::private_doc_tests flags fenced Rust examples on pub(crate) and private items even with --document-private-items on rustdoc 1.100.1. Doctests compile as external crates and cannot call private items. Put public usage examples on the public API. Test private behavior in unit tests.

Compile and test on the compiler named in package.rust-version. If the MSRV is older than the quality compiler, use a separate job without the quality job's warning policy.

Use cargo hack --each-feature check for individual features or cargo hack --feature-powerset check for supported combinations. Exclude incompatible sets explicitly. Run --no-dev-deps in isolation because it can temporarily rewrite manifests and change the lockfile. Do not treat that check as proof of a locked build or commit incidental lockfile changes. For public API changes, use cargo-semver-checks >= 0.51.0 against the supported published baseline.

6.2 Application and CLI binaries

Link to 6.2 Application and CLI binaries

Return std::process::ExitCode or anyhow::Result<()> from main to report failures. clippy::exit flags calls to std::process::exit. Keep stdout for the command's result and stderr for diagnostics. Use writeln!(io::stdout().lock(), ...) and handle write failures. An explicit write needs no allow(clippy::print_stdout). Mapping print_stdout or print_stderr to a CLI crate's intentional output boundary is an implementation mapping, not a Section 2 exception. Use tracing for structured diagnostics.

Enable the binary-specific visibility check in the binary crate root (for example, src/main.rs):

#![warn(dead_code_pub_in_binary)]

Mark private crates publish = false, commit Cargo.lock, and use --locked in verification. For a private application workspace, verify the compiler pinned in rust-toolchain.toml. The Section 6.1 MSRV guarantee, older-MSRV job, cargo-hack, cargo-semver-checks, and public API lints are not required. Keep the supported target and feature coverage in Section 4.1.

For an optional check of internal architecture docs, run CARGO_BUILD_WARNINGS=deny cargo doc --workspace --locked --no-deps --document-private-items. This checks links inside private and pub(crate) items. If crate-root docs intentionally link to private modules, scope the rustdoc::private_intra_doc_links allowance as described in Section 5.5.

If a package has both src/lib.rs and a same-named src/main.rs, cargo doc documents only the library by default. Check the binary docs in a separate cargo doc run with --bins or -p <pkg> --bin <name>.

Select release and CI build profiles deliberately. Verify the shipping profile if its behavior differs from the test build.

6.3 Unsafe, FFI, and systems code

Link to 6.3 Unsafe, FFI, and systems code

Use this profile for OS and ABI boundaries, graphics and GPU code, shader or instruction-set (ISA) compilers, and emulators. When only a few crates or modules own unsafe code, keep workspace unsafe_code = "deny" and opt in at those boundaries with an inline reason. When most crates own unsafe OS, ABI, or GPU boundaries, leave workspace unsafe_code unset and put #![deny(unsafe_code)] in the pure-Rust crate roots instead.

Keep these checks in every systems crate:

  • Keep clippy::correctness, unsafe_op_in_unsafe_fn, and clippy::undocumented_unsafe_blocks at deny.
  • Keep clippy::significant_drop_in_scrutinee, clippy::mutex_integer, clippy::large_stack_arrays, and clippy::allow_attributes_without_reason active.
  • Keep rustc's default clashing_extern_declarations lint active. Lint every supported OS target so rustc can detect incompatible duplicate extern "C" declarations in each platform's code.
  • Keep clippy::missing_safety_doc and clippy::non_send_fields_in_send_ty active. If an FFI or GPU handle has a valid Send implementation despite a non-Send field, put #[expect(clippy::non_send_fields_in_send_ty, reason = "...")] on the item and explain why the handle can cross threads safely.
  • Appendix A.1 enables ffi_unwind_calls to identify calls through an ABI that permits unwinding. clippy::default_union_representation flags unions with multiple non-zero-sized fields that lack #[repr(C)]. clippy::same_length_and_capacity flags reuse of the length as the capacity in Vec::from_raw_parts. clippy::uninhabited_references flags references to uninhabited types that code returns or dereferences.

read_volatile and write_volatile on arrays or structs do not guarantee an atomic multi-word transfer. A GPU or another hardware writer can produce or observe a torn entry. Use word-sized volatile accesses when the device protocol defines them. Use supported atomic operations or a synchronization protocol when another writer must see a consistent entry. Volatile access alone does not synchronize threads. Enable clippy::volatile_composites in crates that need to check for composite volatile accesses.

Shader compilers, ISA compilers, and static recompilers may enable clippy::iter_over_hash_type when iteration order determines emitted bytes (Section 3.1).

Document caller preconditions under # Safety for each unsafe fn and unsafe trait. Use // SAFETY: at each unsafe operation to explain how the code satisfies the relevant aliasing, provenance, alignment, lifetime, initialization, ABI, and thread-safety requirements. Prefer checked representation APIs from bytemuck or zerocopy to std::mem::transmute.

Keep indexing_slicing, multiple_unsafe_ops_per_block, cast_possible_truncation, cast_possible_wrap, cast_precision_loss, cast_sign_loss, and cast_ptr_alignment active in parsing and business-logic crates. In bit manipulation, ISA or shader lowering, graphics, and FFI-heavy crates, relax these lints at the item or narrowest genuine boundary when they obscure a hot path or force boilerplate. Explain the index bounds, register width, rounding, or alignment that makes the operation valid.

You may also relax cognitive_complexity for a cohesive lowering pass or emulator dispatcher, and fn_params_excessive_bools for an ABI with fixed flags. Relax exit only where guest process-exit behavior or a signal handler requires it. Relax cfg_not_test only for an explicit hardware or fault-injection test seam, never to hide production code from checks. Give the reason inline as described in Section 2.4.

Run cargo +nightly miri test only for pure-Rust or other Miri-executable unsafe code. Pin a dated nightly if you run Miri in CI. Use native host integration tests for OS, Win32, Mach, Objective-C, and GPU FFI layers that cannot execute under Miri. Test on each shipped operating system and architecture where layout, ABI, or pointer width can differ.

6.4 Async Rust (Tokio and executors)

Link to 6.4 Async Rust (Tokio and executors)
  • Acquire and use a std::sync::Mutex guard or RefCell borrow inside an inner { ... } block that ends before .await. Calling drop(guard) or drop(borrow) in the same lexical scope can still trigger await_holding_lock or await_holding_refcell_ref in Clippy 0.1.100. Appendix A.1 enables both checks.
  • Do not perform blocking input, output, sleep, or process waits on executor worker threads. Use async APIs or a blocking worker and ban the known synchronous entry points under Section 5.6.
  • Give spawned tasks an owner. Use JoinSet to collect outcomes and tokio_util::sync::CancellationToken (from tokio-util) for cooperative shutdown rather than detaching a tokio::spawn handle. Prefer bounded channels to unbounded_channel. Define what the producer does under backpressure.
  • Audit both cancel safety (dropping and retrying the future) and cancel correctness (the system's state after cancellation) in tokio::select! and timeout. Reserve channel capacity before moving a message, and pin a future across loop iterations when progress must survive selection. Never leave half-finished shared state across .await under a lock.
  • Specify whether futures returned by public trait methods must be Send. Address async_fn_in_trait with explicit future bounds when callers need to spawn the result. Inspect captures and data held across awaits before boxing a large_futures finding.
  • Use #[tokio::test(start_paused = true)] for timer-driven tests. Enable test-util in [dev-dependencies] only. Advance the clock or synchronize on the actual event instead of sleeping.

6.5 no_std and embedded targets

Link to 6.5 no_std and embedded targets

Declare the environment and its checks in the crate root:

#![no_std]
#![warn(
    clippy::std_instead_of_core,
    clippy::std_instead_of_alloc,
    clippy::alloc_instead_of_core
)]

Check the actual --target and feature set without host-only dependencies. On bare-metal targets that lack the test crate, such as thumbv7em-none-eabihf, --all-targets attempts to build test targets and fails with E0463. Run CARGO_BUILD_WARNINGS=deny cargo clippy --target <triple> --lib --bins --locked for the embedded libraries and binaries. To check one package, add -p <crate>. Select only the target kinds the package defines.

Set test = false and bench = false in each [[bin]] that defines a bare-metal #[panic_handler]. Otherwise host --workspace --all-targets checks can link the test harness and the binary's panic handler together, which triggers E0152. State which binary supplies the panic handler and whether allocation is available. Run pure-logic unit tests on the host. Verify device startup, peripherals, panic behavior, and timing on the supported hardware.

7. Formatting, dependencies, and artifacts

Link to 7. Formatting, dependencies, and artifacts

7.1 Formatter ownership (rustfmt)

Link to 7.1 Formatter ownership (rustfmt)

Let rustfmt own Rust layout. Set edition = "2024" in rustfmt.toml to select the 2024 parser and style edition. Bare rustfmt defaults to Edition 2015 and rejects Edition 2024 let-chains. Setting only style_edition = "2024" does not change the parser. Omit use_try_shorthand, which targets the obsolete try!() macro.

Use stable options from the installed formatter (rustfmt --help=config). hex_literal_case stabilized with Rust 1.99. ignore, imports_granularity, group_imports, wrap_comments, and format_code_in_doc_comments remain nightly-only. Do not depend on CLI --config quirks to enable them.

Use #[rustfmt::skip] on the specific generated or byte-sensitive item that must retain its layout. If the repository formats TOML with Taplo or sorts manifests with cargo-sort, assign one owner to each transformation so the tools do not undo one another.

7.2 Dependency, advisory, and supply-chain hygiene

Link to 7.2 Dependency, advisory, and supply-chain hygiene

Use cargo-deny 0.22.2 or later with the current schema in Appendix A.5. Omit the legacy version = 2 marker.

TableRequired policy
[advisories]Check unmaintained = "workspace" and unsound = "all". Review yanked packages. Scope each necessary advisory ignore to { id, reason, expiry }. Remove it when fixed or expired.
[bans]Review multiple-versions = "warn" and deny wildcards. allow-wildcard-paths = true permits private path dependencies for publish = false crates. Use a version and path for publishable internal dependencies.
[licenses]Set an explicit SPDX allowlist that covers the workspace's own licenses and the licenses in the resolved dependency graph that the repository's policy permits.
[sources]Deny unknown-registry and unknown-git. Name authorized sources explicitly.

Local-only repositories may use --offline with a refreshed, cached advisory database. Record the revision or refresh date. An offline scan cannot detect newer advisories. Use cargo-audit for a lockfile-only scan or to scan shipped binaries built with cargo-auditable. To set a minimum age for new registry releases in Cargo 1.100, use registry.global-min-publish-age. Override it for one registry with registries.<name>.min-publish-age. A cooldown does not replace advisory checks.

Run cargo::unused_dependencies and cargo::unused_workspace_dependencies. Add cargo-shear 1.14.1 or later for development dependencies that Cargo does not check. Inspect target, feature, build, and proc-macro use before removing a dependency. Use cargo-vet only when a team owns the actual audit reviews. For vendored or [patch.crates-io] dependencies, record upstream origin, exact revision, checksums, local changes, and removal conditions. Verify the checksum and test the resolved copy, not a registry substitute.

Before adding a dependency that you expect to be pure Rust, inspect its resolved graph with cargo tree or cargo deny. Look for transitive -sys packages that use cc, cmake, pkg-config, or bindgen. They can require a C or C++ toolchain and target headers even if the direct dependency contains only Rust. A host-only toolchain cannot check those targets (Section 4.1).

7.3 Generated code and build scripts

Link to 7.3 Generated code and build scripts

Name the generator, its inputs and version, the output owner, and the command that reproduces checked-in output. Verify freshness without rewriting the working tree: generate into a temporary directory and compare, or use the generator's check mode. Compile and exercise the generated code through its consumer.

Make build.rs deterministic for its declared inputs. Emit cargo::rerun-if-changed=<path> for each input file or directory, including paths in other crates. Emit cargo::rerun-if-env-changed=<VAR> for each external environment variable the script reads. Cargo 1.77 stabilized the double-colon cargo:: syntax in place of the legacy cargo: form.

Emitting any rerun-if-* directive turns off Cargo's default scan of the package directory. If you omit an input, a change to that file, cross-crate path, or environment variable can leave $OUT_DIR outputs stale. cargo clippy --all-targets checks build.rs under the package's [lints] table. Keep network calls out of the build. Fetch or vendor external inputs through the repository's dependency process.

8. Verification and enforcement integrity

Link to 8. Verification and enforcement integrity

8.1 Verify the repository's checks

Link to 8.1 Verify the repository's checks

Run the real acceptance commands. Do not write tests that prove rustc rejects invalid code, Clippy detects one of its stock findings, or rustfmt changes whitespace. Do not parse Makefile recipes to check whether a flag appears: that cannot show whether the gate runs on a workspace member or preserves a failure.

Test behavior the repository owns. For a generator, show that stale output fails the freshness check. For an architecture boundary, test the domain contract a violation would break. A passing gate must include the affected code and propagate its exit status.

8.2 Testing standards and runners

Link to 8.2 Testing standards and runners

Use CARGO_BUILD_WARNINGS=deny cargo test --workspace --locked by default. Test returned values, error variants, cause chains, edge inputs, and observable state changes. A suite of happy paths or assert!(res.is_ok()) does not establish the operation's contract.

For process-per-test isolation, leak detection (leak-timeout), slow-test termination (slow-timeout), and JUnit output, use cargo-nextest 0.9.152 or later (security floor 0.9.150). Always pair nextest with CARGO_BUILD_WARNINGS=deny cargo test --workspace --locked --doc. Nextest does not run doctests.

cargo test --workspace -- --skip <name> passes the trailing libtest arguments to every test binary. A custom harness = false target that does not accept --skip fails. For workspace runs with nextest-compatible custom harnesses, filter in the runner instead: cargo nextest run -E 'not test(name)'.

Edition 2024 makes std::env::set_var and std::env::remove_var unsafe. Inject configuration or set the environment of a child process instead of mutating shared process state. Synchronize tests on observable events rather than sleeps. Use proptest for generative invariants, insta for reviewed snapshots, trybuild for compile-time contracts, cargo-llvm-cov for measured coverage, or cargo-mutants to evaluate assertion strength when the result answers a concrete question.

8.3 Evidence quality

Link to 8.3 Evidence quality

Record the commit SHA or PR, exact toolchain versions, target triples, feature sets, commands, and exit codes. Separate evidence of compilation from unit and integration test execution, doctests, Miri, and live platform or hardware checks. A host check cannot verify a device interrupt handler. A Miri pass cannot verify a native library's ABI.

Use hosted CI or a documented local-only gate. In either case retain the actual result, identify untested combinations, and do not claim a broader scope than the commands covered.

9. Adoption, upgrades, and escalation

Link to 9. Adoption, upgrades, and escalation

9.1 Inspect the target repository first

Link to 9.1 Inspect the target repository first

Record the starting Git revision and preserve unrelated uncommitted work. Read repository instructions, manifests, toolchain and formatter configuration, source attributes, lockfile, CI jobs, and release commands. Use Cargo metadata to enumerate members and targets. Identify supported features, platforms, consumers, and profiles. Check the declared MSRV for libraries covered by Section 6.1. Run the existing gate before changing it so you can distinguish baseline failures from regressions.

9.2 First-time adoption

Link to 9.2 First-time adoption
  1. Identify scope and applicable profiles. Preserve stricter checks that already protect a contract.
  2. Select current quality tools. Apply Appendix A, verify inheritance member by member, and map checks to supported feature sets and targets.
  3. Fix findings in the owning code. Preserve errors, drop order, public API, and actual test assertions. Use Section 2 only for demonstrated exceptions.
  4. Run Section 10.1 and the profile-specific checks. Record the commands and results, including separate MSRV, platform, and doctest results where applicable. Use Appendix B if a repository verification record would help future maintainers.

9.3 Upgrading an existing Rust repository (delta workflow)

Link to 9.3 Upgrading an existing Rust repository (delta workflow)

Compare the adopted baseline and tool versions with the new requirements. Identify changed lint groups, moved or removed lints, stable options, thresholds, profile coverage, and native features that replace local workarounds. Apply that delta without overwriting local policy with a fresh starter file. Inventory repository-owned policy tests, generator freshness checks, and CI wiring before removing obsolete suites. Keep checks that protect repository behavior. Retire stale vendored copies of the standard and update their callers to use the canonical URL. Re-evaluate exceptions against the new toolchain, remove stale suppressions, and run the acceptance matrix on the resulting revision.

9.4 Raising regressions to the driving user

Link to 9.4 Raising regressions to the driving user

If a mandate breaks behavior, degrades safety, conflicts with current upstream behavior, or forces a harmful workaround, report it directly to the user driving the work before relaxing enforcement. Provide the exact command, tool versions, diagnostic, affected contract, and a realistic compliant alternative. Show the observed difference and the narrowest proposed resolution. A note buried in a verification record is not escalation.

9.5 Preserving and surfacing stronger repository conventions

Link to 9.5 Preserving and surfacing stronger repository conventions

Retain stronger checks with evidence that they prevent a real failure without forcing worse code. Check for contradictions before composing them: do not combine clippy::implicit_return with clippy::needless_return, or mod_module_files with self_named_module_files. Show the driving user the rule, its scope, and a concrete benefit so it can be considered for upstream adoption. Do not silently replace it with the weaker starter setting.

10. Acceptance and maintenance

Link to 10. Acceptance and maintenance

10.1 Required commands and CI

Link to 10.1 Required commands and CI

Run the following baseline commands from the workspace root. Run the baseline Clippy command on every supported OS target that ships std and test, including both Windows and macOS if you ship on both. --all-targets alone does not reach code gated to another OS, including dead code, undocumented unsafe blocks, and incompatible extern declarations. Add the supported feature combinations and other checks required by Section 4.1 and your profiles. Keep the commands runnable locally even when hosted CI also runs them.

cargo fmt --all -- --check
CARGO_BUILD_WARNINGS=deny cargo clippy --workspace --all-targets --locked
CARGO_BUILD_WARNINGS=deny cargo test --workspace --locked
cargo deny --locked --workspace check

On a bare-metal triple without test, replace --workspace --all-targets with the embedded target selection: CARGO_BUILD_WARNINGS=deny cargo clippy --target <triple> --lib --bins --locked. Select packages with -p <crate> as needed. Disable test and bench harnesses on binaries with a #[panic_handler] and run pure-logic tests on the host (Section 6.5).

For publishable or externally consumed libraries (Section 6.1), also require CARGO_BUILD_WARNINGS=deny cargo doc --workspace --locked --no-deps. For publish = false private workspaces, the internal docs check is optional: CARGO_BUILD_WARNINGS=deny cargo doc --workspace --locked --no-deps --document-private-items. Scope #![allow(rustdoc::private_intra_doc_links, reason = "...")] to the crate or module whose docs intentionally link to private items (Section 5.5).

If src/lib.rs and src/main.rs produce targets with the same name, the default docs command checks only the library. For binary docs, repeat the command separately with --bins, or select -p <pkg> --bin <name> in place of --workspace.

When using nextest, replace the test line with both commands below. --profile ci requires [profile.ci] in .config/nextest.toml (Appendix A.6). Without that profile nextest exits with code 96. Omit --profile ci to use the default profile. Keep the separate doctest command.

CARGO_BUILD_WARNINGS=deny cargo nextest run --workspace --locked --profile ci --no-fail-fast
CARGO_BUILD_WARNINGS=deny cargo test --workspace --locked --doc

For compact agent triage, run CARGO_BUILD_WARNINGS=deny cargo clippy --workspace --all-targets --locked --message-format=short. A repository without hosted CI may run the same gate locally. When offline, use cargo deny --offline --locked --workspace check with a refreshed advisory database.

Measure before optimizing CI. In a disposable job using sccache, evaluate CARGO_INCREMENTAL=0 against actual cache hits and elapsed time. Rust 1.90 and later already default to LLD on x86_64-unknown-linux-gnu. Evaluate mold only if linking is a measured bottleneck.

10.2 Completion criteria

Link to 10.2 Completion criteria

Acceptance requires passing commands for the declared matrix and no unexplained dependency findings. In the quality job, require zero local-package compiler, Clippy, rustdoc, and [lints.cargo] manifest lint warnings covered by Section 5.1. A successful exit does not establish that build scripts emitted no cargo::warning= messages or that doctest bodies compiled without warnings. Keep the warning policy for older MSRV builds separate. Verify the formatted tree, inherited settings, applicable profiles, generated freshness, and actual behavior at the supported boundaries. Report the command outcomes and state what ran on each target. Keep the reasons for source-level exceptions next to the code.

10.3 Ongoing maintenance

Link to 10.3 Ongoing maintenance

Point AGENTS.md or CLAUDE.md to the canonical standard at https://fitchhub.com/standards/rust.md and name the repository's acceptance command. Link the repository verification record if you keep one. Use the pinned release URL in that record to identify the adopted version. When upgrading, read the release notes, review effective lints and schemas, and update toolchain pins. Run the quality job and any applicable MSRV job. Remove workarounds that no longer apply.

Appendix A: Starter configurations

Link to Appendix A: Starter configurations

A.1 Workspace Cargo.toml

Link to A.1 Workspace Cargo.toml
[workspace]
resolver = "3"
members = ["crates/*"]

[workspace.package]
version = "0.1.0"
edition = "2024"
# Set only for publishable or MSRV-tested libraries (Section 6.1).
# rust-version = "1.100"
license = "MIT OR Apache-2.0"
publish = false

[workspace.lints.cargo]
missing_lints_inheritance = "warn"
unused_dependencies = "warn"
unused_workspace_dependencies = "warn"
unused_workspace_package_fields = "warn"
blanket_hint_mostly_unused = "warn"
redundant_homepage = "warn"
unknown_lints = "warn"

[workspace.lints.rust]
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "deny"
unused_must_use = "deny"
non_ascii_idents = "deny"
unfulfilled_lint_expectations = "warn"
ffi_unwind_calls = "warn"
redundant_imports = "warn"
redundant_lifetimes = "warn"
unused_lifetimes = "warn"
unused_macro_rules = "warn"
let_underscore_drop = "warn"
unit_bindings = "warn"
ambiguous_negative_literals = "warn"
closure_returning_async_block = "warn"
deref_into_dyn_supertrait = "warn"
macro_use_extern_crate = "warn"
meta_variable_misuse = "warn"

[workspace.lints.rustdoc]
broken_intra_doc_links = "deny"

[workspace.lints.clippy]
correctness = { level = "deny", priority = -1 }
suspicious = { level = "warn", priority = -1 }
complexity = { level = "warn", priority = -1 }
perf = { level = "warn", priority = -1 }
style = { level = "warn", priority = -1 }

# Individual pedantic lints (never enable pedantic wholesale)
cast_lossless = "warn"
cast_possible_truncation = "warn"
cast_possible_wrap = "warn"
cast_precision_loss = "warn"
cast_ptr_alignment = "warn"
cast_sign_loss = "warn"
checked_conversions = "warn"
cloned_instead_of_copied = "warn"
copy_iterator = "warn"
doc_link_with_quotes = "warn"
expl_impl_clone_on_copy = "warn"
filter_map_next = "warn"
flat_map_option = "warn"
fn_params_excessive_bools = "warn"
format_collect = "warn"
format_push_string = "warn"
ignore_without_reason = "warn"
implicit_clone = "warn"
inefficient_to_string = "warn"
iter_filter_is_ok = "warn"
iter_filter_is_some = "warn"
iter_not_returning_iterator = "warn"
large_futures = "warn"
large_stack_arrays = "warn"
large_types_passed_by_value = "warn"
macro_use_imports = "warn"
manual_assert = "warn"
manual_instant_elapsed = "warn"
manual_is_power_of_two = "warn"
manual_is_variant_and = "warn"
manual_let_else = "warn"
match_wild_err_arm = "warn"
mismatching_type_param_order = "warn"
missing_fields_in_debug = "warn"
mut_mut = "warn"
needless_pass_by_value = "warn"
no_effect_underscore_binding = "warn"
no_mangle_with_rust_abi = "warn"
non_std_lazy_statics = "warn"
nonminimal_bool = "warn"
overly_complex_bool_expr = "warn"
ref_option = "warn"
same_functions_in_if_condition = "warn"
same_length_and_capacity = "warn"
should_panic_without_expect = "warn"
transmute_ptr_to_ptr = "warn"
unchecked_time_subtraction = "warn"
unicode_not_nfc = "warn"
unsafe_derive_deserialize = "warn"
unused_async = "warn"
zero_sized_map_values = "warn"

# Individual restriction lints (never enable restriction wholesale)
allow_attributes = "warn"
allow_attributes_without_reason = "warn"
assertions_on_result_states = "warn"
cfg_not_test = "warn"
clone_on_ref_ptr = "warn"
cognitive_complexity = "warn"
dbg_macro = "warn"
default_union_representation = "warn"
empty_drop = "warn"
exit = "warn"
expect_used = "warn"
fn_to_numeric_cast_any = "warn"
indexing_slicing = "warn"
infinite_loop = "warn"
map_err_ignore = "warn"
mem_forget = "warn"
multiple_unsafe_ops_per_block = "warn"
mutex_atomic = "warn"
mutex_integer = "warn"
panic = "warn"
print_stderr = "warn"
print_stdout = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
rest_pat_in_fully_bound_structs = "warn"
same_name_method = "warn"
string_slice = "warn"
suspicious_xor_used_as_pow = "warn"
todo = "warn"
undocumented_unsafe_blocks = "deny"
unimplemented = "warn"
unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn"
unused_result_ok = "warn"
unwrap_used = "warn"
verbose_file_reads = "warn"

# Individual nursery lints (never enable nursery wholesale)
debug_assert_with_mut_call = "warn"
fallible_impl_from = "warn"
literal_string_with_formatting_args = "warn"
non_send_fields_in_send_ty = "warn"
path_buf_push_overwrite = "warn"
redundant_clone = "warn"
significant_drop_in_scrutinee = "warn"
uninhabited_references = "warn"
unused_peekable = "warn"

For a single package without [workspace], move [workspace.lints.*] to [lints.*]. Drop the workspace-only Cargo lints missing_lints_inheritance, unused_workspace_dependencies, and unused_workspace_package_fields.

A.2 Member crate Cargo.toml

Link to A.2 Member crate Cargo.toml
[package]
name = "example-crate"
version.workspace = true
edition.workspace = true
# Inherit rust-version only if the workspace sets the library's MSRV.
# rust-version.workspace = true
license.workspace = true
publish.workspace = true

[lints]
workspace = true
allow-dbg-in-tests = false
allow-expect-in-tests = true
allow-indexing-slicing-in-tests = true
allow-panic-in-tests = true
allow-print-in-tests = true
allow-unwrap-in-tests = true
cognitive-complexity-threshold = 20
max-fn-params-bools = 1

A.4 rustfmt.toml

Link to A.4 rustfmt.toml
edition = "2024"
max_width = 100
newline_style = "Unix"
use_field_init_shorthand = true
[advisories]
yanked = "warn"
unmaintained = "workspace"
unsound = "all"

[bans]
multiple-versions = "warn"
wildcards = "deny"
allow-wildcard-paths = true

[licenses]
# cargo-deny checks workspace crates as well as dependencies.
# Include your workspace license (for example, GPL-3.0-or-later).
# Include approved licenses present in Cargo.lock dependencies, such as
# Unicode-3.0, BSD-3-Clause, or Zlib. Do not add unused entries.
allow = ["Apache-2.0", "MIT"]

[sources]
unknown-registry = "deny"
unknown-git = "deny"

Adjust [licenses].allow to the repository's policy and locked dependency graph. cargo-deny warns about unused entries. allow-wildcard-paths = true applies only to publish = false crates.

A.6 Optional .config/nextest.toml

Link to A.6 Optional .config/nextest.toml
# Enforce the 0.9.150 security floor. Install >= 0.9.152 for Section 5.1.
nextest-version = "0.9.150"

[profile.ci]
failure-output = "immediate"
leak-timeout = { period = "100ms", result = "fail" }
slow-timeout = { period = "30s", terminate-after = 4 }

[profile.ci.junit]
path = "junit.xml"

Appendix B: Repository verification record

Link to Appendix B: Repository verification record

Keep an optional short record if it helps maintainers rerun verification:

  • Scope and profiles: Workspace members, applicable profiles, and the adopted version (https://fitchhub.com/standards/rust/v1.2.md).
  • Target and feature matrix: Supported target triples and feature combinations, with toolchain versions and library MSRV where applicable.
  • Acceptance commands: What to run for each combination. Link results that distinguish compilation from execution.
  • Workspace-level adjustments: Notable departures from the starter configuration and why they apply. Keep item-level reasons in the source.

Appendix C: Changelog

Link to Appendix C: Changelog

v1.2 (1 December 2026)

Link to v1.2 (1 December 2026)
  • Expand the pedantic selection to 51 lints. Add checks for union layout, raw allocation capacity, method names, mistaken exponentiation, format strings, path replacement, and uninhabited references.
  • Permit explicit discard of a Copy result when the caller does not need the outcome. Omit string-suffix checks that mistake domain names for file paths. Require deterministic iteration when order affects emitted bytes or cache keys.
  • Scope public visibility checks and rustdoc::private_doc_tests to library crate roots. Deny broken documentation links locally. Distinguish required public documentation checks from optional checks of private items and same-named binaries.
  • Use native runners for each supported OS. Cover excluded packages, retire unused targets, and check shared dependency declarations. Document how a stale MSRV suppresses Clippy findings and how environment flags override target settings.
  • Distinguish local-package lint warnings from build script messages and warnings in doctest bodies. Check bare-metal libraries and binaries without building a target test harness. Specify the Cargo keys for minimum registry release ages.
  • Declare build script file and environment inputs. Check transitive native build requirements, filter tests without passing libtest arguments to custom runners, and use device-appropriate access for shared hardware state.

v1.1 (30 November 2026)

Link to v1.1 (30 November 2026)
  • Keep the native Edition 2024 checks and remove advice tied to individual Rust 1.100 API additions. Use inline lint reasons and native checks instead of exception IDs or a source parser. Make the repository verification record optional.
  • Require Clippy on every supported OS. Reserve MSRV promises, older compiler jobs, cargo-hack, cargo-semver-checks, public API lints, and a required docs build for publishable or externally consumed libraries.
  • Replace wholesale pedantic with 34 explicit lints. Omit invalid_upcast_comparisons, lossy_float_literal, collection_is_never_read, and use_self. Remove the nesting threshold and document how to stack test attributes for OS-specific helpers.
  • Move target-only dependencies to target-specific manifest tables. Calibrate unsafe, cast, indexing, and other lint checks for systems, FFI, graphics, shader and ISA compilers, and emulators while preserving safety checks. Use native integration tests for FFI code that Miri cannot run.
  • Remove the legacy use_try_shorthand option. Document why bare rustfmt needs an explicit edition for let-chains and why cargo-deny needs the workspace license and approved locked dependency licenses.

v1.0 (30 November 2026)

Link to v1.0 (30 November 2026)

Initial Edition 2024 standard. Defines workspace lint inheritance, warning enforcement, structural thresholds, exception evidence, and dependency policy. Adds composable library, binary, unsafe, async, and embedded profiles with acceptance commands and starter manifests.

Primary references for the 1 December 2026 baseline: