Starter Template¶
Rust¶
Cargo.toml
# Starter template
[package]
edition = "2024"
rust-version = "1.100"
[dependencies]
anyhow = "1"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tracing = "0.1"
[dev-dependencies]
[profile.release]
codegen-units = 1
lto = "fat"
overflow-checks = true
[lints.rust]
non_ascii_idents = "forbid"
unsafe_code = "forbid"
future_incompatible = { level = "deny", priority = -1 }
let_underscore = { level = "deny", priority = -1 }
nonstandard_style = { level = "deny", priority = -1 }
rust_2018_idioms = { level = "deny", priority = -1 }
meta_variable_misuse = "warn"
missing_debug_implementations = "warn"
missing_docs = "warn"
redundant_lifetimes = "warn"
single_use_lifetimes = "warn"
unit_bindings = "warn"
unnameable_types = "warn"
unreachable_pub = "warn"
unused_import_braces = "warn"
unused_lifetimes = "warn"
unused_macro_rules = "warn"
unused_must_use = "deny"
unused_qualifications = "warn"
[lints.rustdoc]
bare_urls = "warn"
broken_intra_doc_links = "deny"
invalid_html_tags = "warn"
missing_crate_level_docs = "warn"
private_intra_doc_links = "deny"
redundant_explicit_links = "warn"
unescaped_backticks = "warn"
[lints.clippy]
all = { level = "deny", priority = -1 }
cargo = { level = "warn", priority = -1 }
nursery = { level = "warn", priority = -1 }
pedantic = { level = "deny", priority = -1 }
absolute_paths = "warn"
allow_attributes = "deny"
allow_attributes_without_reason = "deny"
arithmetic_side_effects = "deny"
as_conversions = "deny"
cargo_common_metadata = "allow"
clone_on_ref_ptr = "warn"
dbg_macro = "deny"
empty_structs_with_brackets = "warn"
error_impl_error = "warn"
exit = "deny"
expect_used = "deny"
exhaustive_enums = "warn"
exhaustive_structs = "warn"
format_push_string = "warn"
if_then_some_else_none = "warn"
indexing_slicing = "deny"
infinite_loop = "warn"
iter_over_hash_type = "warn"
let_underscore_must_use = "deny"
lossy_float_literal = "deny"
map_err_ignore = "warn"
mem_forget = "deny"
missing_assert_message = "warn"
# Enforce foo/mod.rs + foo/tests.rs layout
mod_module_files = "warn"
module_name_repetitions = "allow"
multiple_inherent_impl = "warn"
non_ascii_literal = "warn"
panic = "deny"
panic_in_result_fn = "deny"
print_stderr = "deny"
print_stdout = "deny"
rc_buffer = "warn"
rc_mutex = "warn"
same_name_method = "warn"
semicolon_inside_block = "warn"
str_to_string = "warn"
string_add = "warn"
string_slice = "warn"
tests_outside_test_module = "warn"
todo = "deny"
try_err = "warn"
undocumented_unsafe_blocks = "deny"
unimplemented = "deny"
unreachable = "warn"
unused_result_ok = "warn"
unused_trait_names = "warn"
unwrap_used = "deny"
verbose_file_reads = "warn"
# Nursery and pedantic lints that add noise
disallowed_methods = "deny"
missing_const_for_fn = "allow"
option_if_let_else = "allow"
redundant_pub_crate = "allow"
significant_drop_tightening = "allow"
Clippy.toml
allow-dbg-in-tests = true
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
# The ".." keeps clippy's built-in list; add your own proper nouns **BEFORE** it
doc-valid-idents = [".."]
# List tolerated duplicate dependency versions here so multiple_crate_versions stays on
allowed-duplicate-crates = []
disallowed-methods = [
{ path = "std::panic::catch_unwind", reason = "forbidden by project guidelines, see the catch_unwind rule" },
{ path = "std::sync::PoisonError::into_inner", reason = "do not recover poisoned mutex contents" },
{ path = "std::sync::PoisonError::get_ref", reason = "do not recover poisoned mutex contents" },
{ path = "std::sync::PoisonError::get_mut", reason = "do not recover poisoned mutex contents" },
]
### Rust Validation Loop
Rust implementation changes MUST pass all of the following checks before completion:
- [ ] `cargo fmt --all -- --check`
- [ ] `cargo clippy --all-targets --all-features -- -D warnings`
- [ ] `cargo test --all-features`
### Running Sentence
Never break a running sentence or paragraph into newlines to honor a line length limit. This is a global requirement for **EVERYTHING** including commit description, code comments, documentation, and even harness output.
### Code Grammar
- Use active voice.
- Be concise.
- Never leave a code comment which refers to a previous buggy state.
### Writing Guidelines
- All Markdown heading levels MUST use Title Case in Chicago/AP style. Headings MUST NOT contain ordering numbers.
- Authored documentation and comments SHOULD use ASCII characters for portable rendering and MUST NOT use the Unicode em dash. Sentences needing emphasis or interruption MUST use commas, colons, semicolons, parentheses, or be rewritten. Literal non-ASCII data MAY be retained when necessary to document or test its handling.
- Markdown sections MUST have a single blank line between blocks and MUST NOT contain trailing whitespace.
### Rust Style Guide
The following requirements apply to Rust projects. A MUST is mandatory. A SHOULD is the default and requires a concrete readability, maintenance, correctness, or performance justification when an exception is used.
#### Modules and File Layout
- A module named `foo` MUST use `foo/mod.rs` with unit tests in `foo/tests.rs` when tests are needed. This layout takes precedence over examples using a single `foo.rs`. Binary and library entrypoints follow Rust's entrypoint conventions.
- Source files SHOULD remain below 300 lines and have dedicated responsibilities so their purpose remains easy to review. The limit is a preference, not a hard rule. Unit test files are exempt.
- A leaf module with a primary user-defined item MUST be named after that item in snake_case. Leaf modules without a primary abstraction MAY use a descriptive responsibility name. Unit test and cross-language binding submodules do not prevent a module from being treated as a leaf.
- Non-leaf modules MUST contain only module declarations and re-exports, except for a small amount of core integration code when separating it would make the code harder to understand. Substantial API implementation MUST reside in leaf modules.
#### Formatting, Imports, and Names
- Code MUST use `cargo fmt`, four-space indentation, snake_case functions and variables, CamelCase types and traits, and SCREAMING_CASE constants. Method naming MUST follow Rust standard library conventions, including the receiver and ownership distinctions of `as_`, `to_`, and `into_`.
- Imports MUST be grouped as standard library, external dependencies, and internal modules, with alphabetical ordering within each group. A `use` statement MUST import items from one module, with no nested module paths inside its brace group.
- Traits SHOULD be imported locally inside functions unless their methods are used extensively throughout the file, keeping dependencies near their use.
- Calls to top-level functions from other modules or crates MUST be qualified with the module name. Types and traits MUST normally be imported and used unqualified. Ambiguous names, large groups of related types, macros, generated code, and unusually large dependency sets MAY use qualified paths or import aliases where clearer.
- Lifetimes MUST use descriptive names when they describe an enduring role. Anonymous lifetimes and up to two single-character lifetimes MAY be used for simple local relationships, higher-ranked bounds, or highly generic abstractions. Generic parameter names MUST be short and related to what they represent.
- Constructors MUST use `new()` or `new_with_foo()`. Fallible constructors MUST use `try_new()`. Value conversions MUST use `from_foo()` with an associated `From` implementation when the conversion contract fits.
- Names MUST NOT use unfamiliar abbreviations or abbreviate by deleting letters. Common, recognizable abbreviations MAY be used when a reviewer can reasonably expect them to be understood.
#### Ownership and Borrowing
- Unique ownership and borrowing SHOULD be preferred over `Rc` and `Arc` to avoid runtime overhead and unnecessary shared ownership. Shared ownership MAY be used when the alternative would be unreasonably complex to write, understand, or maintain, with the tradeoff addressed in review.
- Borrowing SHOULD be preferred over deep copying. `.clone()` MUST represent a needed copy rather than substitute for a tractable borrowing design. A copy MAY simplify excessively complex borrowing when its performance cost is acceptable. Cloning `Rc` or `Arc` pointers is normal reference-counted ownership and is not a deep copy.
- Immutable parameters SHOULD borrow the data itself using `&T`, `&[T]`, `&str`, or `Option<&T>` rather than `&Box<T>`, `&Vec<T>`, `&String`, or `&Option<T>`. Non-linear text containers MAY expose their native borrowed representation.
#### Function Inputs and Outputs
- Reusable library APIs SHOULD return iterators when callers benefit from choosing their own collection or processing strategy. Returning `Vec<T>` is acceptable when callers need an owned collection, random indexing, the implementation naturally builds or already holds a vector, or application simplicity outweighs unused flexibility.
- Reusable library APIs that only iterate their input SHOULD accept iterators or `impl IntoIterator`. Application code MAY accept slices when simpler and when flexibility or performance does not justify a generic API.
- Library APIs MAY accept `impl Into<T>` when call-site ergonomics outweigh code-size and complexity costs. Application APIs SHOULD use concrete inputs because generic conversion seldom provides enough benefit there.
- APIs SHOULD use an enum instead of a boolean when a boolean's purpose is not obvious. A boolean MAY be used with a clear inline argument comment.
- Defined errors MUST use `thiserror`, and propagated application errors MUST use `anyhow`. APIs MUST use `Option` for simple failures whose causes need no explanation, `Result` for recoverable failures needing context, and reserve panics for bugs or violated invariants. External I/O failures MUST NOT be reported as invariant panics.
- `unwrap()` and `expect()` outside tests MUST be minimized. Pattern matching MUST replace check-then-unwrap code when it can prove the condition. If an invariant panic is necessary, `expect()` MUST be preferred over `unwrap()` and explain the invariant. Tests MAY panic for assertions. Developer-facing non-fatal invariant panics require a documented recovery contract.
#### Types and Traits
- Newtypes MUST be preferred to aliases when a type has distinct semantics, its own API, a need to change representation independently, or a risk of mixing otherwise identical underlying values.
- Named fields SHOULD be preferred over tuples and multi-field tuple structs for clarity. Single-field newtypes and very local unambiguous tuples are acceptable.
- Application code MUST add trait implementations when needed. Reusable low-level library code SHOULD anticipate demonstrated user needs. Traits MUST NOT be introduced merely to organize code.
- A method matching a standard library trait's contract MUST implement that trait. An accompanying inherent method MAY improve discoverability. Derivable implementations MUST use `#[derive()]` rather than equivalent manual implementations.
- Library function parameters SHOULD use generics or `impl Trait` rather than `dyn Trait` for optimization and simpler dispatch. Dynamic dispatch MAY be used when code size or a concrete runtime need justifies it.
- A custom trait MUST enable generic programming, an `impl Trait` or `dyn Trait` contract, or an extension of a foreign type. Other functionality MUST use inherent implementations. Extension trait names MUST end in `Ext` and SHOULD be owned by the team owning the extended type, except for widely useful foundational extensions.
- Public-field types SHOULD implement standard traits supported by all fields. Error types and other types SHOULD implement `Copy` when it is reasonably clear they can remain `Copy`. Types SHOULD implement `Clone` unless they represent an external resource. These defaults reduce ownership friction without misrepresenting resource semantics.
- Types with `new()` or a natural default state SHOULD implement `Default`. Structs with all-public fields serving as bags of options MUST implement `Default` so callers can use struct update syntax.
- Types intended for equality MUST implement `PartialEq`; `Eq` MAY be implemented when reflexivity holds. Types intended for ordering MUST implement `PartialOrd`; `Ord` MAY be implemented when ordering is total. Likely map keys SHOULD implement `Hash` and `Eq`, plus ordering traits when a clear total order exists.
- Important `From` implementations that provide a primary construction path MUST have a corresponding explicit inherent constructor.
#### Concurrency and Macros
- Asynchronous Rust code MUST use Tokio and `async`/`await`.
- Code MUST NOT recover the contents of a poisoned mutex by reaching inside it.
- Regular functions, types, objects, traits, and modules SHOULD be preferred to macros and code generation for tool support and readability. If needed, prefer `macro_rules!`, then other code generation, then procedural macros. Each macro or generation choice MUST weigh benefits against IDE support, searchability, and the cost of a local language dialect.
#### Documentation and Safety
- Public APIs MUST have `///` documentation, and module or library documentation MUST use `//!`. Documentation MUST explain contracts, invariants, and relevant behavior without teaching language basics or merely repeating an item name. A reviewer MAY permit omission of redundant documentation on a self-explanatory variant or item with a documented lint exception.
- Functions that may panic on malformed input MUST document their panic cases. Unsafe functions and traits MUST document their safety invariants. Examples SHOULD cover enough behavior to make APIs usable without requiring an example for every function.
- Documentation MUST use readable Markdown directly in `///` or `//!` comments. Implementation comments and internal TODOs MUST use `//`. Generating documentation through macros SHOULD be avoided because it makes the source less directly readable.
- Unsafe code MUST NOT be written when equivalent safe code is possible. Any necessary unsafe code MUST be isolated behind a safe abstraction and separated from business logic, ideally in a small crate with few dependencies. Each unsafe block MUST have a `SAFETY:` comment explaining correctness and a technical justification explaining why safe code is insufficient. A performance justification MUST include benchmarks. Existing stricter crate lints remain binding.
- Unstable Rust features MUST NOT be used.
#### API Contracts and Other Features
- Getters MUST use `foo()` for borrowed values or `Copy` values, mutable getters `foo_mut()`, clearing accessors `take_foo()`, setters `set_foo()`, closure accessors `with_foo()` or `with_mut_foo()`, and replacements returning the old value `replace_foo()`.
- Closure accessors MAY constrain borrows of interior mutable state or perform validation after access. They MUST return the closure's result when their contract forwards it and MUST NOT leak an implementation lock guard unnecessarily.
- An API implementing `len()` MUST also implement `is_empty()`.
- Code MUST NOT access another owner's `#[doc(hidden)]` items. Public `const` functions MUST be added only when the project can preserve the `const` contract or support a migration.
- Operator overloads MUST retain their mathematical or logical purpose and MUST NOT serve only as unrelated syntax sugar.
- Public enums and public structs with public fields used by other teams MUST use `#[non_exhaustive]`, except for a fixed ontology, a two-state boolean-like enum, fields or variants that will not change, or an explicit commitment to repair all callers after changes. Structs intended for external struct update syntax MAY omit the attribute.
- Functions whose ignored return value prevents correct use, including pure functions, MUST use `#[must_use]`. Critical status and error returns MUST be covered by `#[must_use]` on the function or return type. Types carrying critical results or lazy computations MUST themselves use `#[must_use]`. `Result` already satisfies the return-type requirement.
- Code MUST NOT run before `main()` through constructor hooks or similar global initialization mechanisms.
#### Implementation Clarity
- Code MUST provide enough explicit types for a reader familiar with the project to understand inference, especially for generic conversions, parsing, and complex iterator chains. Variable annotations SHOULD be preferred to turbofish syntax when clearer.
- Matches on non-exhaustive enums SHOULD list known variants and use a wildcard for future variants. Code interested in only selected variants SHOULD use `if let` or `let ... else` when clearer. A wildcard MAY group deliberately ignored variants.
- Assertions SHOULD carry context explaining the violated contract, source of an invariant, or useful values. Context MUST NOT merely repeat the condition. This makes failures useful to reviewers and users.
- Direct iteration SHOULD replace long or complex combinator chains when clearer. A combinator chain MUST be assigned before use in a `for` loop header. `Iterator::for_each` requires a concrete clarity benefit over a loop. Short chains and combinators that express substantial logic directly remain appropriate.
- First-party code MUST NOT use `panic::catch_unwind` except as reviewed defense in depth in a build that supports unwinding. Such recovery MUST NOT be relied upon for correctness or any other required property. Review MUST establish that ordinary code already avoids panics.
- String concatenation involving more than two strings and substitution into a literal template SHOULD use `format!()` or `write!()` rather than chained addition or `str::replace` to reduce allocation and make the intended output explicit.