Warn about assignments where left-hand side place expression is the same
as right-hand side value expression. For example, warn about assignment in:
```rust
pub struct Event {
id: usize,
x: i32,
y: i32,
}
pub fn copy_position(a: &mut Event, b: &Event) {
a.x = b.x;
a.y = a.y;
}
```
should_impl_trait - ignore methods with lifetime params
Fixes: #5617
changelog: don't lint should_implement_trait when an `Iterator::next` case has explicit parameters
Fix: keep parenthesis for suggestion in `useless_conversion` lint
Note: this lint was previously named `identity_conversion`.
fixes: #4750
changelog: fix parenthesis for `useless_conversion` lint suggestion
Add the other overloadable operations to suspicious_arithmetic_impl
In #2268 I idly mused that the other user-overloadable operations could be added to this lint. Knowing that the lint was arguably incomplete was gnawing at the back of my mind, so I figured that I might as well make this PR, particularly given the change needed was so small.
changelog: Start warning on suspicious implementations of the `BitAnd`, `BitOr`, `BitXor`, `Rem`, `Shl`, and `Shr` traits.
make a bunch of lints texts adhere to rustc dev guide
According to the rustc-dev guide: "The text should be matter of fact and avoid capitalization and periods, unless multiple sentences are needed"
changelog: make some lint output adhere to the rustc-dev guide
enable #[allow(clippy::unsafe_derive_deserialize)]
Before this change this lint could not be allowed as the code we are checking is automatically generated.
changelog: Enable using the `allow` attribute on top of an ADT linted by [`unsafe_derive_deserialize`].
Fixes: #5789
Fix ICE in `loops` module
changelog: Fix ICE related to `needless_collect` when a call to `iter()` was not present.
I went for restoring the old suggestion of `next().is_some()` over `get(0).is_some()` given that `iter()` is not necessarily present (could be e.g. `into_iter()` or `iter_mut()`) and that the old suggestion could change semantics, e.g. a call to `filter()` could be present between `iter()` and the collect part.
Fixes#5872
Check whether locals are too large instead of whether accesses into them are too large
Essentially this stops const prop from attempting to optimize
```rust
let mut x = [0_u8; 5000];
x[42] = 3;
```
I don't expect this to be a perf improvement without #73656 (which is also where the lack of this PR will be a perf regression).
r? @wesleywiser
try_err: Consider Try impl for Poll when generating suggestions
There are two different implementation of `Try` trait for `Poll` type:
`Poll<Result<T, E>>` and `Poll<Option<Result<T, E>>>`. Take them into
account when generating suggestions.
For example, for `Err(e)?` suggest either `return Poll::Ready(Err(e))` or
`return Poll::Ready(Some(Err(e)))` as appropriate.
Fixes#5855
changelog: try_err: Consider Try impl for Poll when generating suggestions
Add derive_ord_xor_partial_ord lint
Fix#1621
Some remarks:
This PR follows the example of the analogous derive_hash_xor_partial_eq lint where possible.
I initially tried using the `match_path` function to identify `Ord` implementation like the derive_hash_xor_partial_eq lint currently does, for `Hash` implementations but that didn't work.
Specifically, the structs at the top level were getting paths that matched `&["$crate", "cmp", "Ord"]` instead of `&["std", "cmp", "Ord"]`. While trying to figure out what to do instead I saw the comment at the top of [clippy_lints/src/utils/paths.rs](f5d429cd76/clippy_lints/src/utils/paths.rs (L5)) that mentioned [this issue](https://github.com/rust-lang/rust-clippy/issues/5393) and suggested to use diagnostic items instead of hardcoded paths whenever possible. I looked for a way to identify `Ord` implementations with diagnostic items, but (possibly because this was the first time I had heard of diagnostic items,) I was unable to find one.
Eventually I tried using `get_trait_def_id` and comparing `DefId` values directly and that seems to work as expected. Maybe there's a better approach however?
changelog: new lint: derive_ord_xor_partial_ord
Handle mapping to Option in `map_flatten` lint
Fixes#4496
The existing [`map_flatten`](https://rust-lang.github.io/rust-clippy/master/index.html#map_flatten) lint suggests changing `expr.map(...).flatten()` to `expr.flat_map(...)` when `expr` is `Iterator`. This PR changes suggestion to `filter_map` instead of `flat_map` when mapping to `Option`, because it is more natural
Also here are some questions:
* If expression has type which implements `Iterator` trait (`match_trait_method(cx, expr, &paths::ITERATOR) == true`), how can I get type of iterator elements? Currently I use return type of closure inside `map`, but probably it is not good way
* I would like to change suggestion range to cover only `.map(...).flatten()`, that is from:
```
let _: Vec<_> = vec![5_i8; 6].into_iter().map(|x| 0..x).flatten().collect();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using `flat_map` instead: `vec![5_i8; 6].into_iter().flat_map
```
to
```
let _: Vec<_> = vec![5_i8; 6].into_iter().map(|x| 0..x).flatten().collect();
^^^^^^^^^^^^^^^^^^^^^^^^ help: try using `flat_map` instead: `.flat_map(|x| 0..x)`
```
Is it ok?
* Is `map_flatten` lint intentionally in `pedantic` category, or could it be moved to `complexity`?
changelog: Handle mapping to Option in [`map_flatten`](https://rust-lang.github.io/rust-clippy/master/index.html#map_flatten) lint
needless_collect: catch x: Vec<_> = iter.collect(); x.into_iter() ...
changelog: Expand the needless_collect lint as suggested in #5627 (WIP).
This PR is WIP because I can't figure out how to make the multi-part suggestion include its changes in the source code (the fixed is identical to the source, despite the lint making suggestions). Aside from that one issue, I think this should be good.
There are two different implementation of Try trait for Poll type;
Poll<Result<T, E>> and Poll<Option<Result<T, E>>>. Take them into
account when generating suggestions.
For example, for Err(e)? suggest either return Poll::Ready(Err(e)) or
return Poll::Ready(Some(Err(e))) as appropriate.
The reason we do not trigger these lints anymore is that clippy sets the mir-opt-level to 0, and the recent changes subtly changed how the const propagator works.
Fix FP for `suspicious_arithmetic_impl` from `suspicious_trait_impl` …
As discussed in #3215, the `suspicious_trait_impl` lint causes too many false positives, as it is complex to find out if binary operations are suspicious or not.
This PR restricts the number of binary operations to at most one, otherwise we don't lint.
This can be seen as very conservative, but at least FP can be reduced to bare minimum.
Fixes: #3215
changelog: limit the `suspicious_arithmetic_impl` lint to one binop, to avoid many FPs
Ignore not really redundant clones of ManuallyDrop
"Redundant" clones of `ManuallyDrop` are sometimes used for the side effect of
invoking the clone, without running the drop implementation of the inner type.
In other words, they aren't really redundant. For example, futures-rs crate:
```rust
#[allow(clippy::redundant_clone)] // The clone here isn't actually redundant.
unsafe fn increase_refcount<T: ArcWake>(data: *const ()) {
// Retain Arc, but don't touch refcount by wrapping in ManuallyDrop
let arc = mem::ManuallyDrop::new(Arc::<T>::from_raw(data as *const T));
// Now increase refcount, but don't drop new refcount either
let _arc_clone: mem::ManuallyDrop<_> = arc.clone();
}
```
changelog: Ignore redundant clone lint for ManuallyDrop.
"Redundant" clones of `ManuallyDrop` are sometimes used for the side effect of
invoking the clone, without running the drop implementation of the inner type.
In other words, they aren't really redundant. For example, futures-rs crate:
```rust
#[allow(clippy::redundant_clone)] // The clone here isn't actually redundant.
unsafe fn increase_refcount<T: ArcWake>(data: *const ()) {
// Retain Arc, but don't touch refcount by wrapping in ManuallyDrop
let arc = mem::ManuallyDrop::new(Arc::<T>::from_raw(data as *const T));
// Now increase refcount, but don't drop new refcount either
let _arc_clone: mem::ManuallyDrop<_> = arc.clone();
}
```
Ignore redundant clone lint for ManuallyDrop.
Panic multiple args
changelog: Fixes bug with `panic` lint reported in #5767. I also did the same changes to the lints for `todo`, `unimplemented` and `unreachable`, so those lints should now also detect calls to those macros with a message.
improve advice in iter_nth_zero
fixes#5783
*Please keep the line below*
changelog: For iter_nth_zero, the "use .next()" replacement advice is on the last line of the code snippet, where it is vulnerable to truncation. Display that advice at the beginning instead.
This lint catches cases where the last statement of a closure expecting
an instance of Ord has a trailing semi-colon. It compiles since the
closure ends up return () which also implements Ord but causes
unexpected results in cases such as sort_by_key.
Fixes#5080
reprise: rebase, update and address all concerns
Rename collapsable_if fix suggestion to "collapse nested if block"
The name "try" is confusing when shown as quick fix by rust-analyzer
changelog: Rename `collapsable_if` fix suggestion to "collapse nested if block"
The "use .next()" replacement advice is on the last line of the code snippet,
where it is vulnerable to truncation. Display that advice at the beginning
instead.
closes#5783
Move range_minus_one to pedantic
This moves the range_minus_one lint to the pedantic category, so there
will not be any warnings emitted by default. This should work around
problems where the suggestion is impossible to resolve due to the range
consumer only accepting a specific range implementation, rather than the
`RangeBounds` trait (see #3307).
While it is possible to work around this by extracting the boundary into
a variable, I don't think clippy should encourage people to disable or
work around lints, but instead the lints should be fixable. So hopefully
this will help until a proper implementation checks what the range is
used for.
*Please keep the line below*
changelog: move [`range_minus_one`] to pedantic
Some accuracy lints for floating point operations
This will add some lints for accuracy on floating point operations suggested by @clarfon in #2040 (fixes#2040).
These are the remaining lints:
- [x] x.powi(2) => x * x
- [x] x.logN() / y.logN() => x.logbase(y)
- [x] x.logbase(E) => x.log()
- [x] x.logbase(10) => x.log10()
- [x] x.logbase(2) => x.log2().
- [x] x * PI / 180 => x.to_radians()
- [x] x * 180 / PI => x.to_degrees()
- [x] (x + 1).log() => x.log_1p()
- [x] sqrt(x * x + y * y) => x.hypot(y)
changelog: Included some accuracy lints for floating point operations
Stabilize `transmute` in constants and statics but not const fn
cc #53605 (leaving issue open so we can add `transmute` to `const fn` later)
Previous attempt: #64011
r? @RalfJung
cc @rust-lang/wg-const-eval
new lint: match_like_matches_macro
Suggests using the `matches!` macro from `std` where appropriate.
`redundant_pattern_matching` has been moved into the `matches` pass to allow suppressing the suggestion where `is_some` and friends are a better replacement.
changelog: new lint: `match_like_matches_macro`
single_match_else - single expr/stmt else block corner case
One approach to fix#3489.
See discussion in the issue.
changelog: single_match_else - single expr/stmt else block corner case fix
Added restriction lint: pattern-type-mismatch
changelog: Added a new restriction lint `pattern-type-mismatch`. This lint is especially helpful for beginners learning about the magic behind pattern matching. (This explanation might be worth to include in the next changelog.)