rust-style-clippy について
書式の統一、Clippy の lint 方針、エディション移行、コンパイラーエラーの解説を必要とする Rust 開発者向けのスキルです。設定や CI の実践を扱い、機械的な lint 検査と広範な API 設計を区別します。
主な機能
- 01安定版 rustfmt の書式を設定
- 02全 Clippy lint グループを利用・設定
- 03lint 方針と優先度を設定
- 04Rust エディション間を移行
- 05よくあるコンパイラーエラーを解説
- 06API ガイドラインと Clippy lint を対応付け
活用シーン
- 01Rust コードを整形し CI で確認
- 02プロジェクト種別に応じた lint 設定を選択
- 03Rust エディション移行を計画
- 04rustc エラーコードを理解
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ full-stack-skills/ rust-skills --skill rust-style-clippyインストール後、Claude Code で/rust-style-clippyを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
agents/openai.yamlexamples/examples.mdexamples/golden-style/Cargo.tomlexamples/golden-style/src/lib.rsreferences/api-guidelines-to-clippy.mdclippy-lint-policy.mdproduction-rust-idioms.mdreferences.md詳細
Rust のスタイル整形と静的解析
rustfmt Book、Clippy Book、Edition Guide、Error Code Indexに基づいています。
対応範囲
✅ 得意なこと
- 安定版 rustfmt の設定(edition、max_width、tab_spaces、use_field_init_shorthand など)
- Clippy の lint システム — 10 個すべての lint グループ:correctness、suspicious、style、complexity、perf、pedantic、restriction、cargo、nursery、internal
clippy.tomlの設定(msrv、arithmetic-side、cognitive-complexity-threshold、avoid-breaking-exported-api など)- CI で適用する lint の期待値を指定する
#[expect(...)]属性(Rust 1.81 以降) - 階層化ポリシーのための lint の
priority順序 - 本番環境の CI lint ポリシー(グループごとの deny/warn/allow の判断)
- Edition の移行(2015→2018→2021→2024、各 Edition の主な変更点と cargo fix コマンド)
- コンパイラーエラーコードの解釈(rustc --explain、一般的なエラーコードの参照表)
⚠️ 前提条件
- Rust ツールチェーンがインストールされ、設定されていること
❌ 対象外
- Rust の構文の基礎 →
rust-stableスキルを使用してください - コードレビュー →
rust-code-reviewスキルを使用してください - API の形状設計(命名、型/トレイト設計、モジュール構成)と C-* API ガイドライン全項目(約 100 項目)のチェックリスト →
rust-api-designスキルを使用してください。このスキルでは、Clippy で機械的に適用できる約 25 項目の C-* ルールのみを扱います。それ以外は設計上の判断が必要です。
使用する場面
- 「Rust コードを整形する」
- 「Clippy を実行する」
- 「新しい Edition に移行する」
- 「コンパイラーエラー E0xxx は何を意味しますか?」
I. rustfmt の設定
# .rustfmt.toml
max_width = 100 # Line width (default: 100)
tab_spaces = 4 # Indentation spaces
edition = "2024" # Rust edition
merge_derives = true # Merge derives
use_field_init_shorthand = true # Field initialization shorthand
use_try_shorthand = true # Use ? shorthand
cargo fmt # Format all files
cargo fmt --check # Check formatting (CI usage)
cargo fmt -- --config max_width=80 # Apply specific configuration
imports_granularity、group_imports、reorder_impl_items などのオプションでは、依然として nightly rustfmt が必要な場合があります。安定版 CI を通過する必要があるデフォルト設定には含めないでください。
II. Clippy
cargo clippy # Default: correctness, suspicious, style, complexity, perf
cargo clippy -- -W clippy::pedantic # Enable pedantic group
cargo clippy --fix # Auto-fix MachineApplicable lints
cargo clippy -- -A clippy::module_inception # Allow a specific lint
10 個すべての lint グループ
| グループ | デフォルトのレベル | 説明 | 効果の大きい lint |
|---|---|---|---|
correctness | deny(実質的に) | 誤っているコード — セマンティクスが壊れている状態 | almost_swap、drop_non_drop、if_same_then_else、out_of_bounds_looping、ptr_offset_with_cast |
suspicious | warn | コンパイルは通るものの、不自然でバグの可能性が高いコード | mutable_key_type、assign_op_pattern、blqcklisted_name、cast_lossless、clone_on_ref_ptr |
style | warn(デフォルトのグループ) | 慣用的な Rust のスタイル上の推奨事項 | enum_variant_names、new_without_default、wrong_self_convention、needless_return、module_inception |
complexity | warn | より簡潔にできるコード | too_many_arguments、cognitive-complexity、manual_flatten、option_option |
perf | warn | パフォーマンスに関するヒント(割り当て、コピー) | large_enum_variant、single_char_pattern、manual_memcpy、vec_box、derivable_impls |
pedantic | allow(オプトイン) | 意見の分かれるスタイル上の規則 — style より厳格 | cast_possible_truncation、fn_params_excessive_bools、must_use_candidate、missing_errors_doc、module_name_repetitions |
restriction | allow(オプトイン) | 意図的な場合もあるものの、リスクのあるパターンを禁止 | unwrap_used、expect_used、panic、indexing_slicing、dbg_macro、print_stdout、float_arithmetic |
cargo | warn | Cargo.toml の品質 | cargo_common_metadata、negative_feature_names、redundant_feature_names、wildcard_dependencies |
nursery | allow(実験的) | 開発中の lint | use_self、fallible_impl_from、missing_const_for_fn |
internal | allow | Clippy 自体の開発向け | (ユーザーが使うことはまれ) |
#[expect] 属性(Rust 1.81 以降)— #[allow] より優れた方法
// ✅ #[expect] — CI fails if the lint stops firing, surfacing dead expectations
#[expect(clippy::too_many_arguments, reason = "configurable builder has many options")]
fn build(name: &str, retries: u32, timeout: u32, /* 5 more */) { /* */ }
// ❌ #[allow] — silently becomes dead code if the lint stops firing
#[allow(clippy::too_many_arguments)]
fn build(/* */) { /* */ }
意図的に警告を抑制する場合は #[expect] を優先し、一時的な理由がある場合に限って #[allow] を使用してください。
lint の priority — 階層化
// Higher priority wins. Use for layered policy.
#![warn(clippy::pedantic)] // enable pedantic (priority 0)
#![warn(priority = 1, clippy::module_name_repetitions)] // re-enable a specific lint
clippy.toml の設定
# clippy.toml at workspace root
msrv = "1.85" # Don't suggest APIs newer than MSRV
avoid-breaking-exported-api = false # Suggest fixes that change public API
cognitive-complexity-threshold = 25 # Function complexity limit
arithmetic-side = "checked" # Prefer checked_* arithmetic
enum-variant-name-threshold = 1 # Trigger variant_name lint
single-char-binding-names-threshold = 3 # Allow `_a`, `_b`, but not 4+
too-many-arguments-threshold = 7
type-complexity-threshold = 250
disallowed-methods = [
{ path = "std::env::var", reason = "use our config::get instead" },
]
disallowed-types = [
{ path = "std::collections::LinkedList", reason = "almost never the right choice" },
]
disallowed-macros = [
{ path = "std::println", reason = "use tracing in libraries" },
]
clippy.toml の全項目のリファレンスと本番環境向けポリシーについては、references/clippy-lint-policy.md を参照してください。
本番 CI の lint ポリシー
プロジェクトによって必要な厳格さは異なります。そのまま貼り付けて使える設定については、references/clippy-lint-policy.md を参照してください。
| プロジェクトの種類 | Pedantic | Restriction | 推奨設定 |
|---|---|---|---|
| ライブラリ(公開) | warn | allow | clippy::all + clippy::pedantic warn + cargo::cargo_common_metadata deny |
| アプリケーション/バイナリ | warn | warn(unwrap_used) | restriction::unwrap_used、panic、indexing_slicing を追加 |
| 組み込み/セーフティクリティカル | warn | deny | すべての restriction lint を deny に設定し、float_arithmetic deny を追加 |
| 内部ツール | allow | allow | clippy::all(デフォルトのグループ)のみ |
III. エディションの移行
# Check current edition
cargo metadata --format-version 1 | jq '.packages[0].edition'
# Migration steps (example: 2021 → 2024)
cargo fix --edition # Auto-migrate code
cargo build # Verify compilation
cargo test # Validate functionality
# Update Cargo.toml
# edition = "2024"
エディションごとの主な変更点:
| エディション | 主な変更点 |
|---|---|
| 2015→2018 | パスとモジュールのインポートの変更、dyn Trait、NLL、匿名ライフタイムとキーワードの変更 |
| 2018→2021 | クロージャーキャプチャーの精密化、配列の IntoIterator、panic マクロの一貫性、プレリュードと予約構文の変更 |
| 2021→2024 | RPIT のライフタイムキャプチャー、match ergonomics の調整、一時値のスコープ、unsafe extern/unsafe 属性、gen キーワードなど |
IV. コンパイラーエラーコード早見表
# View error details
rustc --explain E0277
| エラーコード | 意味 | よくある状況 |
|---|---|---|
| E0277 | トレイトが実装されていない | T: Trait の境界が満たされていない |
| E0308 | 型が一致しない | 型 A が期待されているが、B が指定されている |
| E0502 | 借用の競合 | 可変借用と不変借用を同時に行うことはできない |
| E0597 | ライフタイムが不十分 | 参照のスコープが、そのライフタイム値の範囲を超えている |
| E0432 | インポートが見つからない | use パスが正しくない |
| E0061 | 引数の数が一致しない | 関数呼び出しの引数の数が正しくない |
| E0106 | ライフタイムが不足している | 関数シグネチャで明示的なライフタイムが必要 |
| E0382 | 移動済みの値を使用している | 所有権がすでに移動している |
| E0499 | 同時の可変借用 | 1 つの式につき &mut は 1 つだけ使用可能 |
| E0716 | 一時値のライフタイムが不十分 | 一時値への参照が、そのスコープを超えている |
V. API ガイドライン ↔ Clippy リント
Rust API ガイドラインのチェックリストでは、C-* ルール(合計約100項目)が使われています。Clippy はそのうち約25項目を機械的に適用します。残りの約75項目は、設計上の判断(命名、型/トレイトの形状、モジュール構成)に関するもので、rust-api-design スキルの範疇です。または、破壊的変更の検出に cargo-semver-checks が必要です。以下の表では、レビュー担当者から最もよく質問される、特に効果の高い12項目の対応関係を示しています。「未対応のリント」に関するガイダンスを含む完全な対応表は、references/api-guidelines-to-clippy.md にあります。
| C-* ルール | Clippy リント | グループ | 効果 |
|---|---|---|---|
| C-UNWRAP | clippy::unwrap_used | restriction | unwrap() 呼び出しを検出します |
| C-UNWRAP | clippy::expect_used | restriction | expect() 呼び出しを検出します |
| C-PANIC | clippy::panic | restriction | panic!() を検出します |
| C-INDEXING | clippy::indexing_slicing | restriction | [i] によるインデックス指定(パニックを起こす)を検出します |
| C-BOOL-ARG | clippy::fn_params_excessive_bools | pedantic | bool パラメーターが3個以上の関数を検出します |
| C-NEWTYPE | clippy::new_without_default | style | new() はあるが Default がありません |
| C-NEWTYPE | clippy::new_ret_no_self | style | new() が Self 以外を返します |
| C-CONV / C-WRONG-SELF | clippy::wrong_self_convention | style | &self を取る as_X(self)、または self を消費する to_X(&self) を検出します |
| C-STRING-PATTERNS | clippy::single_char_pattern | perf | .contains("a") → .contains('a') |
| C-COMMON-TRAITS | clippy::derivable_impls | perf | derive で置き換えられる手動の impl を検出します |
| C-LARGE-NUMERIC | clippy::unreadable_literal | style | 1000000 は 1_000_000 にすべきです |
| C-MUTABLE-KEY | clippy::mutable_key_type | suspicious | HashMap のキー型が可変です |
| C-CLONE-ON-REF | clippy::clone_on_ref_ptr | restriction | Rc/Arc に対する .clone() を検出します |
多くの restriction および pedantic リントはデフォルトで無効です。CI でガイドラインを適用する場合は、#![warn(clippy::unwrap_used)] を使うか、clippy.toml で明示的に有効にしてください。
ワークフロー
- コードをフォーマットする —
cargo fmtでスタイルを統一します - Clippy を実行する —
cargo clippyでデフォルトの5グループ(correctness、suspicious、style、complexity、perf)が実行されます。より厳格にするには-W clippy::pedanticを追加します - ポリシーを決める — プロジェクトの種類に応じて pedantic/restriction のレベルを選び(上の表を参照)、
references/clippy-lint-policy.mdにある該当する設定を貼り付けます clippy.tomlを設定する —msrv、disallowed-methods、およびプロジェクト固有のしきい値を設定します- 意図的に抑制する場合は
#[expect]を使う — CI で不要になった期待指定を正しく検出できるようにします - Edition を確認する — Cargo.toml の edition が最新であることを確認します
- CI に統合する — CI で
cargo fmt --check+cargo clippy -- -D warnings+cargo auditを実行します
注意点
cargo clippy --fixで修正されるのは、MachineApplicable レベルのリントのみです- rustfmt の設定ファイル名は
.rustfmt.tomlであり、rustfmt.tomlではありません - Edition の移行後、新しい警告が表示されることがあります。特に2024では unsafe_op_in_unsafe_fn に注意してください
cargo fix --editionですべての問題が修正されるわけではありません。移行後に手動でレビューする必要があります- 早期終了には
let ... else、単純なブール値へのマッピングにはis_some_and/then_someを優先してください。最新の構文を使うためだけに、複雑な制御フローを圧縮するのは避けてください saturating_*、checked_*、通常の算術式では、オーバーフロー時の処理に関するビジネス上の意味が異なります。まず方針を決めてから API を選択してください
オンデマンドリソース
- フォーマットと Clippy の例
- Lint グループのクイックリファレンス
- Clippy の Lint ポリシー:
clippy.tomlの完全なリファレンス、10 個すべての lint グループの詳細、#[expect]のパターン、priorityによるレイヤー化、プロジェクトの種類ごとにすぐに貼り付けて使える本番環境向け CI 設定を掲載しています。 - 本番環境向け Rust のイディオム:本番コードをレビューする際に、let-else、Option コンビネーター、newtype パターン、非網羅的 API、ロックのスコープ、オーバーフロー対策を確認できます。
- API ガイドライン ↔ Clippy Lint 対応表:Rust API ガイドラインの
C-*ルールと、それらを適用する Clippy lint の完全な対応表に加え、Clippy がカバーしていない約 75 個のルールと、そのレビュー方法を掲載しています。 examples/golden-style/:rustfmt と Clippy に合格する CI 向けの模範例