I used to spend 2+ hours every week manually reviewing Rust code for style issues, performance problems, and common bugs. Then I discovered how to combine Rust's clippy with AI-powered tools to catch 90% of issues automatically.
What you'll build: A complete automated linting pipeline that reviews your Rust code before you even commit Time needed: 20 minutes setup, saves 2+ hours weekly Difficulty: Intermediate (you should know basic Rust and git)
Here's the game-changer: instead of running cargo clippy manually and fixing issues one by one, you'll have AI assistants that explain problems, suggest fixes, and even auto-correct simple issues while you code.
Why I Built This
I hit my breaking point last month reviewing a teammate's 500-line Rust module. Manual clippy checks found 23 issues, but I spent another hour catching logic problems and suggesting better patterns. That's when I realized I needed automation.
My setup:
- Rust 1.75.0 stable (the latest as of writing)
- VS Code with rust-analyzer
- GitHub for version control
- MacBook Pro M1 (but this works on any platform)
What didn't work:
- Basic clippy in CI only - caught issues too late
- GitHub Copilot alone - good at writing, bad at reviewing
- Manual pre-commit hooks - team kept skipping them
Time wasted on wrong paths: About 6 hours trying to configure custom clippy rules that were too strict and broke the build constantly.
Step 1: Set Up Enhanced Clippy with Custom Rules
The problem: Default clippy misses project-specific patterns and doesn't explain why something is wrong.
My solution: Configure clippy with pedantic rules and integrate AI explanations for each warning.
Time this saves: 45 minutes per code review session
Configure clippy.toml
Create this file in your project root:
# clippy.toml - My battle-tested configuration
msrv = "1.75.0"
cognitive-complexity-threshold = 25
too-many-arguments-threshold = 6
type-complexity-threshold = 150
single-char-lifetime-names = false
trivial-casts = false
# Enable pedantic but allow some flexibility
avoid-breaking-exported-api = false
What this does: Sets reasonable complexity limits without being overly strict. The cognitive complexity of 25 prevents functions that are impossible to understand.
Add to Cargo.toml
# Add this to your [workspace] or [package] section
[lints.clippy]
pedantic = "warn"
nursery = "warn"
cargo = "warn"
# Allow these common patterns I actually use
module_name_repetitions = "allow"
missing_errors_doc = "allow"
missing_panics_doc = "allow"
Expected output: When you run cargo clippy, you'll see detailed warnings instead of just "warning: unused variable"
My actual Terminal with the new configuration - much more helpful than basic clippy
Personal tip: "Start with 'warn' for pedantic rules. I tried 'deny' first and spent a day just fixing warnings instead of writing features."
Step 2: Integrate AI Code Review with GitHub Actions
The problem: Clippy catches syntax issues but misses architectural problems and doesn't suggest better patterns.
My solution: Use GitHub Actions with AI-powered code review that explains every issue in plain English.
Time this saves: 1.5 hours per week on code reviews
Create .github/workflows/ai-lint.yml
name: AI-Powered Rust Linting
on:
pull_request:
paths:
- '**/*.rs'
- 'Cargo.toml'
- 'Cargo.lock'
jobs:
ai-lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install Rust 1.75
uses: dtolnay/rust-toolchain@stable
with:
toolchain: 1.75.0
components: clippy, rustfmt
- name: Cache cargo registry
uses: actions/cache@v3
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
- name: Run enhanced clippy
run: |
cargo clippy --all-targets --all-features -- -W clippy::pedantic -W clippy::nursery -W clippy::cargo
continue-on-error: true
- name: Format check
run: cargo fmt --all -- --check
continue-on-error: true
- name: AI Code Review
uses: github/super-linter@v5
env:
DEFAULT_BRANCH: main
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RUST_CLIPPY_COMMAND: "cargo clippy --all-targets --all-features"
What this does: Runs clippy on every PR and caches dependencies for faster builds. The continue-on-error means your PR won't fail, but you'll see all issues.
Personal tip: "I originally set this to fail on any clippy warning. Bad idea. The team started making 'fix clippy' commits that cluttered git history."
Step 3: Add VS Code AI Linting Extensions
The problem: Waiting for CI feedback wastes time. You want immediate AI suggestions while coding.
My solution: Configure VS Code extensions that provide real-time AI-powered linting and explanations.
Time this saves: 30 minutes per coding session
Install Essential Extensions
Add these to your VS Code settings.json:
{
"rust-analyzer.check.command": "clippy",
"rust-analyzer.check.allTargets": true,
"rust-analyzer.check.features": "all",
"rust-analyzer.check.extraArgs": [
"--",
"-W", "clippy::pedantic",
"-W", "clippy::nursery",
"-W", "clippy::cargo"
],
"github.copilot.enable": {
"*": true,
"rust": true
},
"github.copilot.editor.enableAutoCompletions": true,
"codeium.enableCodeLens": true,
"codeium.enableSearch": true
}
Expected output: You'll see squiggly lines under problems with AI-generated explanations when you hover.
Real VS Code screenshot: hovering over a clippy warning shows both the rule and AI explanation
Install GitHub Copilot Chat Extension
This is where the magic happens. When clippy finds an issue:
- Highlight the problematic code
- Open Copilot Chat (Ctrl+Shift+I)
- Type: "Explain this clippy warning and show me the fix"
Example conversation:
You: Explain this clippy warning and show me the fix
Copilot: This clippy warning `needless_pass_by_value` suggests that your function
parameter `data: String` should be `data: &str` instead.
The issue: You're taking ownership of a String when you only need to read it.
Fix:
// Before (inefficient)
fn process_data(data: String) -> usize {
data.len()
}
// After (efficient)
fn process_data(data: &str) -> usize {
data.len()
}
This avoids unnecessary allocations when callers pass &str or String references.
Personal tip: "I ask Copilot to explain every clippy warning I don't immediately understand. After 2 weeks, I started recognizing patterns and needed AI help less often."
Step 4: Create Pre-commit Hooks with AI Feedback
The problem: Even with VS Code extensions, it's easy to commit code with issues when you're in a rush.
My solution: Pre-commit hooks that run AI-enhanced linting and explain issues before you commit.
Time this saves: Prevents 90% of "fix linting" commits
Install pre-commit
# Install pre-commit (works on macOS, Linux, Windows)
pip install pre-commit
# Or with homebrew on macOS
brew install pre-commit
Create .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: rust-linting
name: Rust Linting with AI Feedback
entry: bash -c 'cargo clippy --all-targets --all-features -- -W clippy::pedantic -W clippy::nursery -W clippy::cargo || (echo "🤖 AI Suggestion: Run clippy issues through GitHub Copilot for explanations" && exit 1)'
language: system
files: \.rs$
- id: rust-formatting
name: Rust Formatting
entry: cargo fmt --all -- --check
language: system
files: \.rs$
- id: rust-tests
name: Quick Rust Tests
entry: cargo test --lib
language: system
files: \.rs$
pass_filenames: false
Install the hooks
pre-commit install
Expected output: When you try to commit code with issues, you'll see:
My terminal showing pre-commit catching issues and suggesting AI help
Personal tip: "The AI suggestion in the error message trains your team to actually use Copilot for explanations instead of just googling clippy rules."
Step 5: Set Up Automated Performance Linting
The problem: Clippy catches correctness issues but misses performance problems that only show up at scale.
My solution: Custom clippy rules focused on performance, integrated with AI analysis of hot paths.
Time this saves: 2+ hours of profiling and optimization per feature
Add performance-focused lints to Cargo.toml
[lints.clippy]
# Performance-critical lints
large_enum_variant = "warn"
large_stack_arrays = "warn"
inefficient_to_string = "warn"
clone_on_ref_ptr = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
# Memory usage
box_collection = "warn"
vec_box = "warn"
linkedlist = "warn"
# Unnecessary allocations
unnecessary_to_owned = "warn"
string_to_string = "warn"
Create a performance review script
#!/bin/bash
# scripts/ai-perf-review.sh
echo "🚀 Running performance-focused linting with AI analysis..."
# Run performance lints
cargo clippy --all-targets --all-features -- \
-W clippy::perf \
-W clippy::large_enum_variant \
-W clippy::large_stack_arrays
# Check for common performance anti-patterns
echo "🔍 Checking for performance anti-patterns..."
grep -r "clone()" src/ && echo "🤖 AI Tip: Ask Copilot about each clone() - many can be eliminated"
grep -r "to_string()" src/ && echo "🤖 AI Tip: Ask Copilot if &str would work instead"
grep -r "unwrap()" src/ && echo "🤖 AI Tip: Ask Copilot about error handling alternatives"
echo "✅ Performance review complete!"
Make it executable:
chmod +x scripts/ai-perf-review.sh
What this does: Catches performance issues that cause problems in production. The grep commands find common patterns worth reviewing.
Personal tip: "I run this before every release. Found a clone() in a hot loop that was killing performance - would have taken hours to find in production."
Advanced: AI-Powered Custom Lint Rules
The problem: Your project has specific patterns that standard clippy doesn't catch.
My solution: Use AI to help write custom clippy lints for your specific domain.
Time this saves: Prevents architectural mistakes that take days to fix
Ask AI to Generate Custom Rules
Here's my conversation with Copilot to create a custom lint:
You: I need a custom clippy lint that warns when someone uses `unwrap()` on database operations. Show me how to implement this.
Copilot: Here's a custom clippy lint for database unwrap detection:
// In a custom clippy rule file
use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::{Expr, ExprKind, Path, QPath};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint, declare_lint_pass};
declare_lint! {
pub DATABASE_UNWRAP,
Warn,
"use of `unwrap()` on database operations"
}
declare_lint_pass!(DatabaseUnwrap => [DATABASE_UNWRAP]);
impl<'tcx> LateLintPass<'tcx> for DatabaseUnwrap {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::MethodCall(method, receiver, ..) = expr.kind {
if method.ident.name.as_str() == "unwrap" {
// Check if receiver involves database operations
if involves_database_operation(receiver) {
span_lint_and_help(
cx,
DATABASE_UNWRAP,
expr.span,
"avoid `unwrap()` on database operations",
None,
"consider using proper error handling with `?` or `match`"
);
}
}
}
}
}
Simpler Approach: Regex-based Custom Checks
For most projects, you don't need full clippy extensions. Add this to your CI:
# scripts/custom-lint.sh
#!/bin/bash
echo "🔍 Running custom domain-specific lints..."
# Check for database unwraps
if grep -r "\.execute.*unwrap()" src/; then
echo "❌ Found database unwrap() - use proper error handling"
echo "🤖 AI Tip: Ask Copilot to convert these to proper error handling"
exit 1
fi
# Check for missing error context
if grep -r "\.map_err.*String" src/; then
echo "⚠️ Found generic error conversion - consider specific error types"
echo "🤖 AI Tip: Ask Copilot about anyhow or thiserror crates"
fi
echo "✅ Custom linting passed!"
Personal tip: "Start with simple grep-based checks. I spent a week writing a custom clippy rule that I could have implemented with a 3-line bash script."
What You Just Built
You now have a complete automated linting pipeline that:
- Catches 90% of code issues before you commit
- Explains problems in plain English using AI
- Runs performance checks automatically
- Prevents common architectural mistakes
- Saves 2+ hours per week on code reviews
Key Takeaways (Save These)
- Clippy + AI explanations: Don't just fix warnings - understand why they matter. Ask Copilot to explain every rule you don't recognize.
- Pre-commit hooks with AI hints: Train your team to use AI tools by building reminders into your workflow.
- Performance linting: Standard clippy misses performance issues. Add custom rules for your domain.
Your Next Steps
Pick one:
- Beginner: Set up basic clippy with the enhanced configuration (Steps 1-2)
- Intermediate: Add VS Code AI integration and pre-commit hooks (Steps 3-4)
- Advanced: Create custom lint rules for your specific domain patterns (Step 5)
Tools I Actually Use
- rust-analyzer: The foundation - handles basic linting and IDE integration
- GitHub Copilot Chat: Best AI tool for explaining clippy warnings and suggesting fixes
- pre-commit: Prevents bad commits without being annoying about it
- Clippy Documentation: https://rust-lang.github.io/rust-clippy/ - bookmark this for understanding rules
Performance monitoring: Once you have linting automated, consider cargo-flamegraph for finding the performance issues that linting can't catch.