Add lint panic in result
### Change
Adding a new "restriction" lint that will emit a warning when using "panic", "unimplemented" or "unreachable" in a function of type option/result.
### Motivation
Some codebases must avoid crashes at all costs, and hence functions of type option/result must return an error instead of crashing.
### Test plan
Running:
TESTNAME=panic_in_result cargo uitest ---
changelog: none
improve the suggestion of the lint `unit-arg`
Fixes#5823Fixes#6015
Changes
```
help: move the expression in front of the call...
|
3 | g();
|
help: ...and use a unit literal instead
|
3 | o.map_or((), |i| f(i))
|
```
into
```
help: move the expression in front of the call and replace it with the unit literal `()`
|
3 | g();
| o.map_or((), |i| f(i))
|
```
changelog: improve the suggestion of the lint `unit-arg`
We no longer lint assignments to const item fields in the
`temporary_assignment` lint, since this is now covered by the
`CONST_ITEM_MUTATION` lint.
Additionally, we `#![allow(const_item_mutation)]` in the
`borrow_interior_mutable_const.rs` test. Clippy UI tests are run with
`-D warnings`, which seems to cause builtin lints to prevent Clippy
lints from running.
Fix FP in `same_item_push`
Don't emit a lint when the pushed item doesn't have Clone trait
Fix#5979
changelog: Fix FP in `same_item_push` not to emit a lint when the pushed item doesn't have Clone trait
useless_attribute: Permit wildcard_imports and enum_glob_use
Fixes#5918
changelog: `useless_attribute`: Permit `wildcard_imports` and `enum_glob_use` on `use` items
default_trait_access: Fix wrong suggestion
https://github.com/rust-lang/rust-clippy/issues/5975#issuecomment-683751131
> I think the underlying problem is clippy suggests code with complete parameters, not clippy triggers this lint even for complex types. AFAIK, If code compiles with `Default::default`, it doesn't need to specify any parameters, as type inference is working. (So, in this case, `default_trait_access` should suggest `RefCell::default`.)
Fixes#5975Fixes#5990
changelog: `default_trait_access`: fixed wrong suggestion
Add a lint for an async block/closure that yields a type that is itself awaitable.
This catches bugs of the form
tokio::spawn(async move {
let f = some_async_thing();
f // Oh no I forgot to await f so that work will never complete.
});
See the two XXXkhuey comments and the unfixed `_l` structure for things that need more thought.
*Please keep the line below*
changelog: none
This catches bugs of the form
tokio::spawn(async move {
let f = some_async_thing();
f // Oh no I forgot to await f so that work will never complete.
});
Fix FP in `to_string_in_display`
Don't emit a lint when `.to_string()` on anything that is not `self`
Fix#5967
changelog: Fix FP in `to_string_in_display` when calling `.to_string()` on anything that is not `self`
Corrects the float_equality_without_abs lint
Fixes an issue in the `float_equality_without_abs` lint. The lint suggestion was configured in a way that it lints the whole error and not just the subtraction part. In the current configuration the lint would suggest to change the expression in a wrong way, e.g.
```rust
let _ = (a - b) < f32::EPSILON; // before
let _ = (a - b).abs(); // after
```
This was dicovered by @flip1995. (See discussion of PR #5952).
Also the suggestion is now formatted via `utils::sugg`.
changelog: none
Fix `let_and_return` bad suggestion
Add a cast to the suggestion when the return expression has adjustments.
These adjustments are lost when the suggestion is applied.
This is similar to the problem in issue #4437.
Closes#5729
changelog: Fix `let_and_return` bad suggestion
Fix fp in `borrow_interior_mutable_const`
fixes#5796
changelog: fix false positive in `borrow_interior_mutable_const` when referencing a field behind a pointer.
Fix incorrect suggestion when `clone_on_ref_ptr` is triggered in macros
In the lint `clone_on_ref_ptr`, if the `span` is in a macro, don't expand it for suggestion.
Fixes: #2076
changelog: none
r? @ebroto
Add a cast to the suggestion when the return expression has adjustments.
These adjustments are lost when the suggestion is applied.
This is similar to the problem in issue #4437.
Closes#5729
Don't lint if it has always inline attribute
Don't trigger the lint `trivially_copy_pass_by_ref` if it has `#[inline(always)]` attribute.
Note: I am not particularly familiar with `inline` impacts, so I implemented this the way that if only `#[inline]` attribute is here (without `always`), the lint will still trigger. Also, it will still trigger if it has `#[inline(never)]`.
Just tell me if it sounds too much conservative.
Fixes: #5876
changelog: none
Prelude imports are exempt from wildcard import warnings. Until now only
imports of the form
```
use ...::prelude::*;
```
were considered. This change makes it so that the segment `prelude` can
show up anywhere, for instance:
```
use ...::prelude::v1::*;
```
Fixes#5917
Fix false positive in `PRECEDENCE` lint
Extend the lint to handle chains of methods combined with unary negation.
Closes#5924
changelog: Fix false negative in `PRECEDENCE` lint
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.