Commit graph

6839 commits

Author SHA1 Message Date
J-ZhengLi
9fe7c6a7ec finally came up with some repro code 2024-01-18 17:56:35 +08:00
bors
2067fe482c Auto merge of #12155 - GuillaumeGomez:fix-9961, r=blyxyas
Correctly handle type relative in trait_duplication_in_bounds lint

Fixes #9961.

The generic bounds were not correctly checked and left out `QPath::TypeRelative`, making different bounds look the same and generating invalid errors (and fix).

r? `@blyxyas`

changelog: [`trait_duplication_in_bounds`]: Correctly handle type relative.
2024-01-17 15:44:16 +00:00
bors
e27ebf28e7 Auto merge of #11766 - dswij:issue-9274, r=blyxyas
`read_zero_byte_vec` refactor for better heuristics

Fixes #9274

Previously, the implementation of `read_zero_byte_vec` only checks for the next statement after the vec init. This fails when there is a block with statements that are expanded and walked by the old visitor.

This PR refactors so that:

1. It checks if there is a `resize`	on the vec
2. It works on blocks properly

e.g. This should properly lint now:

```
    let mut v = Vec::new();
    {
        f.read(&mut v)?;
        //~^ ERROR: reading zero byte data to `Vec`
    }
```

changelog: [`read_zero_byte_vec`] Refactored for better heuristics
2024-01-17 15:14:11 +00:00
bors
5f3a06023a Auto merge of #11608 - atwam:suspicious-open-options, r=y21
Add suspicious_open_options lint.

changelog: [`suspicious_open_options`]: Checks for the suspicious use of std::fs::OpenOptions::create() without an explicit OpenOptions::truncate().

create() alone will either create a new file or open an existing file. If the file already exists, it will be overwritten when written to, but the file will not be truncated by default. If less data is written to the file than it already contains, the remainder of the file will remain unchanged, and the end of the file will contain old data.

In most cases, one should either use `create_new` to ensure the file is created from scratch, or ensure `truncate` is called so that the truncation behaviour is explicit. `truncate(true)` will ensure the file is entirely overwritten with new data, whereas `truncate(false)` will explicitely keep the default behavior.

```rust
use std::fs::OpenOptions;

OpenOptions::new().create(true).truncate(true);
```

- [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`
2024-01-16 21:33:04 +00:00
Michael Goulet
f7376a0f8c Deal with additional wrapping of async closure body in clippy 2024-01-16 17:12:10 +00:00
Guillaume Gomez
7217c22f69 Update trait_duplication_in_bounds.rs ui test to add regression for ##9961 2024-01-16 12:13:27 +01:00
bors
ecb0311fcc Auto merge of #12149 - GuillaumeGomez:core-std-suggestions, r=llogiq
Correctly suggest std or core path depending if this is a `no_std` crate

A few lints emit suggestions using `std` paths whether or not this is a `no_std` crate, which is an issue when running `rustfix` afterwards. So in case this is an item that is defined in both `std` and `core`, we need to check if the crate is `no_std` to emit the right path.

r? `@llogiq`

changelog: Correctly suggest std or core path depending if this is a `no_std` crate
2024-01-16 06:26:29 +00:00
Guillaume Gomez
136a582349 Add non_exhaustive checks in derive_partial_eq_without_eq.rs ui test 2024-01-15 23:29:06 +01:00
y21
f09cd88199
fix false positive in suspicious_open_options, make paths work 2024-01-15 17:15:09 +00:00
atwam
515fe65ba8
Fix conflicts
- New ineffective_open_options had to be fixed.
- Now not raising an issue on missing `truncate` when `append(true)`
  makes the intent clear.
- Try implementing more advanced tests for non-chained operations. Fail
2024-01-15 17:15:09 +00:00
atwam
84588a8815
Add suggestion/fix to suspicious_open_options
Also rebase and fix conflicts
2024-01-15 17:15:09 +00:00
atwam
2ec8729962
PR Fixes 2024-01-15 17:15:08 +00:00
atwam
6fb471d646
More helpful text, small style changes. 2024-01-15 17:15:08 +00:00
atwam
6c201db005
Add suspicious_open_options lint.
Checks for the suspicious use of OpenOptions::create()
without an explicit OpenOptions::truncate().

create() alone will either create a new file or open an
existing file. If the file already exists, it will be
overwritten when written to, but the file will not be
truncated by default. If less data is written to the file
than it already contains, the remainder of the file will
remain unchanged, and the end of the file will contain old
data.
In most cases, one should either use `create_new` to ensure
the file is created from scratch, or ensure `truncate` is
called so that the truncation behaviour is explicit.
`truncate(true)` will ensure the file is entirely overwritten
with new data, whereas `truncate(false)` will explicitely
keep the default behavior.

```rust
use std::fs::OpenOptions;

OpenOptions::new().create(true).truncate(true);
```
2024-01-15 17:15:08 +00:00
Ed Morley
a16a85030c
Add "OpenTelemetry" to default doc_valid_idents
The OpenTelemetry project's name is all one word (see https://opentelemetry.io),
so currently triggers a false positive in the `doc_markdown` lint.

The project is increasing rapidly in popularity, so it seems like a worthy
contender for inclusion in the default `doc_valid_idents` configuration.

I've also moved the existing "OpenDNS" entry earlier in the list, to restore
the alphabetical ordering of that "Open*" row.

The docs changes were generated using `cargo collect-metadata`.

changelog: [`doc_markdown`]: Add `OpenTelemetry` to the default configuration as an allowed identifier
2024-01-15 14:26:41 +00:00
bors
692f53fe8f Auto merge of #12136 - y21:issue12135, r=Jarcho
[`useless_asref`]: check that the clone receiver is the parameter

Fixes #12135

There was no check for the receiver of the `clone` call in the map closure. This makes sure that it's a path to the parameter.

changelog: [`useless_asref`]: check that the clone receiver is the closure parameter
2024-01-15 05:08:16 +00:00
bors
d6ff2d2c2d Auto merge of #12141 - samueltardieu:issue-12138, r=Jarcho
from_over_into: suggest a correct conversion to ()

changelog: [`from_over_into`]: suggest a correct conversion to `()`

Fix #12138
2024-01-15 04:32:22 +00:00
bors
a9fa2f5ed1 Auto merge of #12074 - ARandomDev99:12044-include-comments-while-checking-duplicate-code, r=Jarcho
Make `HirEqInterExpr::eq_block` take comments into account while checking if two blocks are equal

This PR:
- now makes `HirEqInterExpr::eq_block` take comments into account. Identical code with varying comments will no longer be considered equal.
- makes necessary adjustments to UI tests.

Closes #12044

**Lintcheck Changes**
- `match_same_arms` 53 => 52
- `if_same_then_else` 3 => 0

changelog: [`if_same_then_else`]: Blocks with different comments will no longer trigger this lint.
changelog: [`match_same_arms`]: Arms with different comments will no longer trigger this lint.
```
2024-01-15 04:06:52 +00:00
Guillaume Gomez
40a45a463f Update and add ui tests for core/std suggestions 2024-01-14 14:45:24 +01:00
y21
be5707ce1b lint on .map(|&x| x.clone()) 2024-01-13 17:46:46 +01:00
Quinn Sinclair
e0228eeb94 Fixes FP in redundant_closure_call when closures are passed to macros
There are cases where the closure call is needed in some macros, this in
particular occurs when the closure has parameters. To handle this case,
we allow the lint when there are no parameters in the closure, or the
closure is outside a macro invocation.

fixes: #11274, #1553
changelog: FP: [`redundant_closure_call`] when closures with parameters
are passed in macros.
2024-01-13 17:45:30 +01:00
Samuel Tardieu
e025356969 from_over_into: suggest a correct conversion to () 2024-01-13 13:19:55 +01:00
Nilstrieb
3b7ba1d10a Improve let_underscore_lock
- lint if the lock was in a nested pattern
- lint if the lock is inside a `Result<Lock, _>`
2024-01-12 23:18:58 +01:00
Guillaume Gomez
37947ffc40 Update ui tests for search_is_some lint 2024-01-12 22:48:30 +01:00
bors
7eca5afd34 Auto merge of #12137 - GuillaumeGomez:fix-unconditional_recursion-false-positive, r=llogiq
Fix false positive in `PartialEq` check in `unconditional_recursion` lint

Fixes https://github.com/rust-lang/rust-clippy/issues/12133.

We needed to check for the type of the previous element <del>in case it's a field</del>.

EDIT: After some extra thoughts, no need to check if it's a field, just if it's the same type as `Self`.

r? `@llogiq`

changelog: Fix false positive in `PartialEq` check in `unconditional_recursion` lint
2024-01-12 18:30:11 +00:00
Guillaume Gomez
132667288a Add regression ui test for unconditional_recursion lint on PartialEq 2024-01-12 17:37:09 +01:00
Guillaume Gomez
e9f87132a1 Rollup merge of #119819 - chenyukang:yukang-fix-118183-lint, r=davidtwco
Check rust lints when an unknown lint is detected

Fixes #118183
2024-01-12 15:16:56 +01:00
y21
153b83f61b [useless_asref]: check that the clone receiver is the local 2024-01-12 13:39:42 +01:00
yukang
1485e5c4da check rust lints when an unknown lint is detected 2024-01-12 18:50:36 +08:00
bors
88b5d519a1 Auto merge of #12129 - GuillaumeGomez:map-clone-copy, r=llogiq
Fix suggestion for `map_clone` lint on types implementing `Copy`

Follow-up of https://github.com/rust-lang/rust-clippy/pull/12104.

It was missing this check to suggest the correct method.

r? `@llogiq`

changelog: Fix suggestion for `map_clone` lint on types implementing `Copy`
2024-01-11 23:28:12 +00:00
Guillaume Gomez
74db4b7f6d Add new ui tests for map_clone lint on types implementing Copy 2024-01-11 17:44:07 +01:00
Philipp Krones
aa220c7ee7 Merge commit '26ac6aab023393c94edf42f38f6ad31196009643' 2024-01-11 17:27:03 +01:00
Philipp Krones
2c0cea7cbc
Merge remote-tracking branch 'upstream/master' into rustup 2024-01-11 17:19:53 +01:00
cocodery
7c389acd27 Fix error warning span for issue12045 2024-01-11 14:52:03 +08:00
Guillaume Gomez
103e8881c6 Add tests to ensure that map_clone is not emitted if as_ref().clone() is present 2024-01-09 17:39:51 +01:00
Guillaume Gomez
8791a28c4a Also handle Result type for map_clone lint 2024-01-09 16:35:40 +01:00
Guillaume Gomez
cdd96bc662 Update ui tests for useless_asref lint extension 2024-01-09 14:14:29 +01:00
bors
3b8323d790 Auto merge of #12049 - cocodery:fix/issue#11243, r=Alexendoo
fix/issue#11243: allow 3-digit-grouped binary in non_octal_unix_permissions

fixes [Issue#11243](https://github.com/rust-lang/rust-clippy/issues/11243)

Issue#11243 suggest lint `non_octal_unix_permissions` should not report binary format literal unix permissions as an error, and we think binary format is a good way to understand these permissions.

To solve this problem, we need to add check for binary literal, which is written in function `check_binary_unix_permissions` , only `binary, 3 groups and each group length equals to 3` is a legal format.

changelog: [`non_octal_unix_permissions`]: Add check for binary format literal unix permissions like 0b111_111_111
2024-01-08 19:09:42 +00:00
bors
7fbaba856b Auto merge of #12080 - PartiallyTyped:12058, r=xFrednet
Fixed ICE introduced in #12004

Issue: in https://github.com/rust-lang/rust-clippy/pull/12004, we emit a lint for `filter(Option::is_some)`. If the
parent expression is a `.map` we don't emit that lint as there exists a
more specialized lint for that.

The ICE introduced in https://github.com/rust-lang/rust-clippy/pull/12004 is a consequence of the assumption that a
parent expression after a filter would be a method call with the filter
call being the receiver. However, it is entirely possible to have a
closure of the form

```
|| { vec![Some(1), None].into_iter().filter(Option::is_some) }
```
The previous implementation looked at the parent expression; namely the
closure, and tried to check the parameters by indexing [0] on an empty
list.

This commit is an overhaul of the lint with significantly more FP tests
and checks.

Impl details:

1. We verify that the filter method we are in is a proper trait method
   to avoid FPs.
2. We check that the parent expression is not a map by checking whether
   it exists; if is a trait method; and then a method call.
3. We check that we don't have comments in the span.
4. We verify that we are in an Iterator of Option and Result.
5. We check the contents of the filter.
   1. For closures we peel it. If it is not a single expression, we don't
     lint. We then try again by checking the peeled expression.
   2. For paths, we do a typecheck to avoid FPs for types that impl
     functions with the same names.
   3. For calls, we verify the type, via the path, and that the param of
     the closure is the single argument to the call.
   4. For method calls we verify that the receiver is the parameter of
     the closure. Since we handle single, non-block exprs, the
     parameter can't be shadowed, so no FP.

This commit also adds additional FP tests.

Fixes: #12058

Adding `@xFrednet` as you've the most context for this as you reviewed it last time.

`@rustbot` r? `@xFrednet`

---

changelog: none
(Will be backported and therefore don't effect stable)
2024-01-07 17:21:28 +00:00
Quinn Sinclair
bbadce9ec0 Fixed ICE introduced in #12004
Issue: in #12004, we emit a lint for `filter(Option::is_some)`. If the
parent expression is a `.map` we don't emit that lint as there exists a
more specialized lint for that.

The ICE introduced in #12004 is a consequence of the assumption that a
parent expression after a filter would be a method call with the filter
call being the receiver. However, it is entirely possible to have a
closure of the form

```
|| { vec![Some(1), None].into_iter().filter(Option::is_some) }
```
The previous implementation looked at the parent expression; namely the
closure, and tried to check the parameters by indexing [0] on an empty
list.

This commit is an overhaul of the lint with significantly more FP tests
and checks.

Impl details:

1. We verify that the filter method we are in is a proper trait method
   to avoid FPs.
2. We check that the parent expression is not a map by checking whether
   it exists; if is a trait method; and then a method call.
3. We check that we don't have comments in the span.
4. We verify that we are in an Iterator of Option and Result.
5. We check the contents of the filter.
  1. For closures we peel it. If it is not a single expression, we don't
     lint.
  2. For paths, we do a typecheck to avoid FPs for types that impl
     functions with the same names.
  3. For calls, we verify the type, via the path, and that the param of
     the closure is the single argument to the call.
  4. For method calls we verify that the receiver is the parameter of
     the closure. Since we handle single, non-block exprs, the
     parameter can't be shadowed, so no FP.

This commit also adds additional FP tests.
2024-01-07 17:11:34 +02:00
bors
f37e7f3585 Auto merge of #12109 - GuillaumeGomez:map-clone-call, r=llogiq
Handle "calls" inside the closure as well in `map_clone` lint

Follow-up of https://github.com/rust-lang/rust-clippy/pull/12104.

I just realized that I didn't handle the case where the `clone` method was made as a call and not a method call.

r? `@llogiq`

changelog: Handle "calls" inside the closure as well in `map_clone` lint
2024-01-07 14:23:02 +00:00
Guillaume Gomez
f66e940c88 Update ui test for map_clone lint 2024-01-07 13:24:52 +01:00
Samuel Tardieu
5b7a0de3e7 Do not suggest bool::then() and bool::then_some in const contexts 2024-01-07 10:43:18 +01:00
bors
0e5dc8e630 Auto merge of #11883 - J-ZhengLi:issue11642, r=dswij
improve [`cast_sign_loss`], to skip warning on always positive expressions

fixes: #11642

changelog: improve [`cast_sign_loss`] to skip warning on always positive expressions

Turns out this is change became quite big, and I still can't cover all the cases, like method calls such as `POSITIVE_NUM.mul(POSITIVE_NUM)`, or `NEGATIVE_NUM.div(NEGATIVE_NUM)`... but well, if I do, I'm scared that this will goes forever, so I stopped, unless it needs to be done, lol.
2024-01-06 19:22:59 +00:00
bors
788094c235 Auto merge of #11972 - samueltardieu:issue-11958, r=llogiq
Do not suggest `[T; n]` instead of `vec![T; n]` if `T` is not `Copy`

changelog: [`useless_vec`]: do not suggest replacing `&vec![T; N]` by `&[T; N]` if `T` is not `Copy`

Fix #11958
2024-01-06 18:56:30 +00:00
bors
17b2418208 Auto merge of #12104 - GuillaumeGomez:map-clone, r=llogiq
Extend `map_clone` lint to also work on non-explicit closures

I found it weird that this case was not handled by the current line so I added it. The only thing is that I don't see an obvious way to infer the current type to determine if it's copyable or not, so for now I always suggest `cloned` and I added a FIXME.

r? `@llogiq`

changelog: Extend `map_clone` lint to also work on non-explicit closures
2024-01-06 16:54:20 +00:00
Guillaume Gomez
6410606815 Update map_clone lint ui test 2024-01-06 17:22:21 +01:00
cocodery
60c647b262 Fix bug: allow no- '_'-split binary format string, add test 2024-01-06 21:41:25 +08:00
cocodery
bd6e9202b4 modify check that any macros will be ingored in this lint, and add test 2024-01-06 14:12:41 +08:00
bors
5d57ba86a8 Auto merge of #12097 - y21:issue9427-3, r=llogiq
don't change eagerness for struct literal syntax with significant drop

Fixes the bug reported by `@ju1ius` in https://github.com/rust-lang/rust-clippy/issues/9427#issuecomment-1878428001.

`eager_or_lazy` already understands to suppress eagerness changes when the expression type has a significant drop impl, but only for initialization of tuple structs or unit structs. This changes it to also avoid changing it for `Self { .. }` and `TypeWithDrop { .. }`

changelog: [`unnecessary_lazy_eval`]: don't suggest changing eagerness for struct literal syntax when type has a significant drop impl
2024-01-05 20:25:18 +00:00
Matthias Krüger
b418117277 Rollup merge of #119151 - Jules-Bertholet:no-foreign-doc-hidden-suggest, r=davidtwco
Hide foreign `#[doc(hidden)]` paths in import suggestions

Stops the compiler from suggesting to import foreign `#[doc(hidden)]` paths.

```@rustbot``` label A-suggestion-diagnostics
2024-01-05 20:39:50 +01:00
bors
7bb0e9c2f2 Auto merge of #12099 - GuillaumeGomez:struct-field-names-bool, r=llogiq
Don't emit `struct_field_names` lint if all fields are booleans and don't start with the type's name

Fixes #11936.

I only checked that all fields are booleans and not the prefix (nor the suffix) because when I started to list accepted prefixes (like "is", "has", "should", "could", etc), the list was starting to get a bit too long and I thought it was not really worth for such a small change.

r? `@llogiq`

changelog: Don't emit `struct_field_names` lint if all fields are booleans and don't start with the type's name
2024-01-05 16:58:50 +00:00
bors
394f63fe94 Auto merge of #10844 - Centri3:let_unit_value, r=Alexendoo
Don't lint `let_unit_value` when `()` is explicit

since these are explicitly written (and not the result of a function call or anything else), they should be allowed, as they are both useful in some cases described in #9048

Fixes #9048

changelog: [`let_unit_value`]: Don't lint when `()` is explicit
2024-01-05 16:13:38 +00:00
Centri3
fd9d330839 Don't lint let_unit_value when () is explicit 2024-01-05 16:04:02 +00:00
Michael Goulet
3a683f696d Rollup merge of #119148 - estebank:bare-traits, r=davidtwco
Tweak suggestions for bare trait used as a type

```
error[E0782]: trait objects must include the `dyn` keyword
  --> $DIR/not-on-bare-trait-2021.rs:11:11
   |
LL | fn bar(x: Foo) -> Foo {
   |           ^^^
   |
help: use a generic type parameter, constrained by the trait `Foo`
   |
LL | fn bar<T: Foo>(x: T) -> Foo {
   |       ++++++++    ~
help: you can also use `impl Foo`, but users won't be able to specify the type paramer when calling the `fn`, having to rely exclusively on type inference
   |
LL | fn bar(x: impl Foo) -> Foo {
   |           ++++
help: alternatively, use a trait object to accept any type that implements `Foo`, accessing its methods at runtime using dynamic dispatch
   |
LL | fn bar(x: &dyn Foo) -> Foo {
   |           ++++

error[E0782]: trait objects must include the `dyn` keyword
  --> $DIR/not-on-bare-trait-2021.rs:11:19
   |
LL | fn bar(x: Foo) -> Foo {
   |                   ^^^
   |
help: use `impl Foo` to return an opaque type, as long as you return a single underlying type
   |
LL | fn bar(x: Foo) -> impl Foo {
   |                   ++++
help: alternatively, you can return an owned trait object
   |
LL | fn bar(x: Foo) -> Box<dyn Foo> {
   |                   +++++++    +
```

Fix #119525:

```

error[E0038]: the trait `Ord` cannot be made into an object
  --> $DIR/bare-trait-dont-suggest-dyn.rs:3:33
   |
LL | fn ord_prefer_dot(s: String) -> Ord {
   |                                 ^^^ `Ord` cannot be made into an object
   |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
  --> $SRC_DIR/core/src/cmp.rs:LL:COL
   |
   = note: the trait cannot be made into an object because it uses `Self` as a type parameter
  ::: $SRC_DIR/core/src/cmp.rs:LL:COL
   |
   = note: the trait cannot be made into an object because it uses `Self` as a type parameter
help: consider using an opaque type instead
   |
LL | fn ord_prefer_dot(s: String) -> impl Ord {
   |                                 ++++
```
2024-01-05 10:57:20 -05:00
Guillaume Gomez
7aa4624a8f Extend struct_field_names lint ui test 2024-01-05 16:44:41 +01:00
bors
d3dfecbd41 Auto merge of #12066 - y21:issue12048, r=Alexendoo
Don't look for safety comments in doc tests

Fixes #12048.

What happened in the linked issue is that the lint checks for lines that start with `//` and have `SAFETY:` somewhere in it above the function item.
This works for regular comments, but when the `//` is the start of a doc comment (e.g. `/// // SAFETY: ...`) and it's part of a doc test (i.e. within \`\`\`), we probably shouldn't lint that, since the user most likely meant to refer to a different node than the one currently being checked. For example in the linked issue, the safety comment refers to `unsafe { *five_pointer }`, but the lint believes it's part of the function item.

We also can't really easily test whether the `// SAFETY:` comment within a doc comment is necessary or not, since I think that would require creating a new compiler session to re-parse the contents of the doc comment. We already do this for one of the doc markdown lints, to look for a main function in doc tests, but I don't know how to feel about doing that in more places, so probably best to just ignore them?

changelog: [`unnecessary_safety_comment`]: don't look for safety comments in doc tests
2024-01-05 15:23:11 +00:00
bors
2d6c2386f5 Auto merge of #12091 - samueltardieu:issue-12068, r=Alexendoo
Add .as_ref() to suggestion to remove .to_string()

The case of `.to_owned().split(…)` is treated specially in the `unnecessary_to_owned` lint. Test cases check that it works both for slices and for strings, but they missed a corner case: `x.to_string().split(…)` when `x` implements `AsRef<str>` but not `Deref<Target = str>`. In this case, it is wrong to suggest to remove `.to_string()` without adding `.as_ref()` instead.

Fix #12068

changelog: [`unnecessary_to_owned`]: suggest replacing `.to_string()` by `.as_ref()`
2024-01-05 14:54:40 +00:00
y21
890c0702e4 don't change eagerness for struct literal syntax with significant drop 2024-01-05 11:45:59 +01:00
bors
ee8bfb7f7a Auto merge of #12051 - y21:option_as_ref_cloned, r=dswij
new lint: `option_as_ref_cloned`

Closes #12009

Adds a new lint that looks for `.as_ref().cloned()` on `Option`s. That's the same as just `.clone()`-ing the option directly.

changelog: new lint: [`option_as_ref_cloned`]
2024-01-05 06:39:46 +00:00
Yuxiang Qiu
03b3a16a8c
test: add more test cases 2024-01-04 15:29:44 -05:00
bors
8507e4c80e Auto merge of #12090 - GuillaumeGomez:default-unconditional-recursion, r=llogiq
Extend `unconditional_recursion` lint to check for `Default` trait implementation

In case the `Default` trait is implemented manually and is calling a static method (let's call it `a`) and then `a` is using `Self::default()`, it makes an infinite call recursion difficult to see without debugging. This extension checks that there is no such recursion possible.

r? `@llogiq`

changelog: Extend `unconditional_recursion` lint to check for `Default` trait implementation
2024-01-04 19:45:20 +00:00
Guillaume Gomez
bf5c0d8334 Add tests for extension of unconditional_recursion lint on Default trait 2024-01-04 17:40:28 +01:00
Samuel Tardieu
e758413973 Add .as_ref() to suggestion to remove .to_string() 2024-01-04 17:29:20 +01:00
bors
ebf5c1a928 Auto merge of #12031 - y21:eager_transmute_more_binops, r=llogiq
Lint nested binary operations and handle field projections in `eager_transmute`

This PR makes the lint a bit stronger. Previously it would only lint `(x < 4).then_some(transmute(x))` (that is, a single binary op in the condition). With this change, it understands:
- multiple, nested binary ops: `(x < 4 && x > 1).then_some(...)`
- local references with projections: `(x.field < 4 && x.field > 1).then_some(transmute(x.field))`

changelog: [`eager_transmute`]: lint nested binary operations and look through field/array accesses

r? llogiq (since you reviewed my initial PR #11981, I figured you have the most context here, sorry if you are too busy with other PRs, feel free to reassign to someone else then)
2024-01-03 21:43:01 +00:00
bors
17dcd0d2e4 Auto merge of #12030 - torfsen:11973-fix-quoting-of-double-quote-in-char-literal, r=llogiq
11973: Don't escape `"` in `'"'`

Fixes #11973.

```
changelog: [`single_char_pattern`]: don't escape `"` in `'"'`
```
2024-01-03 21:30:01 +00:00
Esteban Küber
ca83a98e66 Track HirId instead of Span in ObligationCauseCode::SizedArgumentType
This gets us more accurate suggestions.
2024-01-03 18:59:42 +00:00
y21
5960107415 new lint: option_as_ref_cloned 2024-01-03 19:40:47 +01:00
Yuxiang Qiu
b5a2192628
fix: incorrect suggestions generated by manual_retain lint 2024-01-03 13:05:55 -05:00
bors
0153ca95ae Auto merge of #12062 - GuillaumeGomez:fix-false-positive-unconditional_recursion, r=xFrednet
Fix false positive `unconditional_recursion`

Fixes #12052.

Only checking if both variables are `local` was not enough, we also need to confirm they have the same type as `Self`.

changelog: Fix false positive for `unconditional_recursion` lint
2024-01-03 09:14:58 +00:00
bors
2eb13d3a7c Auto merge of #12056 - PartiallyTyped:12050, r=xFrednet
Fixes: #12050 - `identity_op` correctly suggests a deference for coerced references

When `identity_op` identifies a `no_op`, provides a suggestion, it also checks the type of the type of the variable. If the variable is a reference that's been coerced into a value, e.g.

```
let x = &0i32;
let _ = x + 0;
```

the suggestion will now use a derefence. This is done by identifying whether the variable is a reference to an integral value, and then whether it gets dereferenced.

changelog: false positive: [`identity_op`]: corrected suggestion for reference coerced to value.

fixes: #12050
2024-01-03 09:02:02 +00:00
Yuxiang Qiu
88541d6637
fix some typos 2024-01-02 19:21:51 -05:00
Jake Goulding
04ebf3c8c9 Remove #[allow(unused_tuple_struct_fields)] from Clippy tests 2024-01-02 15:34:37 -05:00
Aneesh Kadiyala
543d56938e Make HirEqInterExpr::eq_block take comments into account
This commit:
- now makes `HirEqInterExpr::eq_block` take comments into account. Identical code with varying comments will no longer be considered equal.
- makes necessary adjustments to UI tests.
2024-01-02 11:30:20 +05:30
roife
1cce757672 Add error-annotations in tests for unnecessary_fallible_conversions 2024-01-02 01:29:20 +08:00
Quinn Sinclair
70024e16c0 New Lint: [thread_local_initializer_can_be_made_const]
Adds a new lint to suggest using `const` on `thread_local!`
initializers that can be evaluated at compile time.

Impl details:

The lint relies on the expansion of `thread_local!`. For non
const-labelled initializers, `thread_local!` produces a function
called `__init` that lazily initializes the value. We check the function
and decide whether the body can be const. The body of the function is
exactly the initializer. If so, we lint the body.

changelog: new lint [`thread_local_initializer_can_be_made_const`]
2024-01-01 18:06:10 +02:00
roife
094ce3de3e Add comments for unnecessary_fallible_conversions 2024-01-01 16:34:42 +08:00
roife
69cc983155 Add tests for autofix in unnecessary_fallible_conversions 2024-01-01 16:17:46 +08:00
y21
ef35e82ea3 don't look for safety comments in codeblocks 2024-01-01 02:57:23 +01:00
Florian Brucker
fe35e08e9f 8733: Suggest str.lines when splitting at hard-coded newlines
Adds a new `splitting_strings_at_newlines` lint that suggests to use
`str.lines` instead of splitting a trimmed string at hard-coded
newlines.
2023-12-31 13:30:36 +01:00
Guillaume Gomez
7107aa22b2 Add regression tests for unconditional_recursion 2023-12-31 11:20:49 +01:00
bors
44c99a8089 Auto merge of #11980 - GuillaumeGomez:UNCONDITIONAL_RECURSION-tostring, r=llogiq
Extend UNCONDITIONAL_RECURSION to check for ToString implementations

Follow-up of https://github.com/rust-lang/rust-clippy/pull/11938.

r? `@llogiq`

changelog: Extend `UNCONDITIONAL_RECURSION` to check for `ToString` implementations
2023-12-31 09:12:42 +00:00
bors
7f185bdef6 Auto merge of #12047 - ARandomDev99:12007-empty-enum-variants-with-brackets, r=Jarcho
New Lint: empty_enum_variants_with_brackets

This PR:
- adds a new early pass lint that checks for enum variants with no fields that were defined using brackets. **Category: Restriction**
- adds relevant UI tests for the new lint.

Closes #12007

```
changelog: New lint: [`empty_enum_variants_with_brackets`]
```
2023-12-30 19:01:53 +00:00
bors
0cc53f48f5 Auto merge of #11957 - J-ZhengLi:issue11535, r=Jarcho
don't lint [`default_numeric_fallback`] on return and local assigned macro calls with type stated

fixes: #11535

changelog: don't lint [`default_numeric_fallback`] on return and local assigned macro calls with type stated
2023-12-30 16:47:14 +00:00
bors
c6aeb28a7b Auto merge of #11865 - yuxqiu:map_unwrap_or_default, r=Jarcho
feat: add `manual_is_variant_and` lint

changelog: add a new lint [`manual_is_variant_and`].
- Replace `option.map(f).unwrap_or_default()` and `result.map(f).unwrap_or_default()` with `option.is_some_and(f)` and `result.is_ok_and(f)` where `f` is a function or closure that returns `bool`.
- MSRV is set to 1.70.0 for this lint; when `is_some_and` and `is_ok_and` was stabilised

---

For example, for the following code:

```rust
let opt = Some(0);
opt.map(|x| x > 1).unwrap_or_default();
```

It suggests to instead write:

```rust
let opt = Some(0);
opt.is_some_and(|x| x > 1)
```
2023-12-30 16:37:36 +00:00
bors
b19b5f293e Auto merge of #12008 - J-ZhengLi:issue9872, r=Jarcho
make [`mutex_atomic`] more type aware

fixes: #9872

---

changelog: [`mutex_atomic`] now suggests more specific atomic types and skips mutex i128 and u128
2023-12-30 16:29:13 +00:00
Guillaume Gomez
d161f3b559 Add ui test for UNCONDITIONAL_RECURSION lint on ToString impl 2023-12-30 17:11:56 +01:00
Quinn Sinclair
c2b3f5c767 identity_op correctly suggests a deference for coerced references
When `identity_op` identifies a `no_op`, provides a suggestion, it also
checks the type of the type of the variable. If the variable is
a reference that's been coerced into a value, e.g.

```
let x = &0i32;
let _ = x + 0;
```

the suggestion will now use a derefence. This is done by identifying
whether the variable is a reference to an integral value, and then
whether it gets dereferenced.

changelog: false positive: [`identity_op`]: corrected suggestion for
reference coerced to value.

fixes: #12050
2023-12-30 13:31:32 +02:00
y21
0848e120b2 add expansion checks to iter_without_into_iter and into_iter_without_iter 2023-12-30 04:56:46 +01:00
Aneesh Kadiyala
1ee9993a96 add new lint, empty_enum_variants_with_brackets
- Add a new early pass lint.
- Add relevant UI tests.
2023-12-29 19:23:31 +05:30
Philipp Krones
15b1edb209 Merge commit 'ac4c2094a6030530661bee3876e0228ddfeb6b8b' into clippy-subtree-sync 2023-12-28 19:33:07 +01:00
Philipp Krones
9ff84af787
Merge remote-tracking branch 'upstream/master' into rustup 2023-12-28 19:20:18 +01:00
y21
6c28f0765e recognize contains calls on ranges 2023-12-28 05:27:56 +01:00
y21
affde93041 lint on nested binary operations involving local and handle projections 2023-12-27 23:38:20 +01:00
Florian Brucker
e5c9fb6827 11973: Don't escape " in '"' 2023-12-27 22:26:25 +01:00
Florian Brucker
ebc0588937 6459: Check for redundant matches! with Ready, Pending, V4, V6 2023-12-27 19:10:04 +01:00
bors
c689d32a90 Auto merge of #11981 - y21:eager_int_transmute, r=llogiq
new lint: `eager_transmute`

A small but still hopefully useful lint that looks for patterns such as `(x < 5).then_some(transmute(x))`.
This is almost certainly wrong because it evaluates the transmute eagerly and can lead to surprises such as the check being completely removed and always evaluating to `Some` no matter what `x` is (it is UB after all when the integer is not a valid bitpattern for the transmuted-to type). [Example](https://godbolt.org/z/xoY34fPzh).
The user most likely meant to use `then` instead.

I can't remember where I saw this but this is inspired by a real bug that happened in practice.

This could probably be a correctness lint?

changelog: new lint: [`eager_int_transmute`]
2023-12-27 15:16:46 +00:00
y21
08d8ca9edd new lint: eager_int_transmute 2023-12-27 14:16:35 +01:00
Yuxiang Qiu
c4a80f2e3e
feat: add manual_is_variant_and lint 2023-12-26 17:49:51 -07:00
Bruce Mitchener
f48b850c65 [doc_markdown]: Add "WebGL2", "WebGPU" to default doc_valid_idents 2023-12-26 16:58:43 -05:00
Quinn Sinclair
57dd25e2ff FP: needless_return_with_question_mark with implicit Error Conversion
Return with a question mark was triggered in situations where the `?`
desuraging was performing error conversion via `Into`/`From`.

The desugared `?` produces a match over an expression with type
`std::ops::ControlFlow<B,C>` with `B:Result<Infallible, E:Error>` and
`C:Result<_, E':Error>`, and the arms perform the conversion. The patch
adds another check in the lint that checks that `E == E'`. If `E == E'`,
then the `?` is indeed unnecessary.

changelog: False Positive: `needless_return_with_question_mark` when
implicit Error Conversion occurs.
2023-12-26 21:25:06 +02:00
Michael Goulet
2230add36e Rollup merge of #119240 - compiler-errors:lang-item-more, r=petrochenkov
Make some non-diagnostic-affecting `QPath::LangItem` into regular `QPath`s

The rest of 'em affect diagnostics, so leave them alone... for now.

cc #115178
2023-12-26 13:29:13 -05:00
bors
9dd2252b2c Auto merge of #12004 - PartiallyTyped:11843, r=xFrednet
New lints `iter_filter_is_some` and `iter_filter_is_ok`

Adds a pair of lints that check for cases of an iterator over `Result` and `Option` followed by `filter` without being followed by `map` as that is covered already by a different, specialized lint.

Fixes #11843

PS, I also made some minor documentations fixes in a case where a double tick (`) was included.

---

changelog: New Lint: [`iter_filter_is_some`]
[#12004](https://github.com/rust-lang/rust/pull/12004)
changelog: New Lint: [`iter_filter_is_ok`]
[#12004](https://github.com/rust-lang/rust/pull/12004)
2023-12-26 15:41:40 +00:00
Michael Goulet
90a59d4990 Make some non-diagnostic-affecting QPath::LangItem into regular qpaths 2023-12-26 04:07:38 +00:00
Michael Goulet
e0097f5323 Fix clippy's usage of Body's coroutine_kind
Also fixes a bug where we weren't peeling blocks from async bodies
2023-12-25 21:13:41 +00:00
bors
99c783843d Auto merge of #11967 - samueltardieu:issue-11959, r=llogiq
Do not consider `async { (impl IntoFuture).await }` as redundant

changelog: [`redundant_async_block`]: do not trigger on `IntoFuture` instances

Fix #11959
2023-12-25 12:42:26 +00:00
J-ZhengLi
a578b9ba0b make [mutex_atomic] more type aware 2023-12-25 14:28:01 +08:00
J-ZhengLi
a9baf344b8 remove obsolete test comments 2023-12-25 09:39:32 +08:00
Quinn Sinclair
85e1646afc more tests 2023-12-24 17:32:00 +02:00
Quinn Sinclair
4b1ac31c18 Added MSRV and more tests, improved wording 2023-12-24 14:40:14 +02:00
bors
830f1c58f4 Auto merge of #11994 - y21:issue11993-fn, r=xFrednet
[`question_mark`]: also trigger on `return` statements

This fixes the false negative mentioned in #11993: the lint only used to check for `return` expressions, and not a statement containing a `return` expression (doesn't close the issue tho since there's still a useful suggestion that we could make, which is to suggest `.ok_or()?`/`.ok_or_else()?` for `else { return Err(..) }`)

changelog: [`question_mark`]: also trigger on `return` statements
2023-12-23 16:17:35 +00:00
y21
e44caea259 respect comments in question_mark 2023-12-23 16:22:12 +01:00
y21
dfb4ff8bbf [question_mark]: also trigger on return statements 2023-12-23 16:22:08 +01:00
bors
618fd4b494 Auto merge of #11999 - Takashiidobe:fix-typo-in-infinite-loop-lint, r=xFrednet
fix typo in infinite loop lint

*Please write a short comment explaining your change (or "none" for internal only changes)*

changelog: This fixes a small typo introduced in https://github.com/rust-lang/rust-clippy/pull/11829
2023-12-23 14:46:52 +00:00
bors
858d96d63a Auto merge of #11871 - GuillaumeGomez:UNNECESSARY_TO_OWNED-split, r=llogiq
Extend `UNNECESSARY_TO_OWNED` to handle `split`

Fixes https://github.com/rust-lang/rust-clippy/issues/9965.

When you have `to_string().split('a')` or equivalent, it'll suggest to remove the `to_owned`/`to_string` part.

r? `@flip1995`

changelog: Extend `UNNECESSARY_TO_OWNED` to handle `split`
2023-12-23 11:36:53 +00:00
Takashi Idobe
3a4d99ec42 run cargo uibless 2023-12-22 19:02:22 -05:00
Takashi Idobe
67a33e8cc8 fix typo in infinite loop lint 2023-12-22 18:44:20 -05:00
bors
e0b25c5a64 Auto merge of #11998 - cocodery:fix/issue11762, r=llogiq
Check whether out of bound when access a known length array with a constant index

fixes [Issue#11762](https://github.com/rust-lang/rust-clippy/issues/11762)

Issue#11762 points that `Array references with known length are not flagged when indexed out of bounds`.

To fix this problem, it is needed to add check for `Expr::Index`. We expand this issue include reference and direct accessing a array.

When we access a array with a constant index `off`, and already know the length `size`, if `off >= size`, these code will throw an error, instead rustc's lint checking them or runtime panic happening.

changelog: [`out_of_bound_indexing`]: Add check for illegal accessing known length array with a constant index
2023-12-22 17:01:17 +00:00
cocodery
18eb406776 Add test for indexing_slicing_index and modify related test 2023-12-22 20:31:48 +08:00
J-ZhengLi
a556d00c0a stop [bool_comparison]'s suggestion from consuming parentheses 2023-12-21 18:20:25 +08:00
Quinn Sinclair
25b9ca3f64 New lints iter_filter_is_some and iter_filter_is_ok
Adds a pair of lints that check for cases of an iterator over `Result`
and `Option` followed by `filter` without being followed by `map` as
that is covered already by a different, specialized lint.

changelog: New Lint: [`iter_filter_is_some`]
changelog: New Lint: [`iter_filter_is_ok`]
2023-12-21 00:16:47 +02:00
Jules Bertholet
4ab8cdd5b9 Hide foreign #[doc(hidden)] paths in import suggestions 2023-12-20 00:19:45 -05:00
Guillaume Gomez
238c5f9f27 Add ui tests for UNNECESSARY_TO_OWNED on split 2023-12-18 16:55:42 +01:00
bors
dd857f8207 Auto merge of #11966 - StackOverflowExcept1on:issue-8159, r=Jarcho
Do not lint `assertions_on_constants` for `const _: () = assert!(expr)`

Fixes #8159

```rust
pub fn f() {
    // warning
    assert!(true);
    assert!(usize::BITS >= 32);

    // ok
    const _: () = assert!(usize::BITS >= 32);
}
```

changelog: Fix `const _: () = assert!(expr)` false positive on `assertions_on_constants` lint
2023-12-17 14:03:13 +00:00
Samuel Tardieu
4cea5a8f33 Do not suggest [T; n] instead of vec![T; n] if T is not Copy 2023-12-17 11:32:15 +01:00
bors
f9b5def2ae Auto merge of #11869 - PartiallyTyped:result-filter-map, r=Alexendoo
New Lint: `result_filter_map` / Mirror of `option_filter_map`

Added the `Result` mirror of `option_filter_map`.

changelog: New Lint: [`result_filter_map`]

I had to move around some code because the function def was too long 🙃.

I have also added some pattern checks on `option_filter_map`
2023-12-16 23:29:07 +00:00
bors
fff484d18e Auto merge of #11977 - y21:is_const_evaluatable_ice, r=Manishearth
don't visit nested bodies in `is_const_evaluatable`

Fixes #11939

This ICE happened in `if_let_some_else_none`, but the root problem is in one of the utils that it uses.
It is (was) possible for `is_const_evalutable` to visit nested bodies which would lead to it trying to get the type of one of the expressions with the wrong typeck table, which won't have the type stored.

Notably, for the expression `Bytes::from_static(&[0; 256 * 1024]);` in the linked issue, the array length is an anonymous const in which type checking happens on its own, so we can't use the typeck table of the enclosing function in there.

Visiting nested bodies is also not needed for checking whether an expression can be const, so I think it's safe to ignore just ignore them altogether.

changelog: Fix ICE when checking for constness in nested bodies
2023-12-16 22:54:50 +00:00
y21
b5169aea52 don't visit any nested bodies in is_const_evaluatable 2023-12-16 22:13:54 +01:00
bors
9907b90b1e Auto merge of #11938 - GuillaumeGomez:unconditional_recursion, r=llogiq
Add new `unconditional_recursion` lint

Currently, rustc `unconditional_recursion` doesn't detect cases like:

```rust
enum Foo {
    A,
    B,
}

impl PartialEq for Foo {
    fn eq(&self, other: &Self) -> bool {
        self == other
    }
}
```

This is because the lint is currently implemented only for one level, and in the above code, `self == other` will then call `impl PartialEq for &T`, escaping from the detection. The fix for it seems to be a bit tricky (I started investigating potential solution to add one extra level of recursion [here](https://github.com/rust-lang/rust/compare/master...GuillaumeGomez:rust:trait-impl-recursion?expand=1) but completely broken at the moment).

I expect that this situation will remain for a while. In the meantime, I think it's acceptable to check it directly into clippy for the time being as a lot of easy cases like this one can be easily checked (next I plan to extend it to cover other traits like `ToString`).

changelog: Add new `unconditional_recursion` lint
2023-12-16 18:21:01 +00:00
Guillaume Gomez
6b444f3092 Also check code generated by macros 2023-12-16 18:45:24 +01:00
y21
bc22407b79 add tests, lint on while let true and matches!(.., true) 2023-12-16 17:40:32 +01:00
Philipp Krones
3596d44988 Merge commit 'a859e5cc1ce100df22346a1005da30532d04de59' into clippyup 2023-12-16 14:12:50 +01:00
Philipp Krones
80ccd6392f
Merge remote-tracking branch 'upstream/master' into rustup 2023-12-16 13:59:56 +01:00
Quinn Sinclair
8892420aa7 New Lint: Result_filter_map
Added the `Result` mirror of `option_filter_map` to catch

```
   .into_iter().filter(Result::is_ok).map(Result::unwrap)
```

changelog: New Lint: [`result_filter_map`]
Co-authored-by: Alex Macleod <alex@macleod.io>
2023-12-16 00:43:52 +01:00
Samuel Tardieu
e52405a859 Do not consider async { (impl IntoFuture).await } as redundant 2023-12-15 22:58:22 +01:00
StackOverflowExcept1on
058b74fce4
Do not lint assertions_on_constants for const _: () = assert!(expr) 2023-12-15 22:52:38 +03:00
J-ZhengLi
eae2317977 improve [cast_sign_loss], to skip warning on mathmatical expression that is always positive 2023-12-14 09:27:01 +08:00
bors
29bdc8b2bc Auto merge of #11953 - Jarcho:issue_11952, r=Alexendoo
Fix binder handling in `unnecessary_to_owned`

fixes #11952

The use of `rebind` instead of `EarlyBinder::bind` isn't technically needed, but it is the semantically correct operation.

changelog: None
2023-12-13 18:57:50 +00:00
bors
1839b79e51 Auto merge of #11956 - intgr:doc_markdown-include-function-parenthesis, r=Alexendoo
[`doc_markdown`] Recognize words followed by empty parentheses `()` for quoting

*Please write a short comment explaining your change (or "none" for internal only changes)*

changelog: [`doc_markdown`] Recognize words followed by empty parentheses for quoting, e.g. `func()`.

---

Developers often write function/method names with trailing `()`, but `doc_markdown` lint did not consider that.

Old clippy suggestion was not very good:

```patch
-/// There is no try (do() or do_not()).
+/// There is no try (do() or `do_not`()).
```

New behavior recognizes function names such as `do()` even they contain no `_`/`::`; and backticks are suggested outside of the `()`:

```patch
-/// There is no try (do() or do_not()).
+/// There is no try (`do()` or `do_not()`).
```
2023-12-13 17:53:59 +00:00
J-ZhengLi
60c059114c [default_numeric_fallback]: don't lint on return and macro calls with stated type 2023-12-13 11:09:08 +08:00
Marti Raudsepp
1f2ca8127c [doc_markdown] Recognize words followed by empty parenthesis () for quoting 2023-12-13 01:16:12 +02:00
bors
c19508b356 Auto merge of #11895 - ericwu2003:useless_vec-FP, r=blyxyas
Useless vec false positive

changelog: [`useless_vec`]: fix false positive in macros.

fixes #11861

We delay the emission of `useless_vec` lints to the check_crate_post stage, which allows us to effectively undo lints if we find that a `vec![]` expression is being used multiple times after macro expansion.
2023-12-12 22:57:24 +00:00
bors
2e96c74dce Auto merge of #11829 - J-ZhengLi:issue11438, r=matthiaskrgr
new lint to detect infinite loop

closes: #11438

changelog: add new lint to detect infinite loop

~*I'll change the lint name*~. Should I name it  `infinite_loop` or `infinite_loops` is fine? Ahhhh, English is hard...
2023-12-12 17:53:51 +00:00
Eric
884bec3d85 emit lints in check_crate_post for useless_vec
this fixes issue #11861 by adding an extra map to
keep track of which spans are ok to lint
2023-12-12 08:47:22 -08:00
Guillaume Gomez
2c867ce01e Add ui tests for unconditional_recursion lint 2023-12-12 15:37:51 +01:00
Guillaume Gomez
5accd517ee Add ui test for write_and_append lint 2023-12-12 14:56:35 +01:00
Jason Newcomb
27c5b21fb6 Fix binder handling in unnecessary_to_owned 2023-12-11 13:52:55 -05:00
bors
2a1645d009 Auto merge of #11878 - samueltardieu:uninhabited_reference, r=flip1995
uninhabited_reference: new lint

Close #11851

The lint is implemented on function parameters and return types, as this is the place where the risk of exchanging references to uninhabited types is the highest. Other constructs, such as in a local variable,
would require the use of `unsafe` and will clearly be done on purpose.

changelog: [`uninhabited_reference`]: new lint
2023-12-11 09:28:54 +00:00
Jason Newcomb
184845fb0c Fix is_from_proc_macro patterns 2023-12-10 15:36:31 -05:00
Samuel Tardieu
cdfa38a9d1 new lint: uninhabited_reference 2023-12-08 17:21:30 +01:00