Commit graph

14929 commits

Author SHA1 Message Date
relrelb
f0e586c251 Suggest Entry::or_default for Entry::or_insert(Default::default())
Unlike past similar work done in #6228, expand the existing `or_fun_call`
lint to detect `or_insert` calls with a `T::new()` or `T::default()`
argument, much like currently done for `unwrap_or` calls. In that case,
suggest the use of `or_default`, which is more idiomatic.

Note that even with this change, `or_insert_with(T::default)` calls
aren't detected as candidates for `or_default()`, in the same manner
that currently `unwrap_or_else(T::default)` calls aren't detected as
candidates for `unwrap_or_default()`.

Also, as a nearby cleanup, change `KNOW_TYPES` from `static` to `const`,
since as far as I understand it's preferred (should Clippy have a lint
for that?).

Fixes #3812.
2022-09-04 23:43:17 +03:00
bors
90804d35fe Auto merge of #9425 - kraktus:patch-1, r=xFrednet
fix wording for `derivable_impls`

While looking at the explanation as to why this lint was not automatically applicable, found the explanation a bit clunky grammatically.

 Feel free to close if you consider the wording was correct in the first place.

changelog: none
2022-09-04 15:32:09 +00:00
kraktus
2cc20e3245 fix wording for derivable_impls 2022-09-04 17:20:54 +02:00
bors
46b7cb69cb Auto merge of #9424 - mikerite:fix-9351-4, r=xFrednet
Fix `unnecessary_to_owned` false positive

Fixes #9351.

Note that this commit reworks that fix for #9317. The change
is to check that the type implements `AsRef<str>` before regarding
`to_string` as an equivalent of `to_owned`. This was suggested
by Jarcho in the #9317 issue comments.

The benefit of this is that it moves some complexity out of
`check_other_call_arg` and simplifies the module as a whole.

changelog: FP: [`unnecessary_to_owned`]: No longer lints, if type change would cause errors in the caller function
2022-09-04 15:14:58 +00:00
Michael Wright
750a2d57bd Fix unnecessary_to_owned false positive
Fixes #9351.

Note that this commit reworks that fix for #9317. The change
is to check that the type implements `AsRef<str>` before regarding
`to_string` as an equivalent of `to_owned`. This was suggested
by Jarcho in the #9317 issue comments.

The benefit of this is that it moves some complexity out of
`check_other_call_arg` and simplifies the module as a whole.
2022-09-03 17:00:44 +02:00
bors
99ab5fe53a Auto merge of #9400 - lukaslueg:approx_large_enum, r=llogiq
Use `approx_ty_size` for `large_enum_variant`

This builds upon #9373 to use the approximate size of each variant for `large_enum_variant`. This allows us to lint in situations where an `enum` contains generics but is still guaranteed to have a large variant on an at-least basis, e.g. with `(T, [u8; 512])`.

* I've changed the wording from "is ... bytes" to "contains at least" because
  * the size is now an approximate lower bound (e.g. `512` in the example above). The actual size is larger due to `T`, including due to `T`'s memory layout.
  * the discriminant is not taken into account in the message. This comes up with variants like `A(T)`, which are "is at least 0 bytes" otherwise, which may be misleading.
* If the second-largest variant has no fields, there is a special case "carries no data" instead of "is at least 0 bytes".
* A variant like `A(T)` is "at least 0 bytes", which is technically true, yet we don't distinguish between "indeterminate" and truly "ZST".
* The generics-tests that were there before now lint while they didn't lint before. AFAICS this is correct.

I guess the above is correct-ish. However, I use the `SubstsRef` that I got via `cx.tcx.type_of(item.def_id)` to solve for generics in the variants. Is this even applicable, since we start from an - [ ] `ItemKind`?

changelog: none
2022-09-03 07:34:42 +00:00
Lukas Lueg
584000a792 Use approx_ty_size for large_enum_variant 2022-09-03 00:16:28 +02:00
bors
30e4532153 Auto merge of #8952 - rust-lang:explain, r=xFredNet
add `--explain` subcommand

This closes #8291.

---

changelog: add `cargo clippy -- --explain <lintname>` subcommand
2022-09-02 20:27:42 +00:00
Andre Bogus
ad72aee93c add --explain subcommand 2022-09-02 22:17:39 +02:00
bors
c36696ac02 Auto merge of #9418 - lukaslueg:issue9415, r=llogiq
Fix `mut_mutex_lock` when Mutex is behind immutable deref

I *think* the problem here is the `if let ty::Ref(_, _, Mutability::Mut) = cx.typeck_results().expr_ty(recv).kind()` line tries to check if the `Mutex` can be mutably borrowed (there already is a test for `Arc<Mutex<_>>`), but gets bamboozled by the `&mut Arc` indirection. And I *think* checking the deref-adjustment to filter immutable-adjust (the deref through the `Arc`, starting from `&mut Arc`) is the correct fix.

Fixes #9415

changelog: Fix `mut_mutex_lock` when Mutex is behind immutable deref
2022-09-02 18:54:06 +00:00
Lukas Lueg
ffc75af4cd Fix mut_mutex_lock for Mutex behind imm deref
Fixes #9415
2022-09-02 20:39:47 +02:00
bors
958a9cf297 Auto merge of #9417 - Jarcho:ice_9414, r=Alexendoo
Don't use `hir_ty_to_ty` in `result_large_err`

fixes #9414

This occurs starting with 2022-09-01. I checked that this does fix the ICE on rust-lang/rust@9353538. Not sure which pr caused the late-bound region to leak through `hir_ty_to_ty`.

changelog: None
2022-09-02 18:07:38 +00:00
Jason Newcomb
bd70ccf915 Don't use hir_ty_to_ty in result_large_err as it sometimes leaves late-bound lifetimes. 2022-09-02 13:40:35 -04:00
bors
334be18a74 Auto merge of #9412 - xFrednet:jst-r-bool-to-int-lint, r=xFrednet
New lint `bool_to_int_with_if`

This is a rebased version of https://github.com/rust-lang/rust-clippy/pull/9086 I could sadly not push directly push to the PR branch as it's protected.

The lint implementation comes from `@jst-r.` Thank you for the work you put into this :)

---

Closes: https://github.com/rust-lang/rust-clippy/issues/8131
Closes: https://github.com/rust-lang/rust-clippy/pull/9086

changelog: Add lint [`bool_to_int_with_if`]

r? `@ghost`
2022-09-01 21:39:06 +00:00
Dmitrii Lavrov
b1f86a49ea
New lint bool_to_int_with_if 2022-09-01 23:23:56 +02:00
bors
a80e278036 Auto merge of #9404 - lukaslueg:issue9402, r=giraffate
Fix `suboptimal_float` not linting on `{const}.powf({const})`

There used to be an early return if the receiver was an effective const but the method was not linted, not taking into account later cases where the receiver and the arguments are both effective consts for different methods. Removed the early return.

Fixes #9402
Fixes #9201

changelog: Fix `suboptimal_flops`, `imprecise_flops` not linting on `{const}.powf({const})` et al
2022-09-01 13:18:17 +00:00
Lukas Lueg
6e14e60af4 Fix {subopt,imprec}_float not lint const.*(const)
Fixes #9402
Fixes #9201
2022-09-01 12:51:13 +02:00
bors
291f75e1fb Auto merge of #9406 - Jarcho:unescape_ice, r=Manishearth
Correctly handle unescape warnings

fixes #9405

changelog: Fix ICE when format literals raise compiler warnings
2022-09-01 04:12:00 +00:00
Jason Newcomb
d4a0785464 Correctly handle unescape warnings 2022-09-01 00:00:37 -04:00
bors
c782767d47 Auto merge of #9403 - softmoth:wild_err_expect, r=Alexendoo
match_wild_err_arm: Fix typo in note text

changelog: [`match_wild_err_arm`]: fix typo in note text
2022-08-31 13:53:39 +00:00
Tim Siegel
28a055dcea
match_wild_err_arm: Fix typo in note text 2022-08-31 09:09:11 -04:00
bors
f51aade56f Auto merge of #9397 - Jarcho:trait_dup_order, r=dswij
Fix the emission order of `trait_duplication_in_bounds`

Makes the lint emit in source order rather than whatever order the hash map happens to be in. This is currently blocking the sync into rustc.

changelog: None
2022-08-31 08:07:33 +00:00
bors
09e4659a86 Auto merge of #9373 - lukaslueg:result_large_err, r=Alexendoo
Initial implementation `result_large_err`

This is a shot at #6560, #4652, and #3884. The lint checks for `Result` being returned from functions/methods where the `Err` variant is larger than a configurable threshold (the default of which is 128 bytes). There has been some discussion around this, which I'll try to quickly summarize:

* A large `Err`-variant may force an equally large `Result` if `Err` is actually bigger than `Ok`.
* There is a cost involved in large `Result`, as LLVM may choose to `memcpy` them around above a certain size.
* We usually expect the `Err` variant to be seldomly used, but pay the cost every time.
* `Result` returned from library code has a high chance of bubbling up the call stack, getting stuffed into `MyLibError { IoError(std::io::Error), ParseError(parselib::Error), ...}`, exacerbating the problem.

This PR deliberately does not take into account comparing the `Ok` to the `Err` variant (e.g. a ratio, or one being larger than the other). Rather we choose an absolute threshold for `Err`'s size, above which we warn. The reason for this is that `Err`s probably get `map_err`'ed further up the call stack, and we can't draw conclusions from the ratio at the point where the `Result` is returned. A relative threshold would also be less predictable, while not accounting for the cost of LLVM being forced to generate less efficient code if the `Err`-variant is _large_ in absolute terms.

We lint private functions as well as public functions, as the perf-cost applies to in-crate code as well.

In order to account for type-parameters, I conjured up `fn approx_ty_size`. The function relies on `LateContext::layout_of` to compute the actual size, and in case of failure (e.g. due to generics) tries to come up with an "at least size". In the latter case, the size of obviously wrong, but the inspected size certainly can't be smaller than that. Please give the approach a heavy dose of review, as I'm not actually familiar with the type-system at all (read: I have no idea what I'm doing).

The approach does, however flimsy it is, allow us to successfully lint situations like

```rust
pub union UnionError<T: Copy> {
    _maybe: T,
    _or_perhaps_even: (T, [u8; 512]),
}

// We know `UnionError<T>` will be at least 512 bytes, no matter what `T` is
pub fn param_large_union<T: Copy>() -> Result<(), UnionError<T>> {
    Ok(())
}
```

I've given some refactoring to `functions/result_unit_err.rs` to re-use some bits. This is also the groundwork for #6409

The default threshold is 128 because of https://github.com/rust-lang/rust-clippy/issues/4652#issue-505670554

`lintcheck` does not trigger this lint for a threshold of 128. It does warn for 64, though.

The suggestion currently is the following, which is just a placeholder for discussion to be had. I did have the computed size in a `span_label`. However, that might cause both ui-tests here and lints elsewhere to become flaky wrt to their output (as the size is platform dependent).

```
error: the `Err`-variant returned via this `Result` is very large
  --> $DIR/result_large_err.rs:36:34
   |
LL | pub fn param_large_error<R>() -> Result<(), (u128, R, FullyDefinedLargeError)> {
   |                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The `Err` variant is unusually large, at least 128 bytes
```

changelog: Add [`result_large_err`] lint
2022-08-30 18:20:45 +00:00
Lukas Lueg
66a97055b2 Initial implementation of result_large_err 2022-08-30 17:39:40 +02:00
Jason Newcomb
19ef04ff5d Fix the order of trait_duplication_in_bounds
* Emit the lint in source order
* Make suggestions with multiple traits be in source order rather than alphabetical
2022-08-30 00:33:56 -04:00
bors
4df6032100 Auto merge of #9394 - lukaslueg:issue9391, r=Jarcho
Fix missing parens in `suboptimal_flops` suggestion

Fixes #9391. The problem is simple enough, I didn't check if the same problem occurs elsewhere, though.

changelog: fix missing parenthesis in `suboptimal_flops` suggestion
2022-08-30 00:37:45 +00:00
Lukas Lueg
9ffc5a5c8d Fix more parens for suboptimal_flops suggs 2022-08-29 22:36:11 +02:00
bors
e1ecdb621c Auto merge of #9395 - Alexendoo:suspicious-to-owned-test, r=Manishearth
Fix `suspicious_to_owned` test when `c_char` is `u8`

e.g. on aarch64 linux

changelog: none
2022-08-29 19:26:22 +00:00
bors
e9f7ce1f91 Auto merge of #9247 - clubby789:raw_slice_pointer_cast, r=Alexendoo
New lint: Raw slice pointer cast

Adds a lint to check for a raw slice being created and cast back to a pointer, suggesting `ptr::slice_from_raw_parts`, to identify UB such as https://github.com/SimonSapin/rust-typed-arena/pull/54.
```
changelog: [`cast_slice_from_raw_parts`]: Add lint to check for `slice::from_raw_parts(.., ..) as *const _`
```
2022-08-29 18:07:50 +00:00
clubby789
cc9f203543
Update clippy_lints/src/casts/mod.rs
Co-authored-by: Alex Macleod <alex@macleod.io>
2022-08-29 15:17:23 +01:00
clubby789
30979bfe83 Add lint cast_slice_from_raw_parts 2022-08-29 14:10:17 +01:00
Alex Macleod
c5a82304cf Fix suspicious_to_owned test when c_char is u8 2022-08-29 12:17:08 +00:00
Lukas Lueg
26a6891925 Fix missing parens in suboptimal_flops sugg
Fixes #9391
2022-08-29 13:56:03 +02:00
bors
58bbb1a95d Auto merge of #9385 - rust-lang:unnecessary-cast-remove-parens, r=Alexendoo
remove parenthesis from `unnecessary_cast` suggestion

This fixes #9380.

---

changelog: none
2022-08-29 11:49:08 +00:00
bors
28ec27b33a Auto merge of #9388 - Jarcho:rustup, r=Jarcho
Rustup

Hopefully this is done right.

changelog: None
2022-08-29 01:51:23 +00:00
Jason Newcomb
e5507390b7 Disable incremental compilation on CI 2022-08-28 19:22:46 -04:00
bors
4e31c8cab4 Auto merge of #9389 - lukaslueg:penmacro, r=llogiq
Don't lint literal `None` from expansion

This addresses https://github.com/rust-lang/rust-clippy/pull/9288#issuecomment-1229398524: If the literal `None` is from expansion, we never lint. This is correct because e.g. replacing the call to `option_env!` with whatever that macro expanded to at the time of linting is certainly wrong.

changelog: Don't lint [`partialeq_to_none`] for macro-expansions
2022-08-28 10:59:16 +00:00
Jason Newcomb
9790a3291b Fixes for latest nightly 2022-08-28 06:44:22 -04:00
Jason Newcomb
278b0920d8 Bump nightly version -> 2022-08-27 2022-08-28 06:44:22 -04:00
Jason Newcomb
3ad398d9b0 Merge branch 'master' into rustup 2022-08-28 06:44:13 -04:00
Lukas Lueg
c542f1fe3f Don't lint literal None from expansion 2022-08-28 12:18:50 +02:00
bors
8d9da4d7c7 Auto merge of #9276 - dswij:9164, r=flip1995
Ignore `match_like_matches_macro` when there is comment

Closes #9164

changelog: [`match_like_matches_macro`] is ignored when there is some comment inside the match block.

Also add `span_contains_comment` util to check if given span contains comments.
2022-08-28 07:08:18 +00:00
bors
2d4d8e16cd Auto merge of #8984 - xanathar:pr/suspicious_to_owned, r=llogiq
Implemented `suspicious_to_owned` lint to check if `to_owned` is called on a `Cow`

changelog: Add lint ``[`suspicious_to_owned`]``

-----------------
Hi,
posting this unsolicited PR as I've been burned by this issue :)
Being unsolicited, feel free to reject it or reassign a different lint level etc.

This lint checks whether `to_owned` is called on `Cow<'_, _>`. This is done because `to_owned` is very similarly named to `into_owned`, but the effect of calling those two methods is completely different (one makes the `Cow::Borrowed` into a `Cow::Owned`, the other just clones the `Cow`). If the cow is then passed to code for which the type is not checked (e.g. generics, closures, etc.) it might slip through and if the cow data is coming from an unsafe context there is the potential for accidentally cause undefined behavior.
Even if not falling into this painful case, there's really no reason to call `to_owned` on a `Cow` other than confusing people reading the code: either `into_owned` or `clone` should be called.

Note that this overlaps perfectly with `implicit_clone` as a warning, but `implicit_clone` is classified pedantic (while the consequences for `Cow` might be of a wider blast radius than just pedantry); given the overlap, I set-up the lint so that if `suspicious_to_owned` triggers `implicit_clone` will not trigger. I'm not 100% sure this is done in the correct way (I tried to copy what other lints were doing) so please provide feedback on it if it isn't.

### Checklist

- \[x] 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`
2022-08-27 17:38:40 +00:00
dswij
b07d72b69e Ignore when there is comment 2022-08-28 00:07:00 +08:00
dswij
51e9113c60 Add span_contains_comments util 2022-08-28 00:07:00 +08:00
Andre Bogus
90fe3bea52 remove parenthesis from unnecessary_cast suggestion 2022-08-27 12:04:19 +02:00
bors
be8bd60000 Auto merge of #9381 - lukaslueg:issue9361, r=dswij
Don't lint `needless_return` if `return` has attrs

Fixes #9361

The lint used to have a mechanic to allow `cfg`-attrs on naked `return`-statements. This was well-intentioned, yet we can have any kind of attribute, e.g. `allow`, `expect` or even custom `derive`. So the mechanic was simply removed. We now never lint on a naked `return`-statement that has attributes on it.

Turns out that the ui-test had a Catch22 in it: In `check_expect()` the `#[expect(clippy::needless_return)]` is an attribute on the `return` statement that can and will be rustfixed away without side effects. But any other attribute would also have been removed, which is what #9361 is about. The test proved the wrong thing. Removed the test, the body is tested elsewhere as well.

changelog: Ignore [`needless_return`] on `return`s with attrs
2022-08-27 08:37:29 +00:00
Marco Mastropaolo
de028e2fb9 Implemented suspicious_to_owned lint to check if to_owned is called on a Cow.
This is done because `to_owned` is very similarly named to `into_owned`, but the
effect of calling those two methods is completely different. This creates
confusion (stemming from the ambiguity of the 'owned' term in the context of
`Cow`s) and might not be what the writer intended.
2022-08-26 17:41:17 -07:00
Lukas Lueg
fe93b8d001 Don't lint needless_return if return has attrs
Fixes #9361
2022-08-26 19:06:07 +02:00
bors
602bec26b0 Auto merge of #9374 - sk1p:patch-1, r=Jarcho
uninit_vec: Vec::spare_capacity_mut is stable

Quick documentation fix: `Vec::spare_capacity_mut` no longer needs nightly.

changelog: none
2022-08-26 13:15:58 +00:00