Commit graph

7616 commits

Author SHA1 Message Date
bors
8538562429 Auto merge of #13567 - y21:span_debug_assertions, r=flip1995
Add debug assertions for empty replacements and overlapping spans

rustc has debug assertions [^1] [^2] that check that a substitution doesn't have an empty suggestion string and an empty span at the same time, as well as that spans in multipart suggestions don't overlap.
However, since we link to the rustc-dev distributed compiler, these debug assertions are always disabled and so we never actually run them.

This leads to the problem that the debug ICE is not necessarily caught in the PR and only triggered in the rust repo sync, and in one of the last syncs this was a blocker and delayed the sync by several weeks because the fix was not obvious.

So this PR essentially copies the checks over and runs them in clippy debug builds as well, so that we can catch these errors in PRs directly.

-----
As for the second commit, this also *did* cause an ICE in a sync before and was fixed in the sync PR (see https://github.com/rust-lang/rust/pull/120345#issuecomment-1911005554), but it seems like that commit didn't make it back into the clippy repo (cc `@flip1995),` so the fixed code is in the rust repo but not in the clippy repo.

changelog: none

[^1]: https://doc.rust-lang.org/1.82.0/nightly-rustc/src/rustc_errors/diagnostic.rs.html#1019
[^2]: https://doc.rust-lang.org/1.82.0/nightly-rustc/src/rustc_errors/diagnostic.rs.html#932
2024-10-21 08:26:32 +00:00
y21
65eb1ec0fb remove the semicolon for builtin macro call statements in statement_outside_block
The expansion of `asm!()` and `line!()` is not marked as from an expansion, in which case `SourceMap::stmt_span` returns the input span unchanged. So instead of using `stmt_span`, use `mac_call_stmt_semi_span` directly
2024-10-20 19:00:55 +02:00
GnomedDev
a739cc3abe
Stop linting manual_bits in any macro invoke 2024-10-18 21:41:05 +01:00
Philipp Krones
224d1e323a
Merge remote-tracking branch 'upstream/master' into rustup 2024-10-18 13:25:37 +02:00
GnomedDev
42511a3ffa
Add lint for unnecessary lifetime bounded &str return 2024-10-15 17:06:21 +01:00
bors
f444012c4c Auto merge of #13454 - samueltardieu:push-ymnkzlqloptz, r=xFrednet
Use correct std/core prefix in lint output

changelog: none

I was waiting for #13452 to be merged before sending this one. `std` is used instead of `core` when appropriate in messages.
2024-10-14 13:12:22 +00:00
bors
6a281e9a73 Auto merge of #13487 - Coekjan:fix-slice-size-calc-on-ref-ref, r=dswij
Fix lint `manual_slice_size_calculation` when a slice is ref more than once

When a slice is ref more than once, current suggestion given by `manual_slice_size_calculation` is wrong. For example:

```rs
let s: &[i32] = &[1, 2][..];
let ss: &&[i32] = &s;  // <-----

let _ = size_of::<i32>() * ss.len();
```

clippy now suggests:

```patch
- let _ = size_of::<i32>() * ss.len();
+ let _ = size_of_val(ss);
```

However, this can result in calculating the size of `&[i32]`, instead of `[i32]` (this wrong suggestion also leads to `size_of_ref` warning: https://rust-lang.github.io/rust-clippy/master/index.html#/size_of_ref )

Now I am sending this PR to fix this bug, so that clippy will suggest (some deref added):

```patch
- let _ = size_of::<i32>() * ss.len();
+ let _ = size_of_val(*ss);
```

As I am not familiar with current clippy code-base, please correct me if I am not doing well or I can do it better :)

changelog: [`manual_slice_size_calculation`]: fix a bug when a slice is ref more than once.
2024-10-13 15:49:30 +00:00
bors
f883e28e3d Auto merge of #13542 - blyxyas:fix-implicit_saturating_sub, r=y21
[`implicit_saturating_sub`] Fix suggestion with a less volatile approach

Related to #13533, such and obvious mistake got pass my watch, quite embarassing :/

Revert #13533 and implement a more robust solution.

Revert "Fix span issue on `implicit_saturating_sub`
This reverts commit 140a1275f2.

changelog: [`lint_name`]: Fix suggestion for `if {} else if {} else {}` cases

r? `@y21`
2024-10-13 15:24:05 +00:00
bors
04849bd7d9 Auto merge of #13510 - alex-semenyuk:cleanup_const_float_classify, r=llogiq
Cleanup `const_float_classify`

As mentioned at #13508 `const_float_classify` has been stabilized recently in https://github.com/rust-lang/rust/pull/130157 and can be cleanup

Close #13508

changelog: [none]
2024-10-13 09:17:14 +00:00
Samuel Tardieu
46a0770102 Use correct std/core prefix in lint output 2024-10-13 10:48:27 +02:00
bors
c71f0bebd2 Auto merge of #13334 - nyurik:ascii-str-eq, r=xFrednet
Add manual_ignore_cast_cmp lint

```rust
// bad
fn compare(a: &str, b: &str) -> bool {
    a.to_ascii_lowercase() == b.to_ascii_lowercase()
    || a.to_ascii_lowercase() == "abc"
}

// good
fn compare(a: &str, b: &str) -> bool {
   a.eq_ignore_ascii_case(b)
   || a.eq_ignore_ascii_case("abc")
}
```

- [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`

changelog: New lint: [`manual_ignore_case_cmp`] `perf`
[#13334](https://github.com/rust-lang/rust-clippy/pull/13334)

Closes #13204
2024-10-13 07:34:38 +00:00
Trevor Gross
3c43a60d06 Stabilize const_option
This makes the following API stable in const contexts:

    impl<T> Option<T> {
        pub const fn as_mut(&mut self) -> Option<&mut T>;
        pub const fn expect(self, msg: &str) -> T;
        pub const fn unwrap(self) -> T;
        pub const unsafe fn unwrap_unchecked(self) -> T;
        pub const fn take(&mut self) -> Option<T>;
        pub const fn replace(&mut self, value: T) -> Option<T>;
    }

    impl<T> Option<&T> {
        pub const fn copied(self) -> Option<T>
        where T: Copy;
    }

    impl<T> Option<&mut T> {
        pub const fn copied(self) -> Option<T>
        where T: Copy;
    }

    impl<T, E> Option<Result<T, E>> {
        pub const fn transpose(self) -> Result<Option<T>, E>
    }

    impl<T> Option<Option<T>> {
        pub const fn flatten(self) -> Option<T>;
    }

The following functions make use of the unstable
`const_precise_live_drops` feature:

- `expect`
- `unwrap`
- `unwrap_unchecked`
- `transpose`
- `flatten`

Fixes: <https://github.com/rust-lang/rust/issues/67441>
2024-10-12 17:07:13 -04:00
bors
55f6029baa Auto merge of #13444 - kpreid:fix-8524-private-rep, r=blyxyas
`module_name_repetitions`: don't warn if the item is in a private module.

Fixes <https://github.com/rust-lang/rust-clippy/issues/8524>.

There is still a warning (as there should be) if the item is reexported by name, but not by glob; that would require further work to examine the names in the glob, and I haven't looked into that.

Credit to `@Centri3` for suggesting approximately this simple fix in <https://github.com/rust-lang/rust-clippy/issues/8524#issuecomment-1729036149>. However, per later comment <https://github.com/rust-lang/rust-clippy/issues/8524#issuecomment-2035836495>, I am not making it configuration-dependent, but *always* checking public items in public modules only.

changelog: [`module_name_repetitions`]: don't warn if the item is in a private module.
2024-10-12 16:46:31 +00:00
blyxyas
2b562dece6 Fix suggestion with a less volatile approach
Revert "Fix span issue on `implicit_saturating_sub`"
This reverts commit 140a1275f2.
2024-10-12 17:43:06 +02:00
bors
b85f632607 Auto merge of #13528 - zvavybir:master, r=Alexendoo
Improved wording of or_fun_call lint

The current wording (e.g. ``use of `ok_or` followed by a function call``) is potentially confusing (at least it confused me) by suggesting that the function that follows the (in this case) `ok_or` is the problem and not the function that is an argument to it.

The code in my program that triggered the confusing message is the following:
```rust
let file_id = buf
    .lines()
    .next()
    .ok_or((
        InternalError::ProblemReadingFromInbox,
        anyhow!("No first line in inbox response ({file:?}): {buf:?}"),
    ))
    .html_context(stream, lang)?;
```
I thought that `html_context` was the problem and that I should do something along the following lines:
```rust
let file_id = buf
    .lines()
    .next()
    .ok_or_else(
        (
            InternalError::ProblemReadingFromInbox,
            anyhow!("No first line in inbox response ({file:?}): {buf:?}"),
        ),
        html_context(stream, lang),
    )?
```
This is of course wrong.  My confusion was only cleared up through the help message indicating what I should try instead.

If someone has a better idea of a replacement wording (currently e.g. ``` function call inside of `ok_or` ```), I'm all ears.

changelog: none
2024-10-11 15:01:07 +00:00
bors
f5cc292830 Auto merge of #131045 - compiler-errors:remove-unnamed_fields, r=wesleywiser
Retire the `unnamed_fields` feature for now

`#![feature(unnamed_fields)]` was implemented in part in #115131 and #115367, however work on that feature has (afaict) stalled and in the mean time there have been some concerns raised (e.g.[^1][^2]) about whether `unnamed_fields` is worthwhile to have in the language, especially in its current desugaring. Because it represents a compiler implementation burden including a new kind of anonymous ADT and additional complication to field selection, and is quite prone to bugs today, I'm choosing to remove the feature.

However, since I'm not one to really write a bunch of words, I'm specifically *not* going to de-RFC this feature. This PR essentially *rolls back* the state of this feature to "RFC accepted but not yet implemented"; however if anyone wants to formally unapprove the RFC from the t-lang side, then please be my guest. I'm just not totally willing to summarize the various language-facing reasons for why this feature is or is not worthwhile, since I'm coming from the compiler side mostly.

Fixes #117942
Fixes #121161
Fixes #121263
Fixes #121299
Fixes #121722
Fixes #121799
Fixes #126969
Fixes #131041

Tracking:
* https://github.com/rust-lang/rust/issues/49804

[^1]: https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Unnamed.20struct.2Funion.20fields
[^2]: https://github.com/rust-lang/rust/issues/49804#issuecomment-1972619108
2024-10-11 13:11:13 +00:00
bors
47903dbf97 Auto merge of #13532 - y21:issue13531, r=Alexendoo
Only emit `manual_c_str_literals` in >= Edition 2021

Fixes #13531

changelog: none
2024-10-11 12:47:38 +00:00
bors
05f3793392 Auto merge of #13534 - GnomedDev:fix-large-stack-arrays-nested-item, r=flip1995
Fix large_stack_arrays triggering when nesting const items

Fixes #13529.

r? `@flip1995`

changelog: [`large_stack_arrays`]: No longer triggers in static/const context when using nested items
2024-10-11 09:04:46 +00:00
bors
14c05c974c Auto merge of #13533 - blyxyas:fix-implicit_saturating_sub, r=dswij
Fix span issue on `implicit_saturating_sub`

Fixes #13524

changelog: [`implicit_saturating_sub`]: Fix span issue on else blocks
2024-10-11 06:25:08 +00:00
GnomedDev
87b4c1ffb7
Fix large_stack_arrays triggering when nesting const items 2024-10-10 22:01:46 +01:00
blyxyas
140a1275f2 Fix span issue on implicit_saturating_sub
Fixes #13524
2024-10-10 19:10:04 +02:00
Alexey Semenyuk
cb19f23c79 Clean up const_float_classify leftovers 2024-10-10 22:08:45 +05:00
y21
2b86ffc57e only emit manual_c_str_literals in >= edition2021 2024-10-10 18:08:40 +02:00
bors
806a9dfddd Auto merge of #13464 - y21:issue13458, r=flip1995
Don't warn on proc macro generated code in `needless_return`

Fixes #13458
Fixes #13457
Fixes #13467
Fixes #13479
Fixes #13481
Fixes #13526
Fixes #13486

The fix is unfortunately a little more convoluted than just simply adding a `is_from_proc_macro`. That check *does*  fix the issue, however it also introduces a bunch of false negatives in the tests, specifically when the returned expression is in a different syntax context, e.g. `return format!(..)`.

The proc macro check builds up a start and end pattern based on the HIR nodes and compares it to a snippet of the span, however that would currently fail for `return format!(..)` because we would have the patterns `("return", <something inside of the format macro>)`, which doesn't compare equal. So we now return an empty string pattern for when it's in a different syntax context.

"Hide whitespace" helps a bit for reviewing the proc macro detection change

changelog: none
2024-10-10 11:34:13 +02:00
bors
8e60f143d8 Auto merge of #13464 - y21:issue13458, r=flip1995
Don't warn on proc macro generated code in `needless_return`

Fixes #13458
Fixes #13457
Fixes #13467
Fixes #13479
Fixes #13481
Fixes #13526
Fixes #13486

The fix is unfortunately a little more convoluted than just simply adding a `is_from_proc_macro`. That check *does*  fix the issue, however it also introduces a bunch of false negatives in the tests, specifically when the returned expression is in a different syntax context, e.g. `return format!(..)`.

The proc macro check builds up a start and end pattern based on the HIR nodes and compares it to a snippet of the span, however that would currently fail for `return format!(..)` because we would have the patterns `("return", <something inside of the format macro>)`, which doesn't compare equal. So we now return an empty string pattern for when it's in a different syntax context.

"Hide whitespace" helps a bit for reviewing the proc macro detection change

changelog: none
2024-10-10 09:17:20 +00:00
Matthias Kaak
8c46c498d9 Improved wording of or_fun_call lint
Signed-off-by: Matthias Kaak <zvavybir@zvavybir.eu>
2024-10-10 08:05:41 +00:00
bors
1f8f982f22 Auto merge of #13504 - samueltardieu:needless-raw-strings, r=Alexendoo
Check for needless raw strings in `format_args!()` template as well

changelog: [`needless_raw_strings`, `needless_raw_string_hashes`]: check `format_args!()` template as well

Fix #13503
2024-10-09 01:35:08 +00:00
bors
d9c8d976cb Auto merge of #13512 - samueltardieu:issue-13511, r=xFrednet
`infinite_loop`: continuing an outer loop leaves the inner loop

changelog: [`infinite_loop`]: detect a `continue` targeting an outer loop

Fix #13511
2024-10-08 08:49:07 +00:00
Samuel Tardieu
5e78c15caa raw_strings: handle format template as well 2024-10-07 18:29:24 +02:00
bors
b013e69692 Auto merge of #13496 - y21:issue10619, r=Alexendoo
Show interior mutability chain in `mutable_key_type`

Fixes #10619

Just ran into this myself and I definitely agree it's not very nice to have to manually go through all the types involved to figure out why this happens and to evaluate if this is really a problem (knowing if the field of a struct is something that a hash impl relies on), so this changes the lint to emit notes for each step involved.

changelog: none
2024-10-07 15:32:34 +00:00
Samuel Tardieu
99ce411ed6 infinite_loop: continuing an outer loop leaves the inner loop 2024-10-06 19:19:27 +02:00
bors
2d2e8cc21f Auto merge of #13485 - GnomedDev:reduce-large-threshold, r=xFrednet
Reduce default 'large array' threshold

As-is this threshold is `512kb`, but as #9449 points out this is way too high for most people to consider sensible (why would you want to copy `256kb` of data around on the stack or duplicate it via `const`) and didn't get any discussion when originally added. This PR reduces it the threshold to `1kb`, which is higher than the issue says ("a few cpu words") but helps out for actual codebases.

While reducing this, I found that `large_stack_arrays` was triggering for statically promoted arrays in constants/statics, so I also fixed that up as seen in the difference to [array_size_threshold.stderr](https://github.com/rust-lang/rust-clippy/compare/master...GnomedDev:rust-clippy:reduce-large-threshold?expand=1#diff-4c2a2a855d9ff7777f1d385be0c1bede2a3fc8aaab94837cde27a35235233fc7).

Closes #9449.

changelog: [`large_stack_arrays`]: No longer triggers in `static`/`const` context
changelog: [`large_const_arrays`]: Changed the default of [`array-size-threshold`] from `512kb` to `16kb`
2024-10-06 11:24:28 +00:00
bors
d0507302fc Auto merge of #130540 - veera-sivarajan:fix-87525, r=estebank
Add a Lint for Pointer to Integer Transmutes in Consts

Fixes #87525

This PR adds a MirLint for pointer to integer transmutes in const functions and associated consts. The implementation closely follows this comment: https://github.com/rust-lang/rust/pull/85769#issuecomment-880969112. More details about the implementation can be found in the comments.

Note: This could break some sound code as mentioned by RalfJung in https://github.com/rust-lang/rust/pull/85769#issuecomment-886491680:

> ... technically const-code could transmute/cast an int to a ptr and then transmute it back and that would be correct -- so the lint will deny some sound code. Does not seem terribly likely though.

References:
1. https://doc.rust-lang.org/std/mem/fn.transmute.html
2. https://doc.rust-lang.org/reference/items/associated-items.html#associated-constants
2024-10-06 02:39:23 +00:00
bors
753629bb33 Auto merge of #13412 - GnomedDev:regex-comp-in-loop, r=y21
Implement lint for regex::Regex compilation inside a loop

Closes #598.

Seems like a pretty simple one, I'm not sure if I sorted out all the lint plumbing correctly because I was adding it to the existing regex pass, but seems to work. The name is a bit jank and I'm super open to suggestions for changing it.

changelog: [`regex_creation_in_loops`]: Added lint for Regex compilation inside loops.
2024-10-05 18:41:45 +00:00
GnomedDev
196dbcf6d5
Avoid linting for Regexes compiled in items defined in loops 2024-10-05 17:10:21 +01:00
Veera
98b59a1cf6 Add a Lint for Pointer to Integer Transmutes in Consts 2024-10-05 12:48:02 +00:00
Ralf Jung
7f390d6fe0 move f16/f128 const fn under f16/f128 feature gate 2024-10-05 10:13:18 +02:00
Camille GILLOT
810bd5dd09 Bless clippy. 2024-10-05 00:19:43 +00:00
GnomedDev
26994e2519
Reduce default 'large array' threshold 2024-10-04 19:07:40 +01:00
GnomedDev
4b7c19018d
Fix large_stack_arrays triggering for static/constants 2024-10-04 19:06:39 +01:00
y21
19d1358b31 print cause chain in mutable_key_type 2024-10-03 21:27:05 +00:00
bors
a01975b152 Auto merge of #13493 - y21:trait_duplication_in_bounds_fix, r=Manishearth
Compare trait references in `trait_duplication_in_bounds` correctly

Fixes #13476
Fixes #11067
Fixes #9915
Fixes #9626

Currently, the `trait_duplication_in_bounds` lints has a helper type for a trait reference that can be used for comparison and hashing, represented as `{trait: Res, generic_args: Vec<Res>}`. However, there are a lot of issues with this. For one, a `Res` can't represent e.g. references, slices, or lots of other types, as well as const generics and associated type equality. In those cases, the lint simply ignores them and has no way of checking if they're actually the same.

So, instead of using `Res` for this, use `SpanlessEq` and `SpanlessHash` for comparisons with the trait path for checking if there are duplicates.

However, using `SpanlessEq` as is alone lead to a false negative in the test. `std::clone::Clone` + `foo::Clone` wasn't recognized as a duplicate, because it has different segments. So this also adds a new "mode" to SpanlessEq which compares by final resolution. (I've been wondering if this can't just be the default but it's quite a large scale change as it affects a lot of lints and I haven't yet looked at all uses of it to see if there are lints that really do care about having exactly the same path segments).

Maybe an alternative would be to turn the hir types/consts into middle types/consts and compare them instead but I'm not sure there's really a good way to do that

changelog: none
2024-10-03 21:16:22 +00:00
y21
d6be597fbc Use SpanlessEq for in trait_bounds lints 2024-10-03 15:49:37 +00:00
Philipp Krones
277c4e4baf Merge commit 'aa0d551351a9c15d8a95fdb3e2946b505893dda8' into clippy-subtree-update 2024-10-03 16:32:51 +02:00
Philipp Krones
d300cdfcda
Merge remote-tracking branch 'upstream/master' into rustup 2024-10-03 14:47:50 +02:00
coekjan
2080634d33
Fix lint manual_slice_size_calculation when the slice is ref more than once 2024-10-03 12:47:15 +08:00
bors
398be8c842 Auto merge of #13443 - SpriteOvO:simplify-option-neg-methods, r=xFrednet
Simplify negative `Option::{is_some_and,is_none_or}`

Closes #13436.

Improved based on the existing lint `nonminimal_bool`, since there is already handling of similar methods `Option::{is_some,is_none}` and `Result::{is_ok,is_err}`, and there is a lot of reusable code.

When `is_some_and` or `is_none_or` have a negation, we invert it into another method by removing the Not sign and inverting the expression in the closure.

For the case where the closure block has statements, currently no simplification is implemented. (Should we do it?)

```rust
// Currently will not simplify this
_ = !opt.is_some_and(|x| {
    let complex_block = 100;
    x == complex_block
});
```

changelog: [`nonminimal_bool`]: Simplify negative `Option::{is_some_and,is_none_or}`
2024-10-02 08:54:12 +00:00
Rob Shearman
c88cb08afc Fix mut_mutex_lock when reference not ultimately mutable
When there is are multiple references where one of the references
isn't mutable then this results in a false-positive for
`mut_mutex_lock` as it only checks the mutability of the first
reference level.

Fix this by using `peel_mid_ty_refs_is_mutable` which correctly
determines whether the reference is ultimately mutable and thus
whether `Mutex::get_lock()` can actually be used.

Fixes #9854
2024-10-01 22:19:42 +02:00
Michael Goulet
3ac3c34951 Remove crashes and fix tests 2024-10-01 13:55:46 -04:00
y21
f06a46ee4d consider wait() calls in nested bodies 2024-10-01 19:21:30 +02:00