feat(fix): Do not lint if the target code is inside a loop
close#8753
we consider the following code.
```rust
fn main() {
let vec = vec![1];
let w: Vec<usize> = vec.iter().map(|i| i * i).collect(); // <- once.
for i in 0..2 {
let _ = w.contains(&i);
}
}
```
and the clippy will issue the following warning.
```rust
warning: avoid using `collect()` when not needed
--> src/main.rs:3:51
|
3 | let w: Vec<usize> = vec.iter().map(|i| i * i).collect();
| ^^^^^^^
...
6 | let _ = w.contains(&i);
| -------------- the iterator could be used here instead
|
= note: `#[warn(clippy::needless_collect)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
help: check if the original Iterator contains an element instead of collecting then checking
|
3 ~
4 |
5 | for i in 0..2 {
6 ~ let _ = vec.iter().map(|i| i * i).any(|x| x == i);
```
Rewrite the code as indicated.
```rust
fn main() {
let vec = vec![1];
for i in 0..2 {
let _ = vec.iter().map(|i| i * i).any(|x| x == i); // <- execute `map` every loop.
}
}
```
this code is valid in the compiler, but, it is different from the code before the rewrite.
So, we should not lint, If `collect` is outside of a loop.
Thank you in advance.
---
changelog: Do not lint if the target code is inside a loop in `needless_collect`
Lint `collapsible_str_replace`
fixes#6651
```
changelog: [`collapsible_str_replace`]: create new lint `collapsible_str_replace`
```
If you added a new lint, here's a checklist for things that will be
checked during review or continuous integration.
- \[x] Followed [lint naming conventions][lint_naming]
- \[x] Added passing UI tests (including committed `.stderr` file)
- \[x] `cargo test` passes locally
- \[ ] Executed `cargo dev update_lints`
- \[x] Added lint documentation
- \[x] Run `cargo dev fmt`
Rework `only_used_in_recursion`
fixes#8782fixes#8629fixes#8560fixes#8556
This is a complete rewrite of the lint. This loses some capabilities of the old implementation. Namely the ability to track through tuple and slice patterns, as well as the ability to trace through assignments.
The two reported bugs are fixed with this. One was caused by using the name of the method rather than resolving to the `DefId` of the called method. The second was cause by using the existence of a cycle in the dependency graph to determine whether the parameter was used in recursion even though there were other ways to create a cycle in the graph.
Implementation wise this switches from using a visitor to walking up the tree from every use of each parameter until it has been determined the parameter is used for something other than recursion. This is likely to perform better as it avoids walking the entire function a second time, and it is unlikely to walk up the HIR tree very much. Some cases would perform worse though.
cc `@buttercrab`
changelog: Scale back `only_used_in_recursion` to fix false positives
changelog: Move `only_used_in_recursion` back to `complexity`
Enhance `needless_borrow` to consider trait implementations
The proposed enhancement causes `needless_borrow` to suggest removing `&` from `&e` when `&e` is an argument position requiring trait implementations, and `e` implements the required traits. Example:
```
error: the borrowed expression implements the required traits
--> $DIR/needless_borrow.rs:131:51
|
LL | let _ = std::process::Command::new("ls").args(&["-a", "-l"]).status().unwrap();
| ^^^^^^^^^^^^^ help: change this to: `["-a", "-l"]`
```
r? `@Jarcho`
changelog: Enhance `needless_borrow` to consider trait implementations
unwrap_used and expect_used: trigger on uses of their _err variants
changelog: [`unwrap_used`]: lint uses of `unwrap_err`
changelog: [`expect_used`]: lint uses of `expect_err`
fixes#9331
`transmute_undefined_repr` fix
changelog: Don't lint `transmute_undefined_repr` when the the first field of a `repr(C)` type is compatible with the other type
Fix [`non_ascii_literal`] in tests
changelog: Don't lint [`non_ascii_literal`] when using non-ascii comments in tests
changelog: Don't lint [`non_ascii_literal`] when `allow`ed on tests
closes: #7739closes: #8263
Add new lint [`positional_named_format_parameters`]
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: Add new lint [`positional_named_format_parameters`] to warn when named parameters in format strings are used as positional arguments.
Fix if_let_mutex not checking Mutexes behind refs
Fixes#9193
We can always peel references because we are looking for a method-call, for which autoderef applies.
---
changelog: [`if_let_mutex`]: detect calls to `Mutex::lock()` if mutex is behind a ref
changelog: [`if_let_mutex`]: Add labels to the two instances of the same Mutex that will deadlock
Add lint recommending using `std::iter::once` and `std::iter::empty`
```
changelog: [`iter_once`]: add new lint
changelog: [`iter_empty`]: add new lint
```
fixes#9186
- \[ ] Followed [lint naming conventions][lint_naming]
- \[x] Added passing UI tests (including committed `.stderr` file)
- \[x] `cargo test` passes locally
- \[x] Executed `cargo dev update_lints`
- \[x] Added lint documentation
- \[x] Run `cargo dev fmt`
[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
The lint doesn't really follow the naming conventions. I don't have any better idea so I'm open to suggestions.
Extend `if_then_some_else_none` to also suggest `bool::then_some`
Closes#9094.
changelog: Extend `if_then_some_else_none` to also suggest `bool::then_some`
Add partialeq_to_none lint
Initial implementation of #9275, adding lint `partialeq_to_none`. This is my first time working on `clippy`, so please review carefully.
I'm unsure especially about the `Sugg`, as it covers the entire `BinOp`, instead of just covering one of the sides and the operator (see the multi-line example). I was unsure if pinpointing the suggestion wouldn't be brittle...
changelog: [`PARTIALEQ_TO_NONE`]: Initial commit
`explicit_auto_deref` changes
fixes#9123fixes#9109fixes#9143fixes#9101
This avoid suggesting code which hits a rustc bug. Basically `&{x}` won't use auto-deref if the target type is `Sized`.
changelog: Don't suggest using auto deref for block expressions when the target type is `Sized`
changelog: Include the borrow in the suggestion for `explicit_auto_deref`
changelog: Don't lint `explicit_auto_deref` on `dyn Trait` return
changelog: Don't lint `explicit_auto_deref` when other adjustments are required
changelog: Lint `explicit_auto_deref` in implicit return positions for closures
Fix suggestions for `async` closures in redundant_closure_call
Fixes#9052
changelog: Fix suggestions given by [`redundant_closure_call`] for async closures
- only compare where predicates to trait bounds when generating where
clause specific message to fix#9151
- use comparable_trait_ref to account for trait bound generics to fix#8757
Move [`assertions_on_result_states`] to restriction
Close#9263
This lint causes regression on readability of code and log output. And printing runtime values is not particularly useful for majority of tests which should be reproducible.
changelog: Move [`assertions_on_result_states`] to restriction and don't lint it for unit type
Signed-off-by: tabokie <xy.tao@outlook.com>
unwrap_used: Don't recommend using `expect` when the `expect_used` lint is not allowed
Fixes#9222
```
changelog: [`unwrap_used`]: Don't recommend using `expect` when the `expect_used` lint is not allowed
```
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
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`