Improve `possible_borrower` This PR makes several improvements to `clippy_uitls::mir::possible_borrower`. These changes benefit both `needless_borrow` and `redundant clone`. 1. **Use the compiler's `MaybeStorageLive` analysis** I could spot not functional differences between the one in the compiler and the one in Clippy's repository. So, I removed the latter in favor of the the former. 2. **Make `PossibleBorrower` a dataflow analysis instead of a visitor** The main benefit of this change is that allows `possible_borrower` to take advantage of statements' relative locations, which is easier to do in an analysis than in a visitor. This is easier to illustrate with an example, so consider this one: ```rust fn foo(cx: &LateContext<'_>, lint: &'static Lint) { cx.struct_span_lint(lint, rustc_span::Span::default(), "", |diag| diag.note(&String::new())); // ^ } ``` We would like to flag the `&` pointed to by the `^` for removal. `foo`'s MIR begins like this: ```rust fn span_lint::foo::{closure#0}(_1: [closure@$DIR/needless_borrow.rs:396:68: 396:74], _2: &mut rustc_errors::diagnostic_builder::DiagnosticBuilder<'_, ()>) -> &mut rustc_errors::diagnostic_builder::DiagnosticBuilder<'_, ()> { debug diag => _2; // in scope 0 at $DIR/needless_borrow.rs:396:69: 396:73 let mut _0: &mut rustc_errors::diagnostic_builder::DiagnosticBuilder<'_, ()>; // return place in scope 0 at $DIR/needless_borrow.rs:396:75: 396:75 let mut _3: &mut rustc_errors::diagnostic_builder::DiagnosticBuilder<'_, ()>; // in scope 0 at $DIR/needless_borrow.rs:396:75: 396:100 let mut _4: &mut rustc_errors::diagnostic_builder::DiagnosticBuilder<'_, ()>; // in scope 0 at $DIR/needless_borrow.rs:396:75: 396:100 let mut _5: &std::string::String; // in scope 0 at $DIR/needless_borrow.rs:396:85: 396:99 let _6: std::string::String; // in scope 0 at $DIR/needless_borrow.rs:396:86: 396:99 bb0: { StorageLive(_3); // scope 0 at $DIR/needless_borrow.rs:396:75: 396:100 StorageLive(_4); // scope 0 at $DIR/needless_borrow.rs:396:75: 396:100 _4 = &mut (*_2); // scope 0 at $DIR/needless_borrow.rs:396:75: 396:100 StorageLive(_5); // scope 0 at $DIR/needless_borrow.rs:396:85: 396:99 StorageLive(_6); // scope 0 at $DIR/needless_borrow.rs:396:86: 396:99 _6 = std::string::String::new() -> bb1; // scope 0 at $DIR/needless_borrow.rs:396:86: 396:99 // mir::Constant // + span: $DIR/needless_borrow.rs:396:86: 396:97 // + literal: Const { ty: fn() -> std::string::String {std::string::String::new}, val: Value(<ZST>) } } bb1: { _5 = &_6; // scope 0 at $DIR/needless_borrow.rs:396:85: 396:99 _3 = rustc_errors::diagnostic_builder::DiagnosticBuilder::<'_, ()>::note::<&std::string::String>(move _4, move _5) -> [return: bb2, unwind: bb4]; // scope 0 at $DIR/needless_borrow.rs:396:75: 396:100 // mir::Constant // + span: $DIR/needless_borrow.rs:396:80: 396:84 // + literal: Const { ty: for<'a> fn(&'a mut rustc_errors::diagnostic_builder::DiagnosticBuilder<'_, ()>, &std::string::String) -> &'a mut rustc_errors::diagnostic_builder::DiagnosticBuilder<'_, ()> {rustc_errors::diagnostic_builder::DiagnosticBuilder::<'_, ()>::note::<&std::string::String>}, val: Value(<ZST>) } } ``` The call to `diag.note` appears in `bb1` on the line beginning with `_3 =`. The `String` is owned by `_6`. So, in the call to `diag.note`, we would like to know whether there are any references to `_6` besides `_5`. The old, visitor approach did not consider the relative locations of statements. So all borrows were treated the same, *even if they occurred after the location of interest*. For example, before the `_3 = ...` call, the possible borrowers of `_6` would be just `_5`. But after the call, the possible borrowers would include `_2`, `_3`, and `_4`. So, in a sense, the call from which we are try to remove the needless borrow is trying to prevent us from removing the needless borrow(!). With an analysis, things do not get so muddled. We can determine the set of possible borrowers at any specific location, e.g., using a `ResultsCursor`. 3. **Change `only_borrowers` to `at_most_borrowers`** `possible_borrowers` exposed a function `only_borrowers` that determined whether the borrowers of some local were *exactly* some set `S`. But, from what I can tell, this was overkill. For the lints that currently use `possible_borrower` (`needless_borrow` and `redundant_clone`), all we really want to know is whether there are borrowers *other than* those in `S`. (Put another way, we only care about the subset relation in one direction.) The new function `at_most_borrowers` takes this more tailored approach. 4. **Compute relations "on the fly" rather than using `transitive_relation`** The visitor would compute and store the transitive closure of the possible borrower relation for an entire MIR body. But with an analysis, there is effectively a different possible borrower relation at each location in the body. Computing and storing a transitive closure at each location would not be practical. So the new approach is to compute the transitive closure on the fly, as needed. But the new approach might actually be more efficient, as I now explain. In all current uses of `at_most_borrowers` (previously `only_borrowers`), the size of the set of borrowers `S` is at most 2. So you need only check at most three borrowers to determine whether the subset relation holds. That is, once you have found a third borrower, you can stop, since you know the relation cannot hold. Note that `transitive_relation` is still used by `clippy_uitls::mir::possible_origin` (a kind of "subroutine" of `possible_borrower`). cc: `@Jarcho` --- changelog: [`needless_borrow`], [`redundant_clone`]: Now track references better and detect more cases [#9701](https://github.com/rust-lang/rust-clippy/pull/9701) <!-- changelog_checked -->
Clippy
A collection of lints to catch common mistakes and improve your Rust code.
There are over 550 lints included in this crate!
Lints are divided into categories, each with a default lint level.
You can choose how much Clippy is supposed to annoy help you by changing the lint level by category.
Category | Description | Default level |
---|---|---|
clippy::all |
all lints that are on by default (correctness, suspicious, style, complexity, perf) | warn/deny |
clippy::correctness |
code that is outright wrong or useless | deny |
clippy::suspicious |
code that is most likely wrong or useless | warn |
clippy::style |
code that should be written in a more idiomatic way | warn |
clippy::complexity |
code that does something simple but in a complex way | warn |
clippy::perf |
code that can be written to run faster | warn |
clippy::pedantic |
lints which are rather strict or have occasional false positives | allow |
clippy::nursery |
new lints that are still under development | allow |
clippy::cargo |
lints for the cargo manifest | allow |
More to come, please file an issue if you have ideas!
The lint list also contains "restriction lints", which are for things which are usually not considered "bad", but may be useful to turn on in specific cases. These should be used very selectively, if at all.
Table of contents:
Usage
Below are instructions on how to use Clippy as a cargo subcommand, in projects that do not use cargo, or in Travis CI.
As a cargo subcommand (cargo clippy
)
One way to use Clippy is by installing Clippy through rustup as a cargo subcommand.
Step 1: Install Rustup
You can install Rustup on supported platforms. This will help us install Clippy and its dependencies.
If you already have Rustup installed, update to ensure you have the latest Rustup and compiler:
rustup update
Step 2: Install Clippy
Once you have rustup and the latest stable release (at least Rust 1.29) installed, run the following command:
rustup component add clippy
If it says that it can't find the clippy
component, please run rustup self update
.
Step 3: Run Clippy
Now you can run Clippy by invoking the following command:
cargo clippy
Automatically applying Clippy suggestions
Clippy can automatically apply some lint suggestions, just like the compiler.
cargo clippy --fix
Workspaces
All the usual workspace options should work with Clippy. For example the following command
will run Clippy on the example
crate:
cargo clippy -p example
As with cargo check
, this includes dependencies that are members of the workspace, like path dependencies.
If you want to run Clippy only on the given crate, use the --no-deps
option like this:
cargo clippy -p example -- --no-deps
Using clippy-driver
Clippy can also be used in projects that do not use cargo. To do so, run clippy-driver
with the same arguments you use for rustc
. For example:
clippy-driver --edition 2018 -Cpanic=abort foo.rs
Note that clippy-driver
is designed for running Clippy only and should not be used as a general
replacement for rustc
. clippy-driver
may produce artifacts that are not optimized as expected,
for example.
Travis CI
You can add Clippy to Travis CI in the same way you use it locally:
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.
Note that adding -D warnings
will cause your build to fail if any warnings are found in your code.
That includes warnings found by rustc (e.g. dead_code
, etc.). If you want to avoid this and only cause
an error for Clippy warnings, use #![deny(clippy::all)]
in your code or -D clippy::all
on the command
line. (You can swap clippy::all
with the specific lint category you are targeting.)
Configuration
Allowing/denying lints
You can add options to your code to allow
/warn
/deny
Clippy lints:
-
the whole set of
Warn
lints using theclippy
lint group (#![deny(clippy::all)]
). Note thatrustc
has additional lint groups. -
all lints using both the
clippy
andclippy::pedantic
lint groups (#![deny(clippy::all)]
,#![deny(clippy::pedantic)]
). Note thatclippy::pedantic
contains some very aggressive lints prone to false positives. -
only some lints (
#![deny(clippy::single_match, clippy::box_vec)]
, etc.) -
allow
/warn
/deny
can be limited to a single function or module using#[allow(...)]
, etc.
Note: allow
means to suppress the lint for your code. With warn
the lint
will only emit a warning, while with deny
the lint will emit an error, when
triggering for your code. An error causes clippy to exit with an error code, so
is useful in scripts like CI/CD.
If you do not want to include your lint levels in your code, you can globally enable/disable lints by passing extra flags to Clippy during the run:
To allow lint_name
, run
cargo clippy -- -A clippy::lint_name
And to warn on lint_name
, run
cargo clippy -- -W clippy::lint_name
This also works with lint groups. For example, you can run Clippy with warnings for all lints enabled:
cargo clippy -- -W clippy::pedantic
If you care only about a single lint, you can allow all others and then explicitly warn on the lint(s) you are interested in:
cargo clippy -- -A clippy::all -W clippy::useless_format -W clippy::...
Configure the behavior of some lints
Some lints can be configured in a TOML file named clippy.toml
or .clippy.toml
. It contains a basic variable = value
mapping e.g.
avoid-breaking-exported-api = false
disallowed-names = ["toto", "tata", "titi"]
cognitive-complexity-threshold = 30
See the list of configurable lints, the lint descriptions contain the names and meanings of these configuration variables.
Note
clippy.toml
or.clippy.toml
cannot be used to allow/deny lints.
To deactivate the “for further information visit lint-link” message you can
define the CLIPPY_DISABLE_DOCS_LINKS
environment variable.
Specifying the minimum supported Rust version
Projects that intend to support old versions of Rust can disable lints pertaining to newer features by specifying the minimum supported Rust version (MSRV) in the clippy configuration file.
msrv = "1.30.0"
Alternatively, the rust-version
field
in the Cargo.toml
can be used.
# Cargo.toml
rust-version = "1.30"
The MSRV can also be specified as an attribute, like below.
#![feature(custom_inner_attributes)]
#![clippy::msrv = "1.30.0"]
fn main() {
...
}
You can also omit the patch version when specifying the MSRV, so msrv = 1.30
is equivalent to msrv = 1.30.0
.
Note: custom_inner_attributes
is an unstable feature, so it has to be enabled explicitly.
Lints that recognize this configuration option can be found here
Contributing
If you want to contribute to Clippy, you can find more information in CONTRIBUTING.md.
License
Copyright 2014-2022 The Rust Project Developers
Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. Files in the project may not be copied, modified, or distributed except according to those terms.