Commit graph

19223 commits

Author SHA1 Message Date
bors
aceeb54b75 Auto merge of #12405 - PartiallyTyped:12404, r=blyxyas
Added msrv to threadlocal initializer check

closes: #12404
changelog:[`thread_local_initializer_can_be_made_const`]: Check for MSRV (>= 1.59) before processing.
2024-03-03 23:01:37 +00:00
bors
30642113b2 Auto merge of #12406 - MarcusGrass:fix-duplicate-std-instead-of-core, r=Alexendoo
Dedup std_instead_of_core by using first segment span for uniqueness

Relates to #12379.

Instead of checking that the paths have an identical span, it checks that the relevant `std` part of the path segment's span is identical. Added a multiline test, because my first implementation was worse and failed that, then I realized that you could grab the span off the first_segment `Ident`.

I did find another bug that isn't addressed by this, and that exists on master as well.

The path:
```Rust
use std::{io::Write, fmt::Display};
```

Will get fixed into:
```Rust
use core::{io::Write, fmt::Display};
```

Which doesn't compile since `io::Write` isn't in `core`, if any of those paths are present in `core` it'll do the replace and cause a miscompilation. Do you think I should file a separate bug for that? Since `rustfmt` default splits those up it isn't that big of a deal.

Rustfmt:
```Rust
// Pre
use std::{io::Write, fmt::Display};
// Post
use std::fmt::Display;
use std::io::Write;
```
---

changelog: [`std_instead_of_core`]: Fix duplicated output on multiple imports
2024-03-03 18:22:40 +00:00
MarcusGrass
3735bf93ff
Working but not with mixed imports 2024-03-03 17:23:11 +01:00
MarcusGrass
a2e4ef294c
dump bugged fix 2024-03-03 17:17:58 +01:00
Quinn Sinclair
08459b4dae Added msrv to threadlocal initializer 2024-03-03 15:43:09 +01:00
MarcusGrass
74cba639e9
Dedup std_instead_of_core by using first segment span for uniqueness 2024-03-03 15:30:49 +01:00
bors
28e11b31de Auto merge of #12400 - samueltardieu:issue-12395, r=Alexendoo
[`let_underscore_untyped`]: fix false positive on async function

changelog: [`let_underscore_untyped`]: fix false positive on async function

Fix #12395
2024-03-03 13:20:11 +00:00
Samuel Tardieu
1df2854ac3 [let_underscore_untyped]: fix false positive on async function 2024-03-03 14:03:02 +01:00
bors
5e0afee334 Auto merge of #12394 - CBSpeir:issue-12390-refactor, r=Alexendoo
Refactor lints in clippy_lints::attrs into separate submodules/files

This pull request contains the changes requested in issue #12390.

changelog: none
2024-03-02 14:32:43 +00:00
Christopher B. Speir
1580af6b55 Refactor lints in clippy_lints::attrs into separate submodules/files 2024-03-02 07:20:25 -06:00
bors
346b094a11 Auto merge of #12218 - jhpratt:manifest-options-doc, r=blyxyas
Document manifest options

All built-in cargo commands have this output included when run with `cargo foo --help`. Clippy is the only exception, so I have copied the text here. As far as I can tell, the flags come from Cargo itself and not clippy, but the user almost certainly does not care about that.

```text
Manifest Options:
      --manifest-path <PATH>  Path to Cargo.toml
      --frozen                Require Cargo.lock and cache are up to date
      --locked                Require Cargo.lock is up to date
      --offline               Run without accessing the network
```

changelog: Add the standard Manifest Options section to the `--help` output
2024-03-01 12:13:24 +00:00
bors
e865dca4d7 Auto merge of #12010 - granddaifuku:fix/manual-memcpy-indexing-for-multi-dimension-arrays, r=Alexendoo
fix: `manual_memcpy` wrong indexing for multi dimensional arrays

fixes: #9334

This PR fixes an invalid suggestion for multi-dimensional arrays.

For example,
```rust
let src = vec![vec![0; 5]; 5];
let mut dst = vec![0; 5];

for i in 0..5 {
    dst[i] = src[i][i];
}
```

For the above code, Clippy suggests `dst.copy_from_slice(&src[i]);`, but it is not compilable because `i` is only used to loop the array.
I adjusted it so that Clippy `manual_memcpy` works properly for multi-dimensional arrays.

changelog: [`manual_memcpy`]: Fixes invalid indexing suggestions for multi-dimensional arrays
2024-03-01 12:05:03 +00:00
Jacob Pratt
c5f819854c
Document manifest options 2024-03-01 13:00:00 +01:00
bors
225d3771d7 Auto merge of #12276 - PartiallyTyped:hide-thread-local, r=blyxyas
Fix FP in `threadlocal!` when falling back to `os_local`

**Issue**: The lint always triggers for some targets.
**Why**: The lint assumes an `__init` function is not present for const initializers.
This does not hold for all targets. Some targets always have an initializer function.
**Fix**: If an initializer function exists, we check that it is not a `const` fn.

Lint overview before the patch:

1. Outside `threadlocal!`, then exit early.
2. In `threadlocal!` and `__init` does not exist => is const already, exit early.
3. In `threadlocal!` and `__init` exists and `__init` body can be `const` => we lint.

Lint overview after the patch:

1. Outside `threadlocal!`, then exit early.
2. In `threadlocal!` and `__init` does not exist => is const already, exit early.
3. In `threadlocal!` and `__init` exists and is `const fn` => is const already, exit early.
4. In `threadlocal!` and `__init` exists and is not `const fn` and `__init` body can be `const` => we lint.

The patch adds step 3.

changelog: Fixed fp in [`thread_local_initializer_can_be_made_const`] where fallback implementation of `threadlocal!` was always linted.

## Verifying the changes
For each of these platforms [ mac, x86_64-windows-gnu, x86_64-windows-msvc ]:

1. switched to master, ran bless. Found a failure for windows-gnu.
2. switched to patch, ran bless. Success for all three platforms.

## How platform affects the lint:

The compiler performs a [conditional compilation depending on platform features](https://doc.rust-lang.org/src/std/sys/common/thread_local/mod.rs.html). The `os_local` fallback includes a call to `__init`, without step 3, we lint in all cases.

```rust
cfg_if::cfg_if! {
    if #[cfg(any(all(target_family = "wasm", not(target_feature = "atomics")), target_os = "uefi"))] {
        #[doc(hidden)]
        mod static_local;
        #[doc(hidden)]
        pub use static_local::{Key, thread_local_inner};
    } else if #[cfg(target_thread_local)] {
        #[doc(hidden)]
        mod fast_local;
        #[doc(hidden)]
        pub use fast_local::{Key, thread_local_inner};
    } else {
        #[doc(hidden)]
        mod os_local;
        #[doc(hidden)]
        pub use os_local::{Key, thread_local_inner};
    }
}
```

r? `@llogiq`
2024-03-01 00:03:52 +00:00
Quinn Sinclair
bb1ee8746e Fixed FP for thread_local_initializer_can_be_made_const for os_local
`os_local` impl of `thread_local` — regardless of whether it is const and
unlike other implementations — includes an `fn __init(): EXPR`.

Existing implementation of the lint checked for the presence of said
function and whether the expr can be made const. Because for `os_local`
we always have an `__init()`, it triggers for const implementations.

The solution is to check whether the `__init()` function is already const.
If it is `const`, there is nothing to do. Otherwise, we verify that we can
make it const.

Co-authored-by: Alejandra González <blyxyas@gmail.com>
2024-03-01 00:41:14 +01:00
bors
3b8da4ac4b Auto merge of #12382 - Alexendoo:macos-ci, r=flip1995
Bump macOS CI version to 13

I looked into the random failures we've been getting on macOS CI, not entirely sure what is going on but it seems to be an issue out of our department. A [plain driver](314425001d/src/driver.rs) being ran on the test files [without `ui_test` or any special flags](314425001d/src/driver.rs) hit the same issue

It didn't occur on `macos-13` the few times I tried it though so let's upgrade to that. [The current `macos-latest` refers to `macos-12`](https://github.com/actions/runner-images?tab=readme-ov-file#available-images), later this year it will refer to `macos-14` which runs on `aarch64` so specifying the version for our x64 macOS tests will also save a future headache

r? `@flip1995`

changelog: none
2024-02-29 16:14:14 +00:00
Alex Macleod
ce4b81d2a7 Bump macOS CI version to 13 2024-02-29 14:54:37 +00:00
bors
00ff8c92d3 Auto merge of #12354 - GuillaumeGomez:mixed_attributes_style, r=llogiq
Add new `mixed_attributes_style` lint

Add a new lint to detect cases where both inner and outer attributes are used on a same item.

r? `@llogiq`

----

changelog: Add new [`mixed_attributes_style`] lint
2024-02-29 11:44:51 +00:00
bors
04b74ee392 Auto merge of #12344 - CBSpeir:alphabetize-affected-lints, r=flip1995
Alphabetize configuration options and lints in Clippy documentation

changelog: alphabetize configuration options and affected lints listed in section 3.1. of the Clippy Documentation

r? blyxyas
2024-02-29 11:15:53 +00:00
bors
139191b8b7 Auto merge of #12380 - Ethiraric:fix-12358, r=llogiq
[`redundant_closure_call`]: Don't lint if closure origins from a macro

The following code used to trigger the lint:
```rs
 macro_rules! make_closure {
     () => {
         (|| {})
     };
 }
 make_closure!()();
```
The lint would suggest to replace `make_closure!()()` with `make_closure!()`, which changes the code and removes the call to the closure from the macro. This commit fixes that.

Fixes #12358

----

changelog: [`redundant_closure_call`]: If `x!()` returns a closure, don't suggest replacing `x!()()` with `x!()`
2024-02-28 19:13:13 +00:00
Ethiraric
0d59345907 [redundant_closure_call]: Don't lint if closure origins from a macro
The following code used to trigger the lint:
```rs
 macro_rules! make_closure {
     () => {
         (|| {})
     };
 }
 make_closure!()();
```
The lint would suggest to replace `make_closure!()()` with
`make_closure!()`, which changes the code and removes the call to the
closure from the macro. This commit fixes that.

Fixes #12358
2024-02-28 19:17:37 +01:00
bors
af91e6ea8c Auto merge of #12374 - Alexendoo:duplicate-diagnostics, r=Manishearth
Show duplicate diagnostics in UI tests by default

Duplicated diagnostics can indicate where redundant work is being done, this PR doesn't fix any of that but does indicate in which tests they're occurring for future investigation or to catch issues in future lints

changelog: none
2024-02-28 16:19:08 +00:00
bors
e450a27a20 Auto merge of #12372 - GuillaumeGomez:fix-nonminimal_bool-regression, r=flip1995
Fix `nonminimal_bool` lint regression

Fixes #12371.
Fixes #12369.

cc `@RalfJung`

The problem was an invalid condition. Shame on me...

changelog: Fix `nonminimal_bool` lint regression
2024-02-28 15:30:49 +00:00
bors
b4021ee114 Auto merge of #12375 - GuillaumeGomez:improve-code, r=flip1995
Improve `is_lint_level` code

Since https://github.com/rust-lang/rust/pull/121230 was merged, we can now rely on `Level` directly instead of keeping the list of symbols to check in clippy.

changelog: Improve `is_lint_level` code
2024-02-28 15:21:58 +00:00
Guillaume Gomez
41a351665f Improve is_lint_level code 2024-02-28 15:14:22 +01:00
Alex Macleod
733e1d43c7 Show duplicate diagnostics in UI tests by default 2024-02-28 13:24:14 +00:00
Guillaume Gomez
8473716f6e Add ui regression test for #12371 2024-02-28 12:48:00 +01:00
Guillaume Gomez
ebf20954ee Fix invalid condition in nonminimal_bool lint 2024-02-28 12:47:45 +01:00
bors
4c1d05cfa1 Auto merge of #12362 - Ethiraric:fix-11935, r=llogiq
[`map_entry`]: Check insert expression for map use

The lint makes sure that the map is not used (borrowed) before the call to `insert`. Since the lint creates a mutable borrow on the map with the `Entry`, it wouldn't be possible to replace such code with `Entry`. However, expressions up to the `insert` call are checked, but not expressions for the arguments of the `insert` call itself. This commit fixes that.

Fixes #11935

----

changelog: [`map_entry`]: Fix false positive when borrowing the map in the `insert` call
2024-02-27 18:53:25 +00:00
Yudai Fukushima
dfedadc179 fix: manual_memcpy wrong suggestion for multi dimensional arrays
chore: rebase master

chore: replace $DIR

fix: check bases does not contain reference to loop index

fix: grammatical mistake

fix: style
2024-02-28 03:48:49 +09:00
bors
4155becb2a Auto merge of #12365 - Ethiraric:fix-11968, r=Alexendoo
[`unnecessary_cast`]: Avoid breaking precedence

 If the whole cast expression is a unary expression (`(*x as T)`) or an  addressof expression (`(&x as T)`), then not surrounding the suggestion  into a block risks us changing the precedence of operators if the cast  expression is followed by an operation with higher precedence than the  unary operator (`(*x as T).foo()` would become `*x.foo()`, which  changes what the `*` applies on).
The same is true if the expression encompassing the cast expression is a unary expression or an addressof expression.

The lint supports the latter case, but missed the former one. This PR fixes that.

Fixes #11968

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

changelog: [`unnecessary_cast`]: Avoid breaking precedence with unary operators (`(*x as T).foo()` --  before: `*x.foo()` -- now: `{*x}.foo()`)
2024-02-27 17:20:45 +00:00
Ethiraric
c6cb0e99f3 [unnecessary_cast]: Avoid breaking precedence
If the whole cast expression is a unary expression (`(*x as T)`) or an
addressof expression (`(&x as T)`), then not surrounding the suggestion
into a block risks us changing the precedence of operators if the cast
expression is followed by an operation with higher precedence than the
unary operator (`(*x as T).foo()` would become `*x.foo()`, which changes
what the `*` applies on).
The same is true if the expression encompassing the cast expression is a
unary expression or an addressof expression.

The lint supports the latter case, but missed the former one. This PR
fixes that.

Fixes #11968
2024-02-27 16:27:12 +01:00
Guillaume Gomez
f30138623b Update ui tests 2024-02-27 15:22:39 +01:00
Guillaume Gomez
28738234ac Add ui test for mixed_attributes_style 2024-02-27 15:22:39 +01:00
Guillaume Gomez
9f4a58f616 Add new mixed_attributes_style lint 2024-02-27 15:22:39 +01:00
Ethiraric
03bb7908b9 [map_entry]: Check insert expression for map use
The lint makes sure that the map is not used (borrowed) before the call
to `insert`. Since the lint creates a mutable borrow on the map with the
`Entry`, it wouldn't be possible to replace such code with `Entry`.
However, expressions up to the `insert` call are checked, but not
expressions for the arguments of the `insert` call itself. This commit
fixes that.

Fixes #11935
2024-02-27 15:20:49 +01:00
bors
10136170fe Auto merge of #12363 - oli-obk:bump_ui_test, r=flip1995
lower `bstr` version requirement to `1.6.0`

test changes are due to https://github.com/oli-obk/ui_test/pull/201 (cc `@Jarcho)`

changelog: none
2024-02-27 13:46:14 +00:00
Oli Scherer
592fe89997 lower bstr version requirement to 1.6.0 2024-02-27 13:34:01 +00:00
bors
e33cba523a Auto merge of #12126 - teor2345:patch-1, r=llogiq
Fix sign-handling bugs and false negatives in `cast_sign_loss`

**Note: anyone should feel free to move this PR forward, I might not see notifications from reviewers.**

changelog: [`cast_sign_loss`]: Fix sign-handling bugs and false negatives

This PR fixes some arithmetic bugs and false negatives in PR #11883 (and maybe earlier PRs).
Cc `@J-ZhengLi`

I haven't updated the tests yet. I was hoping for some initial feedback before adding tests to cover the cases listed below.

Here are the issues I've attempted to fix:

#### `abs()` can return a negative value in release builds

Example:
```rust
i32::MIN.abs()
```
https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=022d200f9ef6ee72f629c0c9c1af11b8

Docs: https://doc.rust-lang.org/std/primitive.i32.html#method.abs

Other overflows that produce negative values could cause false negatives (and underflows could produce false positives), but they're harder to detect.

#### Values with uncertain signs can be positive or negative

Any number of values with uncertain signs cause the whole expression to have an uncertain sign, because an uncertain sign can be positive or negative.

Example (from UI tests):
```rust
fn main() {
    foo(a: i32, b: i32, c: i32) -> u32 {
        (a * b * c * c) as u32
        //~^ ERROR: casting `i32` to `u32` may lose the sign of the value
    }

    println!("{}", foo(1, -1, 1));
}
```
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=165d2e2676ee8343b1b9fe60db32aadd

#### Handle `expect()` the same way as `unwrap()`

Since we're ignoring `unwrap()` we might as well do the same with `expect()`.

This doesn't seem to have tests but I'm happy to add some like `Some(existing_test).unwrap() as u32`.

#### A negative base to an odd exponent is guaranteed to be negative

An integer `pow()`'s sign is only uncertain when its operants are uncertain. (Ignoring overflow.)

Example:
```rust
((-2_i32).pow(3) * -2) as u32
```

This offsets some of the false positives created by one or more uncertain signs producing an uncertain sign. (Rather than just an odd number of uncertain signs.)

#### Both sides of a multiply or divide should be peeled recursively

I'm not sure why the lhs was peeled recursively, and the rhs was left intact. But the sign of any sequence of multiplies and divides is determined by the signs of its operands. (Ignoring overflow.)

I'm not sure what to use as an example here, because most expressions I want to use are const-evaluable.

But if `p()` is [a non-const function that returns a positive value](https://doc.rust-lang.org/std/primitive.i32.html#method.isqrt), and if the lint handles unary negation, these should all lint:
```rust
fn peel_all(x: i32) {
    (-p(x) * -p(x) * -p(x)) as u32;
    ((-p(x) * -p(x)) * -p(x)) as u32;
    (-p(x) * (-p(x) * -p(x))) as u32;
}
```

#### The right hand side of a Rem doesn't change the sign

Unlike Mul and Div,
> Given remainder = dividend % divisor, the remainder will have the same sign as the dividend.
https://doc.rust-lang.org/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators

I'm not sure what to use as an example here, because most expressions I want to use are const-evaluable.

But if `p()` is [a non-const function that returns a positive value](https://doc.rust-lang.org/std/primitive.i32.html#method.isqrt), and if the lint handles unary negation, only the first six expressions should lint.

The expressions that start with a constant should lint (or not lint) regardless of whether the lint supports `p()` or unary negation, because only the dividend's sign matters.

Example:
```rust
fn rem_lhs(x: i32) {
    (-p(x) % -1) as u32;
    (-p(x) % 1) as u32;
    (-1 % -p(x)) as u32;
    (-1 % p(x)) as u32;
    (-1 % -x) as u32;
    (-1 % x) as u32;
    // These shouldn't lint:
    (p(x) % -1) as u32;
    (p(x) % 1) as u32;
    (1 % -p(x)) as u32;
    (1 % p(x)) as u32;
    (1 % -x) as u32;
    (1 % x) as u32;
}
```

#### There's no need to bail on other expressions

When peeling, any other operators or expressions can be left intact and sent to the constant evaluator.

If these expressions can be evaluated, this offsets some of the false positives created by one or more uncertain signs producing an uncertain sign. If not, they end up marked as having uncertain sign.
2024-02-27 05:38:40 +00:00
bors
fb060815b3 Auto merge of #11136 - y21:enhance_read_line_without_trim, r=dswij
[`read_line_without_trim`]: detect string literal comparison and `.ends_with()` calls

This lint now also realizes that a comparison like `s == "foo"` and calls such as `s.ends_with("foo")` will fail if `s` was initialized by a call to `Stdin::read_line` (because of the trailing newline).

changelog: [`read_line_without_trim`]: detect string literal comparison and `.ends_with()` calls

r? `@giraffate` assigning you because you reviewed #10970 that added this lint, so this is kinda a followup PR ^^
2024-02-27 03:36:12 +00:00
bors
d12b53e481 Auto merge of #12116 - J-ZhengLi:issue12101, r=Alexendoo
fix suggestion error in [`useless_vec`]

fixes: #12101

---

changelog: fix suggestion error in [`useless_vec`]

r+ `@matthiaskrgr` since they opened the issue?
2024-02-26 22:38:24 +00:00
teor
1e3c55eea2
Remove redundant uncertain_counts 2024-02-27 07:34:18 +10:00
Christopher B. Speir
d85642e6e8 Alphabetize configuration options and lints in Clippy doc 2024-02-26 14:55:45 -06:00
y21
fd85db3636 restructure lint code, update description, more cases 2024-02-26 20:24:46 +01:00
y21
cfddd91c91 [read_line_without_trim]: catch string eq checks 2024-02-26 20:19:15 +01:00
bors
1c5094878b Auto merge of #12342 - lucarlig:empty-docs, r=llogiq
Empty docs

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

changelog: [`empty_doc`]: Detects documentation that is empty.
changelog: Doc comment lints now trigger for struct field and enum variant documentation
2024-02-26 18:03:13 +00:00
bors
d71899573a Auto merge of #12355 - Ethiraric:fix-11927, r=Alexendoo
[`box_default`]: Preserve required path segments

When encountering code such as:
```rs
Box::new(outer::Inner::default())
```
clippy would suggest replacing with `Box::<Inner>::default()`, dropping the `outer::` segment. This behavior is incorrect and that commit fixes it.

What it does is it checks the contents of the `Box::new` and, if it is of the form `A::B::default`, does a text replacement, inserting `A::B` in the `Box`'s quickfix generic list.
If the source does not match that pattern (including `Vec::from(..)` or other `T::new()` calls), we then fallback to the original code.

Fixes #11927

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

changelog: [`box_default`]: Preserve required path segments
2024-02-26 17:25:43 +00:00
Ethiraric
97dc4b22c6 [box_default]: Preserve required path segments
When encountering code such as:
```
Box::new(outer::Inner::default())
```
clippy would suggest replacing with `Box::<Inner>::default()`, dropping
the `outer::` segment. This behavior is incorrect and that commit fixes
it.

What it does is it checks the contents of the `Box::new` and, if it is
of the form `A::B::default`, does a text replacement, inserting `A::B`
in the `Box`'s quickfix generic list.
If the source does not match that pattern (including `Vec::from(..)`
or other `T::new()` calls), we then fallback to the original code.

Fixes #11927
2024-02-26 17:39:00 +01:00
bors
a11875bd22 Auto merge of #12353 - lucarlig:book, r=flip1995
add cargo.toml lint section way of adding lints in the book

changelog: add cargo.toml lint section way of adding lints in the book

as from [discussion on zulip](https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/.E2.9C.94.20clippy.20config)
2024-02-26 15:53:46 +00:00
Philipp Krones
6d0b70e08f
Clean up Allowing/Denying Lints section 2024-02-26 16:43:05 +01:00