/dm-lang:rust-profrom dm-lang
"Boring Rust" — clone freely, simple control flow, max-strictness lints with mechanical enforcement, ownership-honest code that compiles and reads cleanly. Use when implementing, debugging, refactoring, or reviewing Rust code; resolving borrow checker errors; tuning Cargo lints; choosing between Arc/Rc/Box; designing trait boundaries; or evaluating whether a clone is the right call. Applies to any Rust work unless a more specific role overrides.
Ships in dm-lang. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Senior-level Rust expertise following "Boring Rust" principles. Correctness over cleverness. One way to do things. Local reasoning.
Cargo.toml, clippy.toml, and rustfmt.toml for project conventionsRequired:
-D warnings in the gate)unwrap() or expect() in production code — use .context("...")? (tests are exempt via clippy.toml, not via allow attributes)unsafe without explicit human approval — isolated in a dedicated module, every block // SAFETY:-documented (mechanically enforced)#[expect]/#[allow] carries reason = "..." (denied otherwise)_ on enums you controlFoundational Principles:
One strict default, with two real escape hatches. (Everything here uses stable Rust mechanisms — no custom attributes, no pretend enforcement.)
All code, all the time. The shipped clippy.toml + [lints] config enforces:
// Complexity ceilings: cognitive 15, function lines 50, args 5, nesting 4
// Error handling: always with context
let config = load_config(path)
.context("failed to load configuration")?;
// Matching: exhaustive, no wildcards
match state {
State::Active => handle_active()?,
State::Pending => handle_pending()?,
State::Done => handle_done()?,
// NO: _ => unreachable!()
}
Test code (#[cfg(test)]) is automatically exempt from the panic lints (unwrap, expect, panic!, indexing) via allow-*-in-tests keys in clippy.toml — write natural test assertions, no preamble needed.
#[expect] with reasonFor justified local relaxations (hot paths, invariants the checker can't see). #[expect] beats #[allow] because it self-cleans: if the lint stops firing, the attribute becomes an error and gets removed.
#[expect(clippy::indexing_slicing, reason = "hot path: index bounded by loop above")]
fn sample(pixels: &[Rgba], idx: usize) -> Rgba {
pixels[idx]
}
Rules: smallest possible scope (never module-wide in production code), reason mandatory (allow_attributes_without_reason is denied), and the reason states the invariant — not "clippy is wrong".
unsafe_code is deny (not forbid) so exactly one sanctioned pattern can re-enable it:
// src/simd_ops.rs — human-approved unsafe island
#![allow(unsafe_code, reason = "SIMD intrinsics; reviewed by <name> <date>")]
/// Normalizes vectors in place using AVX2.
pub fn normalize(vectors: &mut [f32]) {
// SAFETY: alignment verified by caller contract; length checked above
unsafe { ... }
}
Agents do not create or modify these modules without explicit human direction. undocumented_unsafe_blocks (every block needs // SAFETY:) and multiple_unsafe_ops_per_block are denied, so sloppy unsafe can't slip in even with sign-off.
Pin the Rust toolchain with mise: mise use rust@latest (resolves and pins current stable in .mise.toml — commit it, complements rustup). Team members run mise install. See mise skill for setup.
Alternatively, use rust-toolchain.toml (rustup-native) if you prefer not to add mise as a dependency.
The lint config assumes 1.85+ (edition 2024 baseline); keep msrv in clippy.toml aligned with your actual floor.
# Initialize
cargo new project-name && cd project-name
# Copy configs from this skill's references/ directory:
# references/gitignore → .gitignore
# references/clippy.toml → clippy.toml
# references/cargo_lints.toml → merge into Cargo.toml [lints] section
# references/rustfmt.toml → rustfmt.toml
# For build system, invoke just-pro skill
# Verify
just check # Or: cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test
git clone <repo> && cd <repo>
just setup # Runs mise trust/install + cargo build
just check # Verify everything works
Or manually:
mise trust && mise install # Get pinned Rust toolchain
cargo build # Get dependencies
Why Boring Rust? Agent-generated code that compiles is usually correct. Complex patterns cause agents to produce incorrect or unmaintainable code.
Invoke the just-pro skill for build system setup. It covers:
references/package-rust.just)Why just? Consistent toolchain frontend between agents and humans.
Auto-Fix First:
just fix # Or: cargo clippy --fix --allow-dirty --all-targets && cargo fmt --all
Verification:
just check # fmt + clippy -D warnings + tests with coverage floor
Use --all-targets so tests, examples, and benches are linted too.
Supply chain: just audit runs cargo audit against the RustSec advisory DB (CI: just audit-ci). For license/source/duplicate policy on top of advisories, graduate to cargo-deny.
// Libraries: thiserror for typed errors
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("missing field: {field}")]
MissingField { field: &'static str },
#[error("failed to read file")]
Io(#[from] std::io::Error),
}
// Applications: anyhow with context
pub fn load_config(path: &Path) -> anyhow::Result<Config> {
let content = fs::read_to_string(path)
.context("failed to read config file")?;
toml::from_str(&content)
.context("failed to parse config")
}
// Option handling: explicit, never silent
let user = users.get(&id)
.ok_or_else(|| Error::NotFound { id: id.clone() })?;
The shipped lint set (pedantic) pushes toward idiomatic iterator use — fighting it with manual loops everywhere loses. The boring rule:
// Pure transformation, short and linear → iterator chain
let total: f32 = probes.iter()
.filter(|probe| probe.faction == target)
.map(|probe| probe.damage)
.sum();
// Body propagates errors (?) or mutates state → for loop
for record in records {
let parsed = parse(record).context("bad record")?;
store.insert(parsed)?;
}
Limits for chains: no nested closures, no side effects inside closures, no try_fold/scan cleverness when a for loop reads plainly. When in doubt, write the loop.
pub enum ConnectionState {
Disconnected,
Connecting { attempt: u32, started: Instant },
Connected { session: Session },
}
impl ConnectionState {
pub fn connect(&mut self) -> Result<(), Error> {
match self {
Self::Disconnected => {
*self = Self::Connecting {
attempt: 1,
started: Instant::now(),
};
Ok(())
}
Self::Connecting { .. } => Err(Error::AlreadyConnecting),
Self::Connected { .. } => Err(Error::AlreadyConnected),
}
}
}
use bon::Builder;
#[derive(Debug, Builder)]
pub struct ServerConfig {
#[builder(default = 8080)]
port: u16,
host: String, // Required
#[builder(default)]
timeout: Option<Duration>,
}
let config = ServerConfig::builder()
.host("localhost".to_string())
.build();
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UserId(String);
impl UserId {
// Explicit generic, not `impl Into<String>` (impl_trait_in_params is denied)
pub fn new<S: Into<String>>(raw: S) -> Result<Self, ValidationError> {
let s = raw.into();
if s.is_empty() {
return Err(ValidationError::Empty("user_id"));
}
Ok(Self(s))
}
pub fn as_str(&self) -> &str { &self.0 }
}
// GOOD: Owned data in, owned data out
pub async fn fetch_user(client: &Client, id: UserId) -> Result<User, Error> {
let response = client
.get(format!("/users/{}", id.as_str()))
.send()
.await
.context("request failed")?;
response.json::<User>().await
.context("failed to parse response")
}
// GOOD: Structured concurrency
pub async fn fetch_all(client: &Client, ids: Vec<UserId>) -> Result<Vec<User>, Error> {
futures::future::try_join_all(
ids.into_iter().map(|id| fetch_user(client, id))
).await
}
// BANNED: Complex lifetime bounds in async
async fn bad<'a>(data: &'a [u8]) -> &'a str { ... }
// BANNED: select! (disallowed-macros), manual Poll
Panic-style assertions are automatically allowed in #[cfg(test)] code (via clippy.toml) — no allow preamble:
// src/parser.rs
#[cfg(test)]
#[path = "parser_tests.rs"] // separate file keeps production files small
mod tests;
// src/parser_tests.rs
use super::*;
#[test]
fn parses_valid_input() {
let result = parse("input").unwrap(); // fine in tests
assert_eq!(result, expected);
}
Inline mod tests is fine for small files; switch to the #[path] companion file when the production file approaches its size target. One behavior per test; name describes the behavior. Property-based tests (proptest) for parsers and invariants — see references/patterns.md.
project/
├── src/
│ ├── lib.rs # Crate root
│ ├── error.rs # Error types
│ ├── config.rs # Production code
│ ├── config_tests.rs # Tests (if config.rs > 200 lines)
│ └── external/ # Wrappers around external crates
├── Cargo.toml
├── clippy.toml
├── rustfmt.toml
└── justfile
Module layout is foo.rs + foo/ — mod.rs files are denied (mod_module_files).
File size targets: Production < 300 LOC (code, excluding comments), Tests < 500 LOC.
These limits exist to improve code architecture, not to be gamed. When a file or function exceeds its clippy/size limit, the correct response is to decompose by responsibility.
Extract, don't compress:
order.rs → order/validate.rs, order/transform.rs) or a sibling moduleWhen extraction is costly: Many locals to pass — consider a context struct or builder pattern.
Prohibited responses to limit violations: combining statements onto single lines, removing or shortening comments, compressing whitespace, shortening descriptive names, inlining helpers, and #[expect]-ing the complexity lint. The goal is clean architecture, not metric compliance.
Mechanically enforced by the shipped config unless noted:
| Banned | Why | Alternative |
|---|---|---|
.unwrap() / .expect() | Panics | .context("...")? (tests exempt) |
array[i] | Panics | .get(i).ok_or(Error::Index)? |
unsafe { } | Correctness | Human-approved unsafe module with // SAFETY: docs |
#[allow] without reason | Silent drift | #[expect(lint, reason = "...")] |
impl Trait in params | Hides types | <T: Trait> explicit |
RefCell<T> / Cell<T> | Runtime borrow panics | Restructure with &mut |
select! | Cancellation bugs | Structured concurrency (try_join_all, JoinSet) |
Wildcard _ match | Silent failures | Explicit variants |
mod.rs files | Two layouts = zero layouts | foo.rs + foo/ |
dbg!, println! debugging | Ships noise | tracing |
macro_rules! | Complexity (convention, not lint) | Functions or generics |
| Complex lifetimes | Agent confusion (convention) | Clone or restructure |
clone() to silence borrow checker without understanding whyRefCell, Cell) in agent codefor loop wearing a costume| Category | Crate | Notes |
|---|---|---|
| Errors (lib) | thiserror | Derive-based |
| Errors (app) | anyhow | With .context() |
| Builder | bon | Derive-based |
| Serialization | serde | Standard |
| Async runtime | tokio | Blessed subset only (no select!) |
| HTTP client | reqwest | High-level |
| Logging | tracing | Structured |
| CLI | clap | Derive mode |
| Data parallelism | rayon | par_iter for CPU-bound work |
| Property tests | proptest | Parsers, invariants |
Before writing code:
Cargo.toml for dependencies and lint configurationclippy.toml for complexity thresholds and disallowed itemsWhen writing code:
.context("what you were doing")?for loops for effectful iteration; short pure chains are fine_ on your own enums#[expect(lint, reason = "...")] at the smallest scopeVerification cadence:
just check-fast when the repo provides it.just check for full integration at the repository’s required checkpoint; it is not automatically due before every commit.cargo fmt --check, cargo clippy --all-targets -- -D warnings, and cargo test at the appropriate package/workspace scope. Preserve full release requirements and reuse unchanged relevant evidence.#[expect]. With dm-work installed, see tauri-dev for mixed Rust/frontend and native-shell verification.Clippy and rustfmt walk up directory trees looking for config files. A rogue config in a parent directory (like /tmp) can break your project.
Symptoms:
unknown field errors from clippy (an unknown clippy.toml key is a hard error — clippy stops linting entirely)Fix: Project-local clippy.toml and rustfmt.toml (this skill's references) prevent inheritance. Keep them stable-clean: verify any new clippy.toml key against cargo clippy output and any rustfmt option against the stable list before committing.
cargo init defaults to edition 2024. If referencing older templates, update them. Note style_edition in rustfmt.toml is separate from the language edition in Cargo.toml.
references/clippy.toml — thresholds, test relaxations, disallowed items (validated on stable)references/cargo_lints.toml — Cargo.toml [lints] section (validated on stable)references/rustfmt.toml — stable-only formatting rulesreferences/patterns.md — Additional Rust patternsreferences/bevy.md — Bevy ECS patterns (game development)What SKILL.md sets; muted values are Claude Code's defaults
5 skills in this plugin
/go-proIdiomatic Go with proper error handling, concurrency patterns, slog, generics, and clean package design. Use when implementing, debugging, refactoring, or reviewing Go code; designing package boundaries; resolving race conditions or goroutine leaks; setting up table-driven tests; choosing between channels and mutexes; or tuning module layout. Applies to any Go work unless a more specific role overrides./just-proPatterns for setting up just (command runner) in projects. Use when creating build systems, setting up new repos, organizing build/test/lint recipes, or when the user asks about just/justfile configuration. Covers both simple single-project repos and monorepos with hierarchical justfile modules, mise integration, and conventional recipe naming (check, build, test, lint, fmt)./Other plugins' skills for the same job
npx claudepluginhub rbergman/dark-matter-marketplace --plugin dm-lang