### Install mdBook Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/book.md Install mdBook using cargo. This is the easiest option if you have cargo installed. ```shell cargo install mdbook ``` -------------------------------- ### Install nightly rustfmt Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Install the nightly rustfmt component via rustup to ensure compatibility with Clippy's CI requirements. ```bash rustup component add rustfmt --toolchain=nightly ``` -------------------------------- ### Example of a Help Message Diagnostic in Rust Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/emitting_lints.md This example demonstrates a 'help' message diagnostic, indicating a potential issue and suggesting an alternative approach. ```text error: constant division of 0.0 with 0.0 will always result in NaN --> tests/ui/zero_div_zero.rs:6:25 | 6 | let other_f64_nan = 0.0f64 / 0.0; | ^^^^^^^^^^^^ | = help: consider using `f64::NAN` if you would like a constant representing NaN ``` -------------------------------- ### Generate version info in build.rs Source: https://github.com/rust-lang/rust-clippy/blob/master/rustc_tools_util/README.md Invoke the setup macro within the build script's main function. ```rust fn main() { rustc_tools_util::setup_version_info!(); } ``` -------------------------------- ### Example of a Suggestion Diagnostic in Rust Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/emitting_lints.md This example illustrates a 'suggestion' diagnostic, offering a direct code change to fix the issue, often usable by `rustfix`. ```text error: This `.fold` can be more succinctly expressed as `.any` --> tests/ui/methods.rs:390:13 | 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)` | ``` -------------------------------- ### Build and install Clippy toolchain Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/basics.md Run this command from the Clippy project root to build binaries and register the toolchain. ```terminal cargo dev setup toolchain ``` -------------------------------- ### Install Clippy Component Source: https://context7.com/rust-lang/rust-clippy/llms.txt Installs Clippy as a rustup component for seamless integration with your Rust toolchain. Ensure your rustup and compiler are up-to-date before installation. ```bash rustup update rustup component add clippy cargo clippy --version ``` -------------------------------- ### Install Clippy Source: https://github.com/rust-lang/rust-clippy/blob/master/README.md Add the Clippy component to the current Rust toolchain. ```terminal rustup component add clippy ``` -------------------------------- ### Install Clippy using Rustup Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/installation.md Use this command to add Clippy as a component to your Rust toolchain if it was not automatically installed. You can specify a particular toolchain using the --toolchain flag. ```bash $ rustup component add clippy [--toolchain=] ``` -------------------------------- ### Example of a Note Diagnostic in Rust Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/emitting_lints.md This example shows the typical output format for a 'note' diagnostic, including the error location and a specific note with its own span. ```text error: calls to `std::mem::forget` with a reference instead of an owned value. Forgetting a reference does nothing. --> tests/ui/drop_forget_ref.rs:10:5 | 10 | forget(&SomeStruct); | ^^^^^^^^^^^^^^^^^^^^ | = note: `-D clippy::forget-ref` implied by `-D warnings` note: argument has type &SomeStruct --> tests/ui/drop_forget_ref.rs:10:12 | 10 | forget(&SomeStruct); | ^^^^^^^^^^^ ``` -------------------------------- ### GitLab CI Integration for Clippy Source: https://context7.com/rust-lang/rust-clippy/llms.txt Configure Clippy for GitLab CI/CD pipelines. This setup defines stages for linting and testing, installs Clippy, and runs the linter on merge requests and default branch commits. ```yaml # .gitlab-ci.yml image: rust:latest variables: CARGO_HOME: $CI_PROJECT_DIR/.cargo cache: paths: - .cargo/ - target/ stages: - lint - test clippy: stage: lint before_script: - rustup component add clippy script: - cargo clippy --all-targets --all-features -- -D warnings rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH test: stage: test script: - cargo test --all-features ``` -------------------------------- ### Run Speedtest with Custom Iterations Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/speedtest.md Execute a speed test with a custom number of iterations. This example tests the 'semicolon_block' lint with 100 iterations. ```sh $ SPEEDTEST=toml SPEEDTEST_ITERATIONS=100 TESTNAME="semicolon_block" cargo uitest ``` -------------------------------- ### UI Test Example for `foo_functions` Lint Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md This Rust code snippet is used in a UI test file to check the `foo_functions` lint. It includes examples of methods and functions that should trigger the lint, marked with `//~^ foo_functions` comments. Method calls are excluded from linting. ```rust #![allow(unused)] #![warn(clippy::foo_functions)] // Impl methods struct A; impl A { pub fn fo(&self) {} pub fn foo(&self) {} //~^ foo_functions pub fn food(&self) {} } // Default trait methods trait B { fn fo(&self) {} fn foo(&self) {} //~^ foo_functions fn food(&self) {} } // Plain functions fn fo() {} fn foo() {} //~^ foo_functions fn food() {} fn main() { // We also don't want to lint method calls foo(); let a = A; a.foo(); } ``` -------------------------------- ### Define Changelog Entries Source: https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md Examples of various changelog entry formats for different types of pull requests. ```text changelog: new lint: [`missing_trait_methods`] ``` ```text changelog: Fix [`unused_peekable`] false positive when peeked in a closure or called as `f(&mut peekable)` ``` ```text changelog: none ``` ```text changelog: Something 1 changelog: Something 2 changelog: Something 3 ``` -------------------------------- ### Example Clippy Lint Output During Testing Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/writing_tests.md As lint logic is implemented, UI tests will start to show actual lint errors. This output demonstrates the expected format of a failing test with specific lint messages. ```text failures: ---- compile_test stdout ---- normalized stderr: error: function called "foo" --> tests/ui/foo_functions.rs:6:12 | LL | pub fn foo(&self) {} | ^^^ | = note: `-D clippy::foo-functions` implied by `-D warnings` error: function called "foo" --> tests/ui/foo_functions.rs:13:8 | LL | fn foo(&self) {} | ^^^ error: function called "foo" --> tests/ui/foo_functions.rs:19:4 | LL | fn foo() {} | ^^^ error: aborting due to 3 previous errors ``` -------------------------------- ### Run Clippy on All Targets and Features Source: https://context7.com/rust-lang/rust-clippy/llms.txt Analyzes all targets, including tests and examples, and enables all features for a comprehensive code review. Use this for a thorough check of your entire project. ```bash cargo clippy --all-targets --all-features ``` -------------------------------- ### Add Clippy to Travis CI Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/continuous_integration/travis.md Configure your .travis.yml file to install and run Clippy. Ensure Clippy is added as a component before the build script. ```yml language: rust rust: - stable - beta before_script: - rustup component add clippy script: - cargo clippy # if you want the build job to fail when encountering warnings, use - cargo clippy -- -D warnings # in order to also check tests and non-default crate features, use - cargo clippy --all-targets --all-features -- -D warnings - cargo test # etc. ``` -------------------------------- ### Example AST Code for EarlyLintPass Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/lint_passes.md This Rust code snippet demonstrates code that is syntactically correct from an AST perspective, which is the focus of EarlyLintPass. It highlights that EarlyLintPass does not have access to type information. ```rust let x = OurUndefinedType; x.non_existing_method(); ``` -------------------------------- ### Example lint diagnostic output Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/emitting_lints.md A sample representation of how a lint diagnostic with an automatic suggestion appears in the console. ```text error: an inclusive range would be more readable --> tests/ui/range_plus_minus_one.rs:37:14 | LL | for _ in 1..1 + 1 {} | ^^^^^^^^ help: use: `1..=1` ``` -------------------------------- ### Update Rustup Source: https://github.com/rust-lang/rust-clippy/blob/master/README.md Ensure the latest version of Rustup and the compiler are installed. ```terminal rustup update ``` -------------------------------- ### Emit a lint with span_lint_and_help Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/emitting_lints.md Example implementation of check_expr using span_lint_and_help to provide a diagnostic message and a suggestion. ```rust impl<'tcx> LateLintPass<'tcx> for LintName { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { // Imagine that `some_lint_expr_logic` checks for requirements for emitting the lint if some_lint_expr_logic(expr) { span_lint_and_help( cx, // < The context LINT_NAME, // < The name of the lint in ALL CAPS expr.span, // < The span to lint "message on why the lint is emitted", None, // < An optional help span (to highlight something in the lint) "message that provides a helpful suggestion", ); } } } ``` -------------------------------- ### Emit lint with span_lint_and_help Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Example of using span_lint_and_help to report a diagnostic with a help message. ```rust impl EarlyLintPass for FooFunctions { fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, span: Span, _: NodeId) { span_lint_and_help( cx, FOO_FUNCTIONS, span, "function named `foo`", None, "consider using a more meaningful name" ); } } ``` -------------------------------- ### Defining an EarlyLintPass in Clippy Source: https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md This example demonstrates the basic structure for defining a lint that implements the EarlyLintPass trait. It includes necessary imports and the struct definition. ```rust // ./clippy_lints/src/else_if_without_else.rs use rustc_lint::{EarlyLintPass, EarlyContext}; // ... pub struct ElseIfWithoutElse; // ... impl EarlyLintPass for ElseIfWithoutElse { // ... the functions needed, to make the lint work } ``` -------------------------------- ### Example of Enforcing Iter Loop Reborrow Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/lint_configuration.md Demonstrates the recommended way to use implicit into iter for reborrowed values in loops, contrasting it with the explicit .iter() and .iter_mut() methods. ```rust let mut vec = vec![1, 2, 3]; let rmvec = &mut vec; for _ in rmvec.iter() {} for _ in rmvec.iter_mut() {} ``` ```rust let mut vec = vec![1, 2, 3]; let rmvec = &mut vec; for _ in &*rmvec {} for _ in &mut *rmvec {} ``` -------------------------------- ### Rust-like pattern syntax for complex binary operation Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Shows a more complex pattern matching a binary operation involving `1 + 0` and another `0`. This example further emphasizes the challenges in handling operator precedence within a Rust-like pattern syntax. ```rust 1 + 0 #[*:BinOpKind] 0 ``` -------------------------------- ### GitHub Actions Workflow for Clippy Source: https://context7.com/rust-lang/rust-clippy/llms.txt Integrate Clippy into GitHub Actions for automated code quality checks on push and pull requests. This workflow installs the necessary toolchain and runs Clippy. ```yaml # .github/workflows/clippy.yml name: Clippy on: push: branches: [main] pull_request: branches: [main] env: CARGO_TERM_COLOR: always RUSTFLAGS: "-Dwarnings" jobs: clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust toolchain uses: dtolnay/rust-action@stable with: components: clippy - name: Cache cargo registry uses: actions/cache@v4 with: path: | ~/.cargo/registry ~/.cargo/git target key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - name: Run Clippy run: cargo clippy --all-targets --all-features ``` -------------------------------- ### Setting up Local Clippy Toolchain Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Commands to set up a local rustup toolchain pointing to local Clippy binaries for testing. ```bash cargo dev setup toolchain ``` ```bash cargo +clippy clippy ``` -------------------------------- ### Build and Test Clippy Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/basics.md Standard commands for building and running the full test suite. ```bash cargo build # builds Clippy cargo test # tests Clippy ``` -------------------------------- ### Retrieve version info in main.rs Source: https://github.com/rust-lang/rust-clippy/blob/master/rustc_tools_util/README.md Use the version info macro to access and display the generated metadata. ```rust fn show_version() { let version_info = rustc_tools_util::get_version_info!(); println!("{}", version_info); } ``` -------------------------------- ### Crate with Command Line Options Source: https://github.com/rust-lang/rust-clippy/blob/master/lintcheck/README.md Specify custom command-line options for a crate during linting, allowing for feature enablement or disabling. ```toml clap = {name = "clap", versions = ['4.5.8'], options = ['-Fderive']} ``` -------------------------------- ### Serve Clippy Book Locally Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/book.md Serve the Clippy book locally to view changes in real time. Changes are automatically updated as you make them. ```shell mdbook serve book --open ``` -------------------------------- ### Run Clippy Source: https://github.com/rust-lang/rust-clippy/blob/master/README.md Execute Clippy on the current project. ```terminal cargo clippy ``` -------------------------------- ### Define complex patterns with repetition Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md An example of a complex pattern that currently requires significant repetition. ```rust pattern!{ pat_if_else: Expr = If( _, _, Block_( Block( Expr((If(_, _, _?) | IfLet(_, _?))#else_) | Semi((If(_, _, _?) | IfLet(_, _?))#else_) )#block_inner )#block ) | IfLet( _, Block_( Block( Expr((If(_, _, _?) | IfLet(_, _?))#else_) | Semi((If(_, _, _?) | IfLet(_, _?))#else_) )#block_inner )#block ) } ``` -------------------------------- ### Configure RustRover for compiler internals Source: https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md Run this command to point Clippy to a local rustc repository for better IDE support. ```bash cargo dev setup intellij --repo-path ``` -------------------------------- ### Switch to Beta Branch Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/backport.md Updates the local environment to the current Rust beta branch by resetting to the upstream beta state. ```bash git switch beta git fetch upstream git reset --hard upstream/beta ``` -------------------------------- ### Run Clippy on a project Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/basics.md Execute Clippy within a project directory using the newly created toolchain. ```terminal cd my-project cargo +clippy clippy ``` -------------------------------- ### Get Clippy Commit Hash Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/changelog_update.md Use this command in a `rust-lang/rust` checkout to find the merge commit hash for the Clippy tool. ```bash git log --oneline -- src/tools/clippy/ | grep -o "Merge commit '[a-f0-9]*' into .*" | head -1 | sed -e "s/Merge commit '\([a-f0-9]*\)' into .*/\1/g" ``` -------------------------------- ### Configure rust-analyzer for multiple projects Source: https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md Add these paths to your configuration to enable rust-analyzer support for sub-crates. ```json { "rust-analyzer.linkedProjects": [ "./Cargo.toml", "clippy_dev/Cargo.toml", "lintcheck/Cargo.toml", ] } ``` -------------------------------- ### Specify Target Directory and Manifest Path Source: https://github.com/rust-lang/rust-clippy/blob/master/lintcheck/README.md Run `cargo lintcheck` with a custom target directory and manifest path, useful for specific build configurations. ```bash cargo run --target-dir lintcheck/target --manifest-path lintcheck/Cargo.toml ``` -------------------------------- ### Configure rust-analyzer for compiler source Source: https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md Set this configuration to enable rust-analyzer to discover compiler source code. ```json { "rust-analyzer.rustc.source": "discover" } ``` -------------------------------- ### Use Pattern in Lint Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Demonstrates how to use a defined pattern (e.g., 'my_pattern') within an EarlyLintPass to check for specific syntax tree structures in Rust code and trigger a lint. ```rust impl EarlyLintPass for MyAwesomeLint { fn check_expr(&mut self, cx: &EarlyContext, expr: &syntax::ast::Expr) { if my_pattern(expr).is_some() { cx.span_lint( MY_AWESOME_LINT, expr.span, "This is a match for a simple pattern. Well done!", ); } } } ``` -------------------------------- ### Get Expression Type in Clippy Lint Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/type_checking.md Retrieves the type of an expression within a Clippy lint pass using `LateContext` and `TypeckResults`. Ensure you are within a `LateLintPass` context. ```rust pub fn expr_ty(&self, expr: &Expr<'_>) -> Ty<'tcx> ``` -------------------------------- ### Git Source Configuration Source: https://github.com/rust-lang/rust-clippy/blob/master/lintcheck/README.md Configure a crate source from a Git repository, including the repository URL and a specific commit hash, branch, or tag. ```toml puffin = {name = "puffin", git_url = "https://github.com/EmbarkStudios/puffin", git_hash = "02dd4a3"} ``` -------------------------------- ### Configure Disallowed Types in Clippy Source: https://context7.com/rust-lang/rust-clippy/llms.txt Prevent the use of specific types by providing a reason and an alternative. This is useful for guiding developers towards more performant or idiomatic data structures. ```toml # clippy.toml # Disallow specific types [[disallowed-types]] path = "std::collections::LinkedList" reason = "Use Vec or VecDeque instead for better performance" replacement = "std::collections::VecDeque" [[disallowed-types]] path = "std::sync::Mutex" reason = "Use parking_lot::Mutex for better performance" replacement = "parking_lot::Mutex" ``` -------------------------------- ### Generate Lint Code with Author Attribute Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Use the `#[clippy::author]` attribute on Rust code in the playground to generate a starting point for your lint implementation. This is useful for complex patterns. ```rust #[clippy::author] ``` -------------------------------- ### Define Clippy Configuration in TOML Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/configuration.md Use a clippy.toml file to set global lint configurations. The '..' syntax allows extending default list values. ```toml avoid-breaking-exported-api = false disallowed-names = ["toto", "tata", "titi"] ``` ```toml # default of disallowed-names is ["foo", "baz", "quux"] disallowed-names = ["bar", ".."] # -> ["bar", "foo", "baz", "quux"] ``` -------------------------------- ### Clone the Clippy Repository Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/basics.md Initial command to clone a fork of the Clippy repository. ```bash git clone git@github.com:/rust-clippy ``` -------------------------------- ### Update Clippy Subtree in Rust Repository Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/sync.md Execute these commands within the rust directory to sync the Clippy subtree. Ensure you have checked out the latest main branch of rust-lang/rust before starting. ```bash git switch -c clippy-subtree-update ``` ```bash git subtree pull -P src/tools/clippy clippy-upstream master ``` -------------------------------- ### Pattern Matching Example (pat_if_without_else) Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Demonstrates a pattern defined using the pattern! macro for an if expression without an else block, capturing an inner if expression. This pattern is used in a lint check. ```rust pattern!{ pat_if_without_else: Expr = If( _, Block( Expr( If(_, _, ())#inner ) | Semi( If(_, _, ())#inner ) )#then, () ) } ``` -------------------------------- ### Run a Simple Speedtest for a Lint Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/speedtest.md Use this command to perform a basic speed test on a specific lint, such as 'allow_attributes'. It tests all 'ui' tests matching the provided name. ```sh $ SPEEDTEST=ui TESTNAME="allow_attributes" cargo uitest ``` -------------------------------- ### Create a Standalone Lint Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Use this command to generate a new lint file and register it. The category defaults to 'nursery' if not specified. ```bash cargo dev new_lint --name=foo_functions --pass=early --category=pedantic ``` -------------------------------- ### Implement IsMatch for Lit Enum Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Provides an example implementation of the IsMatch trait for matching the Lit enum from the PatternTree against ast::LitKind. It handles Char, Bool, and Int literal kinds. ```rust impl IsMatch for Lit { fn is_match(&self, other: &ast::LitKind) -> bool { match (self, other) { (Lit::Char(i), ast::LitKind::Char(j)) => i.is_match(j), (Lit::Bool(i), ast::LitKind::Bool(j)) => i.is_match(j), (Lit::Int(i), ast::LitKind::Int(j, _)) => i.is_match(j), _ => false, } } } ``` -------------------------------- ### Get Ty Kind for Pattern Matching Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/type_checking.md Retrieves the `TyKind` of a `Ty` struct, enabling pattern matching on different type categories. This is commonly used in Clippy for detailed type analysis. ```rust #[inline] pub fn is_char(self) -> bool { matches!(self.kind(), Char) } ``` -------------------------------- ### Crates-io Source Configuration Source: https://github.com/rust-lang/rust-clippy/blob/master/lintcheck/README.md Define a crate source from crates.io in a TOML file, specifying the crate name and version(s) to check. ```toml bitflags = {name = "bitflags", versions = ['1.2.1']} ``` -------------------------------- ### Struct Field Reordering Suggestion Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/lint_configuration.md This example demonstrates a scenario where reordering struct constructor fields might lead to borrow check errors. It's important to consider side effects of initializer expressions. ```rust struct MyStruct { vector: Vec, length: usize } fn main() { let vector = vec![1,2,3]; MyStruct { length: vector.len(), vector}; } ``` -------------------------------- ### Configure Lint Levels via Command Line Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/usage.md Adjust lint severity levels using -A (allow), -W (warn), and -D (deny) flags. ```bash cargo clippy -- -Aclippy::style -Wclippy::box_default -Dclippy::perf ``` ```bash cargo clippy -- -Dwarnings ``` -------------------------------- ### Rust-like pattern syntax for named submatches Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Presents a pattern with a named submatch (`#foo`) within a function. This example points out the difficulties in assigning names to AST nodes in Rust-like syntax, especially when dealing with implicit structure. ```rust fn test() { 1 #foo } ``` -------------------------------- ### Run Multiple UI Test Files Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/writing_tests.md To run tests for multiple lints simultaneously, provide a comma-separated list of test names to the `TESTNAME` environment variable. ```sh TESTNAME=foo_functions,bar_methods,baz_structs ``` -------------------------------- ### Custom Clippy Attributes for Macros and Types Source: https://context7.com/rust-lang/rust-clippy/llms.txt Applies custom attributes to Rust code to guide Clippy's analysis. Use `#[clippy::format_args]` for macros involving format strings and `#[clippy::has_significant_drop]` for types with important drop behavior. ```rust // Mark macro as a formatting macro for format string lints #[macro_export] #[clippy::format_args] macro_rules! log_info { ($($args:tt)+) => {{ println!("[INFO] {}", format!($($args)+)); }}; } // Mark type as having significant drop for lifetime analysis #[clippy::has_significant_drop] pub struct MutexGuard<'a, T> { lock: &'a Mutex, data: &'a mut T, } impl<'a, T> Drop for MutexGuard<'a, T> { fn drop(&mut self) { // Critical: unlocks mutex on drop self.lock.unlock(); } } ``` -------------------------------- ### Local Dependency Configuration Source: https://github.com/rust-lang/rust-clippy/blob/master/lintcheck/README.md Specify a local crate as a source, useful for linting unpublished or local development versions of a crate. ```toml clippy = {name = "clippy", path = "/home/user/clippy"} ``` -------------------------------- ### Implement early filtering Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Demonstrates using a where clause to perform early filtering during pattern matching. ```rust pattern!{ pat_if_without_else: Expr = If( _, Block( Expr( If(_, _, ())#inner ) | Semi( If(_, _, ())#inner ) )#then, () ) where !in_macro(#then.span); } ``` -------------------------------- ### Configure allowed-prefixes Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/lint_configuration.md Define prefixes allowed when checking for module name repetitions. ```toml allowed-prefixes = [ "to", "from" ] ``` -------------------------------- ### Rust-like pattern syntax for binary operation with 0 Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Demonstrates a pattern syntax for matching binary operations where both operands are `0`. This highlights potential issues with operator precedence when extending Rust syntax for patterns. ```rust 0 #[*:BinOpKind] 0 ``` -------------------------------- ### Travis CI Configuration for Clippy Source: https://context7.com/rust-lang/rust-clippy/llms.txt Set up Clippy checks within Travis CI builds. This configuration specifies the Rust versions to test against and includes steps to run Clippy and tests. ```yaml # .travis.yml language: rust rust: - stable - beta - nightly cache: cargo before_script: - rustup component add clippy script: # Run Clippy and fail on warnings - cargo clippy --all-targets --all-features -- -D warnings # Run tests - cargo test --all-features matrix: allow_failures: - rust: nightly fast_finish: true ``` -------------------------------- ### Configure build.rs in Cargo.toml Source: https://github.com/rust-lang/rust-clippy/blob/master/rustc_tools_util/README.md Specify the build script location in the project configuration. ```toml build = "build.rs" ``` -------------------------------- ### Run Clippy in GitHub Actions Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/continuous_integration/github_actions.md This YAML configuration sets up a GitHub Actions workflow to run Clippy. It checks out the code, sets RUSTFLAGS to fail on warnings, and executes `cargo clippy` with all targets and features enabled on an Ubuntu runner. ```yaml on: push name: Clippy check # Make sure CI fails on all warnings, including Clippy lints env: RUSTFLAGS: "-Dwarnings" jobs: clippy_check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - name: Run Clippy run: cargo clippy --all-targets --all-features ``` -------------------------------- ### Configure Lints with clippy.toml Source: https://context7.com/rust-lang/rust-clippy/llms.txt Defines lint behavior in a dedicated `clippy.toml` file located in the project root. This file allows for fine-grained control over various lint thresholds and settings. ```toml # clippy.toml # Minimum Supported Rust Version - disables lints for newer features msrv = "1.70.0" # Suppress lints that would break public API avoid-breaking-exported-api = true # Disallowed variable names (extends defaults: "foo", "baz", "quux") disallowed-names = ["tmp", "temp", ".."] # Maximum cognitive complexity for functions cognitive-complexity-threshold = 30 # Maximum number of function arguments too-many-arguments-threshold = 10 # Maximum lines per function too-many-lines-threshold = 150 # Allow unwrap in test code allow-unwrap-in-tests = true # Allow expect in test code allow-expect-in-tests = true # Allow dbg! macro in tests allow-dbg-in-tests = true # Allow print macros in tests allow-print-in-tests = true ``` -------------------------------- ### Clippy Development Tools Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/basics.md Utility commands available via 'cargo dev' for common development tasks. ```bash # formats the whole Clippy codebase and all tests cargo dev fmt # register or update lint names/groups/... cargo dev update_lints # create a new lint and register it cargo dev new_lint # deprecate a lint and attempt to remove code relating to it cargo dev deprecate # automatically formatting all code before each commit cargo dev setup git-hook # (experimental) Setup Clippy to work with RustRover cargo dev setup intellij # runs the `dogfood` tests cargo dev dogfood ``` -------------------------------- ### Define Lint in Configuration Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Add your newly created lint to the `define_Conf!` macro in `clippy_config/src/conf.rs`. This registers the lint and its default configuration. ```rust define_Conf! { #[lints( allow_attributes, allow_attributes_without_reason, .. , .. unused_trait_names, use_self, )] msrv: Msrv = Msrv::default(), ... } ``` -------------------------------- ### Benchmark a Pull Request with Lintcheck Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/benchmarking.md Commands to switch to a PR branch, run the benchmark, and compare the results against the master branch. ```bash git fetch upstream pull//head: git switch BRANCHNAME # Bench cargo lintcheck --perf # Get last common commit, checkout that LAST_COMMIT=$(git log BRANCHNAME..master --oneline | tail -1 | cut -c 1-11) git switch -c temporary $LAST_COMMIT # We're now on master # Bench cargo lintcheck --perf perf diff ./target/lintcheck/sources/CRATE/perf.data ./target/lintcheck/sources/CRATE/perf.data.0 ``` -------------------------------- ### Configure Lints in Cargo.toml Source: https://context7.com/rust-lang/rust-clippy/llms.txt Sets project-wide lint configurations within the `Cargo.toml` file. This allows for consistent linting rules across the entire project. ```toml [package] name = "my-project" version = "0.1.0" edition = "2021" rust-version = "1.70" # Clippy respects MSRV for lint suggestions [lints.clippy] enum_glob_use = "deny" unwrap_used = "deny" pedantic = "warn" nursery = "warn" module_name_repetitions = "allow" must_use_candidate = "allow" [lints.rust] unsafe_code = "forbid" ``` -------------------------------- ### Testing Lint Configuration Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Test the default configured value like any normal lint in `tests/ui`. For configuration testing, create a subfolder in `tests/ui-toml` containing a `clippy.toml` file and a Rust file to be linted. ```rust # clippy.toml # Configuration value here ``` -------------------------------- ### Publish clippy_utils Crate Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/release.md Publishes the `clippy_utils` crate to crates.io. This should be done after the Rustup PR has been merged and the sync is complete. Ensure you are on the `upstream/master` branch. ```bash git switch master && git pull upstream master cargo publish --manifest-path clippy_utils/Cargo.toml ``` -------------------------------- ### Syncing changes from rust-lang/rust to Clippy Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/infrastructure/sync.md Commands to push changes from the rust-lang/rust repository to a local Clippy branch using git-subtree. ```bash git subtree push -P src/tools/clippy clippy-local rustup ``` -------------------------------- ### Specify Nightly Toolchain for clippy-utils Source: https://github.com/rust-lang/rust-clippy/blob/master/clippy_utils/README.md Ensure you are using a specific nightly toolchain for clippy-utils. The version should match the one specified in the documentation. ```text nightly-2026-04-16 ``` -------------------------------- ### Apply Clippy Suggestions Source: https://github.com/rust-lang/rust-clippy/blob/master/README.md Automatically apply lint suggestions to the codebase. ```terminal cargo clippy --fix ``` -------------------------------- ### Create a new Cargo lint Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/writing_tests.md Initializes a new lint project structure for Cargo-based lints. ```sh $ cargo dev new_lint --name=foo_categories --pass=late --category=cargo ``` -------------------------------- ### Run Cargo Lintcheck Source: https://github.com/rust-lang/rust-clippy/blob/master/lintcheck/README.md Execute the `cargo lintcheck` command from the repository root to run Clippy on a predefined set of crates. ```bash cargo lintcheck ``` -------------------------------- ### Configure allowed-wildcard-imports Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/lint_configuration.md Specify path segments where wildcard imports are permitted. ```toml allowed-wildcard-imports = [ "utils", "common" ] ``` -------------------------------- ### Analyze macro span contexts Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/common_tools_writing_lints.md Demonstrates how macro expansion affects span contexts, where expressions inside and outside the macro differ. ```rust macro_rules! m { ($a:expr, $b:expr) => { if $a.is_some() { $b; } } } let x: Option = Some(42); m!(x, x.unwrap()); // These spans are not from the same context // x.is_some() is from inside the macro // x.unwrap() is from outside the macro assert_eq!(x_is_some_span.ctxt(), x_unwrap_span.ctxt()); ``` -------------------------------- ### Rust-like pattern syntax for if false condition Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Illustrates a pattern syntax similar to Rust for matching `if` expressions with a `false` condition. This approach aims for user-friendliness but may introduce parsing complexities. ```rust if false { #[*] } ``` -------------------------------- ### Configure MSRV in Cargo.toml Source: https://context7.com/rust-lang/rust-clippy/llms.txt Clippy also respects the `rust-version` field in `Cargo.toml` for MSRV configuration. Ensure this field is set to the minimum supported Rust version. ```toml # Cargo.toml - Clippy also reads rust-version field [package] name = "my-crate" version = "0.1.0" rust-version = "1.65" ``` -------------------------------- ### Inspect AST structure Source: https://github.com/rust-lang/rust-clippy/blob/master/CONTRIBUTING.md Use this command to view the AST structure of a code snippet for easier matching. ```bash rustc -Z unpretty=ast-tree ``` -------------------------------- ### Manual Testing with `cargo dev lint` Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/adding_lints.md Commands to manually test Clippy modifications against a single file or an entire project. ```bash cargo dev lint input.rs ``` ```bash cargo dev lint /path/to/project ``` -------------------------------- ### Generate Boilerplate for EarlyLintPass Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/lint_passes.md Use this command to generate the necessary boilerplate code for a new lint that utilizes the EarlyLintPass. Replace placeholders with your lint's name and chosen category. ```sh $ cargo dev new_lint --name= --pass=early --category= ``` -------------------------------- ### Running Clippy on a Workspace Source: https://context7.com/rust-lang/rust-clippy/llms.txt Command to execute Clippy checks across all crates, targets, and features within a Rust workspace. ```bash cargo clippy --workspace --all-targets --all-features ``` -------------------------------- ### Basic Usage of clippy-driver Source: https://context7.com/rust-lang/rust-clippy/llms.txt Run Clippy directly on Rust source files without using Cargo. This is useful for analyzing individual files or projects not managed by Cargo. ```bash # Basic usage with clippy-driver clippy-driver --edition 2021 src/main.rs ``` -------------------------------- ### Use functional composition for patterns Source: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/proposals/syntax-tree-patterns.md Conceptual syntax for simplifying patterns using function definitions for subpatterns. ```rust pattern!{ fn expr_or_semi(expr: Expr) -> Stmt { Expr(expr) | Semi(expr) } fn if_or_if_let(then: Block, else: Opt) -> Expr { If(_, then, else) | IfLet(then, else) } pat_if_else: Expr = if_or_if_let( _, Block_( Block( expr_or_semi( if_or_if_let(_, _?)#else_ ) )#block_inner )#block ) } ```