Add new lint `obfuscated_if_else`
part of #9100, additional commits could make it work with `then` and `unwrap_or_else` as well
changelog: Add new lint `obfuscated_if_else`
unused_self: respect avoid-breaking-exported-api
```
changelog: [`unused_self`]: Now respects the `avoid-breaking-exported-api` config option
```
Fixes#9195.
I mostly copied the implementation from `unnecessary_wraps`, since I don't have much understanding of rustc internals.
[`box_collection`]: raise warn for all std collections
So far, only [`Vec`, `String`, `HashMap`] were considered.
Extend collection checklist for this lint with:
- `HashSet`
- `VecDeque`
- `LinkedList`
- `BTreeMap`
- `BTreeSet`
- `BinaryHeap`
changelog: [`box_collection`]: raise warn for all std collections
fix [`manual_flatten`] help texts order
fixes #8948
Whenever suggestion for this lint does not fit in one line,
legacy solution has some unexpected/unhandled behavior:
lint will then generate two help messages which seem to be shown in the wrong order.
The second help message in that case will contain the suggestion.
The first help message always refers to a suggestion message,
and **it should adapt** depending on the location of the suggestion:
- inline suggestion within the error/warning message
- suggestion separated into a second help text
This is my first contribution here, so I hope I didn't miss anything for creating this PR.
changelog: fix [`manual_flatten`] help texts order
Whenever suggestion for this lint does not fit in one line,
lint will generate two help messages. The second help message
will always contain the suggestion.
The first help message refers to suggestion message,
and it should adapt depending on the location of the suggestion:
- inline suggestion within the error/warning message
- suggestion separated into second help text
Add `repeated_where_clause_or_trait_bound` lint
I thought I would try and scratch my own itch for #8674.
1. Is comparing the `Res` the correct way for ensuring we have the same trait?
2. Is there a way to get the spans for the bounds and clauses for suggestions?
I tried to use `GenericParam::bounds_span_for_suggestions` but it only gave me an empty span at the end of the spans.
I tried `WhereClause::span_for_predicates_or_empty_place` and it included the comma.
3. Is there a simpler way to get the trait names? I have used the spans of the traits because I didn't see a way to get it off the `Res` or `Def`.
changelog: Add ``[`repeated_where_clause_or_trait_bound`]`` lint.
Fixes for `branches_sharing_code`
fixes#7198fixes#7452fixes#7555fixes#7589
changelog: Don't suggest moving modifications to locals used in any of the condition expressions in `branches_sharing_code`
changelog: Don't suggest moving anything after a local with a significant drop in `branches_sharing_code`
Fix span for or_fun_call
Closes#9033
changelog: [`or_fun_call`]: span points to the `unwrap_or` only instead of through the entire method chain expression
* Don't suggest moving modifications to locals used in any of the condition expressions
* Don't suggest moving anything after a local with a significant drop
Simplify if let statements
fixes: #8288
---
changelog: Allowing [`qustion_mark`] lint to check `if let` expressions that immediatly return unwrapped value
Add test for and fix rust-lang/rust-clippy#9131
This lint seems to have been broken by #98446 -- but of course, there was no clippy test for this case at the time.
`expr.span.ctxt().outer_expn_data()` now has `MacroKind::Derive` instead of `MacroKind::Attr` for something like:
```
#[derive(Clone, Debug)]
pub struct UnderscoreInStruct {
_foo: u32,
}
```
---
changelog: none
closes: https://github.com/rust-lang/rust-clippy/issues/9131
Lint simple expressions in `manual_filter_map`, `manual_find_map`
changelog: Lint simple expressions in [`manual_filter_map`], [`manual_find_map`]
The current comparison rules out `.find(|a| a.is_some()).map(|b| b.unwrap())` because `a` being a reference can effect more complicated expressions, this adds a simple check for that case and adds the necessary derefs
There's some overlap with `option_filter_map` so `lint_filter_some_map_unwrap` now returns a `bool` to indicate it linted
rustc comiler internals helpfully tell us how to fix the issue:
to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`
Fixes ICE in #9041
Finishing touches for `#[expect]` (RFC 2383)
This PR adds documentation and some functionality to rustc's lint passes, to manually fulfill expectations. This is needed for some lints in Clippy. Hopefully, it should be one of the last things before we can move forward with stabilizing this feature.
As part of this PR, I've also updated `clippy::duplicate_mod` to showcase how this new functionality can be used and to ensure that it works correctly.
---
changelog: [`duplicate_mod`]: Fixed lint attribute interaction
r? `@wesleywiser`
cc: https://github.com/rust-lang/rust/issues/97660, https://github.com/rust-lang/rust/issues/85549
And I guess that's it. Here have a magical unicorn 🦄
Fix `undocumented_unsafe_blocks` in closures
fixes#9114
changelog: Fix `undocumented_unsafe_blocks` not checking for comments before the start of a closure
`extra_unused_lifetimes` add FP test case emitting from derived attributes.
Add test to cover for #9014 which is fixed in #9037.
changelog: [`extra_unused_lifetimes`] Add FP test case emitting from derived attributes.
---
Seeing the FP from the test:
```sh
$ git revert -m 1 1d1ae10876
$ TESTNAME=extra_unused_lifetime cargo uitest
```
Add details about how significant drop in match scrutinees can cause deadlocks
Adds more details about how a significant drop in a match scrutinee can cause a deadlock and include link to documentation.
changelog: Add more details to significant drop lint to explicitly show how temporaries in match scrutinees can cause deadlocks.
Fix `#[expect]` for most clippy lints
This PR fixes most `#[expect]` - lint interactions listed in rust-lang/rust#97660. [My comment in the issue](https://github.com/rust-lang/rust/issues/97660#issuecomment-1147269504) shows the current progress (Once this is merged). I plan to work on `duplicate_mod` and `multiple_inherent_impl` and leave the rest for later. I feel like stabilizing the feature is more important than fixing the last few nits, which currently also don't work with `#[allow]`.
---
changelog: none
r? `@Jarcho`
cc: rust-lang/rust#97660
Add lint `explicit_auto_deref` take 2
fixes: #234fixes: #8367fixes: #8380
Still things to do:
* ~~This currently only lints `&*<expr>` when it doesn't trigger `needless_borrow`.~~
* ~~This requires a borrow after a deref to trigger. So `*<expr>` changing `&&T` to `&T` won't be caught.~~
* The `deref` and `deref_mut` trait methods aren't linted.
* Neither ~~field accesses~~, nor method receivers are linted.
* ~~This probably shouldn't lint reborrowing.~~
* Full slicing to deref should probably be handled here as well. e.g. `&vec[..]` when just `&vec` would do
changelog: new lint `explicit_auto_deref`
try reading rust-version from Cargo.toml
Cargo.toml can contain a field `rust-version`, that acts like a MSRV of
clippy.toml file: https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field
This will try to read that field and use it, if the clippy.toml config
has no `msrv` entry
changelog: respect `rust-version` from `Cargo.toml`
closes#8746closes#7765
`trivially_copy_pass_by_ref` fixes
fixes#5953fixes#2961
The fix for #5953 is overly aggressive, but the suggestion is so bad that it's worth the false negatives. Basically three things together:
* It's not obviously wrong
* It compiles
* It may actually work when tested
changelog: Don't lint `trivially_copy_pass_by_ref` when unsafe pointers are used.
changelog: Better track lifetimes when linting `trivially_copy_pass_by_ref`.
compiletest_rs is not meant to test full cargo projects, but instead
only files.
So we need to parse the `Cargo.toml` file ourself and set the
corresponding environment variable. In this case we just set
`CARGO_PKG_RUST_VERSION`, nothing more. But, of course, this can be
extended.
add [`manual_find`] lint for function return case
part of the implementation discussed in #7143
changelog: add [`manual_find`] lint for function return case
feat(new lint): new lint `manual_retain`
close#8097
This PR is a new lint implementation.
This lint checks if the `retain` method is available.
Thank you in advance.
changelog: add new ``[`manual_retain`]`` lint
Suggest `pointer::cast` when possible in `transmute_ptr_to_ref`
fixes#8924
changelog: Suggest casting the pointer for any type containing lifetimes in `transmute_ptr_to_ref`.
changelog: Suggest `pointer::cast` when possible in `transmute_ptr_to_ref`.
enum_variant_names should ignore when all prefixes are _
close#9018
When Enum prefix is only an underscore, we should not issue warnings.
changelog: fix false positive in enum_variant_names
Lint `[single_match]` on `Option` matches
fixes#8928
changelog: did some cleanup of the logic for ``[`single_match`]`` and ``[`single_match_else`]`` which fixes the bug where `Option` matches were not linted unless a wildcard was used for one of the arms.
ignore item in `thread_local!` macro
close#8493
This PR ignores `thread_local` macro in `declare_interior_mutable_const`.
changelog: ignore `thread_local!` macro in `declare_interior_mutable_const`
add vec.capacity() to [`slow_vec_initialization`] detection
fix#8800
for example
```rust
let mut vec1 = Vec::with_capacity(len);
vec1.resize(vec1.capacity(), 0);
let mut vec2 = Vec::with_capacity(len);
vec2.extend(repeat(0).take(vec2.capacity()));
```
will trigger the lint
---
changelog: add `vec.capacity()` to [`slow_vec_initialization`] detection
confirm using chain in collapsible_span_lint_calls
close#8798
This PR fixes false positive when using chain in `collapsible_span_lint_calls`.
changelog: None
Adds more details about how a significant drop in a match scrutinee can
cause a deadlock and include link to documentation. Emits messages
indicating temporaries with significant drops in arms of matches and
message about possible deadlocks/unexpected behavior.
changelog: Add more details to significant drop lint to explicitly show
how temporaries in match scrutinees can cause deadlocks/unexpected
behavior.
feat(fix): ignore `todo!` and `unimplemented!` in `if_same_then_else`
close: #8836
take over: #8853
This PR adds check `todo!` and `unimplemented!` in if_same_then_else.
( I thought `unimplemented` should not be checked as well as todo!.)
Thank you in advance.
changelog: ignore todo! and unimplemented! in if_same_then_else
r? `@Jarcho`
once cell renamings
This PR does the renamings proposed in https://github.com/rust-lang/rust/issues/74465#issuecomment-1153703128
- Move/rename `lazy::{OnceCell, Lazy}` to `cell::{OnceCell, LazyCell}`
- Move/rename `lazy::{SyncOnceCell, SyncLazy}` to `sync::{OnceLock, LazyLock}`
(I used `Lazy...` instead of `...Lazy` as it seems to be more consistent, easier to pronounce, etc)
```@rustbot``` label +T-libs-api -T-libs
feat(lint): add default_iter_empty
close#8915
This PR adds `default_iter_empty` lint.
This lint checks `std::iter::Empty::default()` and replace with `std::iter::empty()`.
Thank you in advance.
---
changelog: add `default_instead_of_iter_empty` lint.
Update description in clippy_lints/src/default_iter_empty.rs
Co-authored-by: Fridtjof Stoldt <xFrednet@gmail.com>
Update clippy_lints/src/default_iter_empty.rs
Co-authored-by: Alex Macleod <alex@macleod.io>
Update clippy_lints/src/default_iter_empty.rs
Co-authored-by: Alex Macleod <alex@macleod.io>
renamed default_iter_empty to default_instead_of_iter_empty
Avoid duplicate messages
add tests for regression
rewrite 'Why is this bad?'
cargo dev fmt
delete default_iter_empty lint in renamed_lint.rs
rewrite a message in the suggestion
cargo dev update_lints --check
Hide irrelevant lines in suggestions to allow for suggestions that are far from each other to be shown
This is an attempt to fix suggestions one part of which is 6 lines or more far from the first. I've noticed "the problem" (of not showing some parts of the suggestion) here: https://github.com/rust-lang/rust/pull/97759#discussion_r889689230.
I'm not sure about the implementation (this big closure is just bad and makes already complicated code even more so), but I want to at least discuss the result.
Here is an example of how this changes the output:
Before:
```text
help: consider enclosing expression in a block
|
3 ~ 'l: { match () { () => break 'l,
4 |
5 |
6 |
7 |
8 |
...
```
After:
```text
help: consider enclosing expression in a block
|
3 ~ 'l: { match () { () => break 'l,
4 |
...
31|
32~ } };
|
```
r? `@estebank`
`@rustbot` label +A-diagnostics +A-suggestion-diagnostics
Rework `branches_sharing_code`
fixes#7378
This changes the lint from checking pairs of blocks, to checking all the blocks at the same time. As such there's almost none of the original code left.
changelog: Don't lint `branches_sharing_code` when using different binding names
Fix some `#[expect]` lint interaction
Fixing the first few lints that aren't caught by `#[expect]`. The root cause of these examples was, that the lint was emitted at the wrong location.
---
changelog: none
r? `@Jarcho`
cc: rust-lang/rust#97660
fix(lint): check const context
close: https://github.com/rust-lang/rust-clippy/issues/8898
This PR fixes a bug in checked_conversions.
Thank you in advance.
changelog: check const context in checked_conversions.
Remove migrate borrowck mode
Closes#58781Closes#43234
# Stabilization proposal
This PR proposes the stabilization of `#![feature(nll)]` and the removal of `-Z borrowck`. Current borrow checking behavior of item bodies is currently done by first infering regions *lexically* and reporting any errors during HIR type checking. If there *are* any errors, then MIR borrowck (NLL) never occurs. If there *aren't* any errors, then MIR borrowck happens and any errors there would be reported. This PR removes the lexical region check of item bodies entirely and only uses MIR borrowck. Because MIR borrowck could never *not* be run for a compiled program, this should not break any programs. It does, however, change diagnostics significantly and allows a slightly larger set of programs to compile.
Tracking issue: #43234
RFC: https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md
Version: 1.63 (2022-06-30 => beta, 2022-08-11 => stable).
## Motivation
Over time, the Rust borrow checker has become "smarter" and thus allowed more programs to compile. There have been three different implementations: AST borrowck, MIR borrowck, and polonius (well, in progress). Additionally, there is the "lexical region resolver", which (roughly) solves the constraints generated through HIR typeck. It is not a full borrow checker, but does emit some errors.
The AST borrowck was the original implementation of the borrow checker and was part of the initially stabilized Rust 1.0. In mid 2017, work began to implement the current MIR borrow checker and that effort ompleted by the end of 2017, for the most part. During 2018, efforts were made to migrate away from the AST borrow checker to the MIR borrow checker - eventually culminating into "migrate" mode - where HIR typeck with lexical region resolving following by MIR borrow checking - being active by default in the 2018 edition.
In early 2019, migrate mode was turned on by default in the 2015 edition as well, but with MIR borrowck errors emitted as warnings. By late 2019, these warnings were upgraded to full errors. This was followed by the complete removal of the AST borrow checker.
In the period since, various errors emitted by the MIR borrow checker have been improved to the point that they are mostly the same or better than those emitted by the lexical region resolver.
While there do remain some degradations in errors (tracked under the [NLL-diagnostics tag](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-diagnostics), those are sufficiently small and rare enough that increased flexibility of MIR borrow check-only is now a worthwhile tradeoff.
## What is stabilized
As said previously, this does not fundamentally change the landscape of accepted programs. However, there are a [few](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-fixed-by-NLL) cases where programs can compile under `feature(nll)`, but not otherwise.
There are two notable patterns that are "fixed" by this stabilization. First, the `scoped_threads` feature, which is a continutation of a pre-1.0 API, can sometimes emit a [weird lifetime error](https://github.com/rust-lang/rust/issues/95527) without NLL. Second, actually seen in the standard library. In the `Extend` impl for `HashMap`, there is an implied bound of `K: 'a` that is available with NLL on but not without - this is utilized in the impl.
As mentioned before, there are a large number of diagnostic differences. Most of them are better, but some are worse. None are serious or happen often enough to need to block this PR. The biggest change is the loss of error code for a number of lifetime errors in favor of more general "lifetime may not live long enough" error. While this may *seem* bad, the former error codes were just attempts to somewhat-arbitrarily bin together lifetime errors of the same type; however, on paper, they end up being roughly the same with roughly the same kinds of solutions.
## What isn't stabilized
This PR does not completely remove the lexical region resolver. In the future, it may be possible to remove that (while still keeping HIR typeck) or to remove it together with HIR typeck.
## Tests
Many test outputs get updated by this PR. However, there are number of tests specifically geared towards NLL under `src/test/ui/nll`
## History
* On 2017-07-14, [tracking issue opened](https://github.com/rust-lang/rust/issues/43234)
* On 2017-07-20, [initial empty MIR pass added](https://github.com/rust-lang/rust/pull/43271)
* On 2017-08-29, [RFC opened](https://github.com/rust-lang/rfcs/pull/2094)
* On 2017-11-16, [Integrate MIR type-checker with NLL](https://github.com/rust-lang/rust/pull/45825)
* On 2017-12-20, [NLL feature complete](https://github.com/rust-lang/rust/pull/46862)
* On 2018-07-07, [Don't run AST borrowck on mir mode](https://github.com/rust-lang/rust/pull/52083)
* On 2018-07-27, [Add migrate mode](https://github.com/rust-lang/rust/pull/52681)
* On 2019-04-22, [Enable migrate mode on 2015 edition](https://github.com/rust-lang/rust/pull/59114)
* On 2019-08-26, [Don't downgrade errors on 2015 edition](https://github.com/rust-lang/rust/pull/64221)
* On 2019-08-27, [Remove AST borrowck](https://github.com/rust-lang/rust/pull/64790)
* Don't lint on `.cloned().flatten()` when `T::Item` doesn't implement `IntoIterator`
* Reduce verbosity of lint message
* Narrow down the scope of the replacement range
List configuration values can now be extended instead of replaced
I've seen some `clippy.toml` files, that have a few additions to the default list of a configuration and then a copy of our default. The list will therefore not be updated, when we add new names. This change should make it simple for new users to append values instead of replacing them.
I'm uncertain if the documentation of the `".."` is apparent. Any suggestions are welcome. I've also check that the lint list displays the examples correctly.
<details>
<summary>Lint list screenshots</summary>
![image](https://user-images.githubusercontent.com/17087237/171999434-393f2f83-09aa-4bab-8b05-bd4973150f27.png)
![image](https://user-images.githubusercontent.com/17087237/171999401-e6942b53-25e6-4b09-89e5-d867c7463156.png)
</details>
---
changelog: enhancement: [`doc_markdown`]: Users can now indicate, that the `doc-valid-idents` should extend the default and not replace it
changelog: enhancement: [`blacklisted-name`]: Users can now indicate, that the `blacklisted-names` should extend the default and not replace it
Closes: #8877
That's it. Have a fantastic weekend to everyone reading this. Here is a cookie 🍪
improve [`for_loops_over_fallibles`] to detect the usage of iter, iter_mut and into_iterator
fix#6762
detects code like
```rust
for _ in option.iter() {
//..
}
```
changelog: Improve [`for_loops_over_fallibles`] to detect `for _ in option.iter() {}` or using `iter_mut()` or `into_iterator()`.
fix(manual_find_map and manual_filter_map): check clone method
close#8920
Added conditional branching when the clone method is used.
Thank you in advance.
---
changelog: check `clone()` and other variant preserving methods in [`manual_find_map`] and [`manual_filter_map`]