mcpField
R
rust-style-clippy

rust-style-clippy

github.com/full-stack-skills開発12137 回インストール5 週間前に更新
リポジトリ

rust-style-clippy について

書式の統一、Clippy の lint 方針、エディション移行、コンパイラーエラーの解説を必要とする Rust 開発者向けのスキルです。設定や CI の実践を扱い、機械的な lint 検査と広範な API 設計を区別します。

主な機能

  1. 01安定版 rustfmt の書式を設定
  2. 02全 Clippy lint グループを利用・設定
  3. 03lint 方針と優先度を設定
  4. 04Rust エディション間を移行
  5. 05よくあるコンパイラーエラーを解説
  6. 06API ガイドラインと Clippy lint を対応付け

活用シーン

  1. 01Rust コードを整形し CI で確認
  2. 02プロジェクト種別に応じた lint 設定を選択
  3. 03Rust エディション移行を計画
  4. 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.yaml
examples/
examples.md
examples/golden-style/
Cargo.toml
examples/golden-style/src/
lib.rs
references/
api-guidelines-to-clippy.md
clippy-lint-policy.md
production-rust-idioms.md
references.md

詳細

Rust のスタイル整形と静的解析

rustfmt Book、Clippy Book、Edition Guide、Error Code Index に基づいています。

対応範囲

✅ 得意なこと
  1. 安定版 rustfmt の設定(edition、max_width、tab_spaces、use_field_init_shorthand など)
  2. Clippy の lint システム — 10 個すべての lint グループ:correctness、suspicious、style、complexity、perf、pedantic、restriction、cargo、nursery、internal
  3. clippy.toml の設定(msrv、arithmetic-side、cognitive-complexity-threshold、avoid-breaking-exported-api など)
  4. CI で適用する lint の期待値を指定する #[expect(...)] 属性(Rust 1.81 以降)
  5. 階層化ポリシーのための lint の priority 順序
  6. 本番環境の CI lint ポリシー(グループごとの deny/warn/allow の判断)
  7. Edition の移行(2015→2018→2021→2024、各 Edition の主な変更点と cargo fix コマンド)
  8. コンパイラーエラーコードの解釈(rustc --explain、一般的なエラーコードの参照表)
⚠️ 前提条件
  1. Rust ツールチェーンがインストールされ、設定されていること
❌ 対象外
  1. Rust の構文の基礎 → rust-stable スキルを使用してください
  2. コードレビュー → rust-code-review スキルを使用してください
  3. 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
correctnessdeny(実質的に)誤っているコード — セマンティクスが壊れている状態almost_swap、drop_non_drop、if_same_then_else、out_of_bounds_looping、ptr_offset_with_cast
suspiciouswarnコンパイルは通るものの、不自然でバグの可能性が高いコードmutable_key_type、assign_op_pattern、blqcklisted_name、cast_lossless、clone_on_ref_ptr
stylewarn(デフォルトのグループ)慣用的な Rust のスタイル上の推奨事項enum_variant_names、new_without_default、wrong_self_convention、needless_return、module_inception
complexitywarnより簡潔にできるコードtoo_many_arguments、cognitive-complexity、manual_flatten、option_option
perfwarnパフォーマンスに関するヒント(割り当て、コピー)large_enum_variant、single_char_pattern、manual_memcpy、vec_box、derivable_impls
pedanticallow(オプトイン)意見の分かれるスタイル上の規則 — style より厳格cast_possible_truncation、fn_params_excessive_bools、must_use_candidate、missing_errors_doc、module_name_repetitions
restrictionallow(オプトイン)意図的な場合もあるものの、リスクのあるパターンを禁止unwrap_used、expect_used、panic、indexing_slicing、dbg_macro、print_stdout、float_arithmetic
cargowarnCargo.toml の品質cargo_common_metadata、negative_feature_names、redundant_feature_names、wildcard_dependencies
nurseryallow(実験的)開発中の lintuse_self、fallible_impl_from、missing_const_for_fn
internalallowClippy 自体の開発向け(ユーザーが使うことはまれ)
#[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 を参照してください。

プロジェクトの種類PedanticRestriction推奨設定
ライブラリ(公開)warnallowclippy::all + clippy::pedantic warn + cargo::cargo_common_metadata deny
アプリケーション/バイナリwarnwarn(unwrap_used)restriction::unwrap_used、panic、indexing_slicing を追加
組み込み/セーフティクリティカルwarndenyすべての restriction lint を deny に設定し、float_arithmetic deny を追加
内部ツールallowallowclippy::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→2024RPIT のライフタイムキャプチャー、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-UNWRAPclippy::unwrap_usedrestrictionunwrap() 呼び出しを検出します
C-UNWRAPclippy::expect_usedrestrictionexpect() 呼び出しを検出します
C-PANICclippy::panicrestrictionpanic!() を検出します
C-INDEXINGclippy::indexing_slicingrestriction[i] によるインデックス指定(パニックを起こす)を検出します
C-BOOL-ARGclippy::fn_params_excessive_boolspedanticbool パラメーターが3個以上の関数を検出します
C-NEWTYPEclippy::new_without_defaultstylenew() はあるが Default がありません
C-NEWTYPEclippy::new_ret_no_selfstylenew() が Self 以外を返します
C-CONV / C-WRONG-SELFclippy::wrong_self_conventionstyle&self を取る as_X(self)、または self を消費する to_X(&self) を検出します
C-STRING-PATTERNSclippy::single_char_patternperf.contains("a") → .contains('a')
C-COMMON-TRAITSclippy::derivable_implsperfderive で置き換えられる手動の impl を検出します
C-LARGE-NUMERICclippy::unreadable_literalstyle1000000 は 1_000_000 にすべきです
C-MUTABLE-KEYclippy::mutable_key_typesuspiciousHashMap のキー型が可変です
C-CLONE-ON-REFclippy::clone_on_ref_ptrrestrictionRc/Arc に対する .clone() を検出します

多くの restriction および pedantic リントはデフォルトで無効です。CI でガイドラインを適用する場合は、#![warn(clippy::unwrap_used)] を使うか、clippy.toml で明示的に有効にしてください。

ワークフロー

  1. コードをフォーマットする — cargo fmt でスタイルを統一します
  2. Clippy を実行する — cargo clippy でデフォルトの5グループ(correctness、suspicious、style、complexity、perf)が実行されます。より厳格にするには -W clippy::pedantic を追加します
  3. ポリシーを決める — プロジェクトの種類に応じて pedantic/restriction のレベルを選び(上の表を参照)、references/clippy-lint-policy.md にある該当する設定を貼り付けます
  4. clippy.toml を設定する — msrv、disallowed-methods、およびプロジェクト固有のしきい値を設定します
  5. 意図的に抑制する場合は #[expect] を使う — CI で不要になった期待指定を正しく検出できるようにします
  6. Edition を確認する — Cargo.toml の edition が最新であることを確認します
  7. CI に統合する — CI で cargo fmt --check + cargo clippy -- -D warnings + cargo audit を実行します

注意点

  1. cargo clippy --fix で修正されるのは、MachineApplicable レベルのリントのみです
  2. rustfmt の設定ファイル名は .rustfmt.toml であり、rustfmt.toml ではありません
  3. Edition の移行後、新しい警告が表示されることがあります。特に2024では unsafe_op_in_unsafe_fn に注意してください
  4. cargo fix --edition ですべての問題が修正されるわけではありません。移行後に手動でレビューする必要があります
  5. 早期終了には let ... else、単純なブール値へのマッピングには is_some_and/then_some を優先してください。最新の構文を使うためだけに、複雑な制御フローを圧縮するのは避けてください
  6. 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 向けの模範例

公式リファレンス

コメント