New lint: [`derive_partial_eq_without_eq`]
Introduces a new lint, [`derive_partial_eq_without_eq`].
See: #1781 (doesn't close it though).
changelog: add lint [`derive_partial_eq_without_eq`]
Support tool lints with the `#[expect]` attribute (RFC 2383)
This PR fixes the ICE https://github.com/rust-lang/rust/issues/94953 by making the assert for converted expectation IDs conditional.
Additionally, it moves the lint expectation check into a separate query to support rustdoc and other tools. On the way, I've also added some tests to ensure that the attribute works for Clippy and rustdoc lints.
The number of changes comes from the long test file. This may look like a monster PR, this may smell like a monster PR and this may be a monster PR, but it's a harmless monster. 🦕
---
Closes: https://github.com/rust-lang/rust/issues/94953
cc: https://github.com/rust-lang/rust/issues/85549
r? `@wesleywiser`
cc: `@rust-lang/rustdoc`
Track if a where bound comes from a impl Trait desugar
With https://github.com/rust-lang/rust/pull/93803 `impl Trait` function arguments get desugared to hidden where bounds. However, Clippy needs to know if a bound was originally a `impl Trait` or an actual bound. This adds a field to the `WhereBoundPredicate` struct to keep track of this information during AST->HIR lowering.
r? `@cjgillot`
cc `@estebank` (as the reviewer of #93803)
Address `unnecessary_to_owned` false positive
My proposed fix for #8759 is to revise the conditions that delineate `redundant_clone` and `unnecessary_to_owned`:
```rust
// Only flag cases satisfying at least one of the following three conditions:
// * the referent and receiver types are distinct
// * the referent/receiver type is a copyable array
// * the method is `Cow::into_owned`
// This restriction is to ensure there is no overlap between `redundant_clone` and this
// lint. It also avoids the following false positive:
// https://github.com/rust-lang/rust-clippy/issues/8759
// Arrays are a bit of a corner case. Non-copyable arrays are handled by
// `redundant_clone`, but copyable arrays are not.
```
This change causes a few cases that were previously flagged by `unnecessary_to_owned` to no longer be flagged. But one could argue those cases would be better handled by `redundant_clone`.
Closes#8759
changelog: none
Allow inline consts to reference generic params
Tracking issue: #76001
The RFC says that inline consts cannot reference to generic parameters (for now), same as array length expressions. And expresses that it's desirable for it to reference in-scope generics, when array length expressions gain that feature as well.
However it is possible to implement this for inline consts before doing this for all anon consts, because inline consts are only used as values and they won't be used in the type system. So we can have:
```rust
fn foo<T>() {
let x = [4i32; std::mem::size_of::<T>()]; // NOT ALLOWED (for now)
let x = const { std::mem::size_of::<T>() }; // ALLOWED with this PR!
let x = [4i32; const { std::mem::size_of::<T>() }]; // NOT ALLOWED (for now)
}
```
This would make inline consts super useful for compile-time checks and assertions:
```rust
fn assert_zst<T>() {
const { assert!(std::mem::size_of::<T>() == 0) };
}
```
This would create an error during monomorphization when `assert_zst` is instantiated with non-ZST `T`s. A error during mono might sound scary, but this is exactly what a "desugared" inline const would do:
```rust
fn assert_zst<T>() {
struct F<T>(T);
impl<T> F<T> {
const V: () = assert!(std::mem::size_of::<T>() == 0);
}
let _ = F::<T>::V;
}
```
It should also be noted that the current inline const implementation can already reference the type params via type inference, so this resolver-level restriction is not any useful either:
```rust
fn foo<T>() -> usize {
let (_, size): (PhantomData<T>, usize) = const {
const fn my_size_of<T>() -> (PhantomData<T>, usize) {
(PhantomData, std::mem::size_of::<T>())
}
my_size_of()
};
size
}
```
```@rustbot``` label: F-inline_const
Support negative ints in manual_range_contains
fixes: #8721
changelog: Fixes issue where ranges containing ints with different signs would be
incorrect due to comparing as unsigned.
Fix `cast_lossless` to avoid warning on `usize` to `f64` conversion.
Previously, the `cast_lossless` lint would issue a warning on code that
converted a `usize` value to `f64`, on 32-bit targets.
`usize` to `f64` is a lossless cast on 32-bit targets, however there is
no corresponding `f64::from` that takes a `usize`, so `cast_lossless`'s
suggested replacement does not compile.
This PR disables the lint in the case of casting from `usize` or `isize`.
Fixes#3689.
changelog: [`cast_lossless`] no longer gives wrong suggestion on usize,isize->f64
Those lints are trait_duplication_in_bounds and
type_repetition_in_bounds. I don't think those can be fixed on the
Clippy side alone, but need changes in the compiler. So let's move them
to nursery to get the sync through and then fix them on the rustc side.
Also adds a regression test that has to be fixed before they can be
moved back to pedantic.
[FP] identity_op in front of if
fix#8724
changelog: FP: [`identity_op`]: is now allowed in front of if statements, blocks and other expressions where the suggestion would be invalid.
Resolved simular problems with blocks, mathces, and loops.
identity_op always does NOT suggest reducing `0 + if b { 1 } else { 2 } + 3` into `if b { 1 } else { 2 } + 3` even in the case that the expression is in `f(expr)` or `let x = expr;` for now.
Previously, the `cast_lossless` lint would issue a warning on code that
converted a `usize` value to `f64`, on 32-bit targets.
`usize` to `f64` is a lossless cast on 32-bit targets, however there is
no corresponding `f64::from` that takes a `usize`, so `cast_lossless`'s
suggested replacement does not compile.
This PR disables the lint in the case of casting from `usize` or `isize`.
Fixes#3689.
changelog: [`cast_lossless`] no longer gives wrong suggestion on usize->f64
ignore `redundant_pub_crate` in `useless_attribute`
changelog: [`useless_attribute`] no longer lints [`redundant_pub_crate`]
As mentioned in https://github.com/rust-lang/rust-clippy/issues/8732#issuecomment-1106489634
> And it turns out I can't even explicitly allow it at the usage site, because then `clippy::useless_attribute` fires (which would also be a FP?), which is deny-by-default.
>
> Though it does work if I then allow `clippy::useless_attribute`. 😂
>
> ```rust
> #[allow(clippy::useless_attribute)]
> #[allow(clippy::redundant_pub_crate)]
> pub(crate) use bit;
> ```
>
> The originally-reported warning now no longer occurs.
`needless_late_init`: ignore `if let`, `let mut` and significant drops
No longer lints `if let`, personal taste on this one is pretty split, so it probably shouldn't be warning by default. Fixes#8613
```rust
let x = if let Some(n) = y {
n
} else {
1
}
```
No longer lints `let mut`, things like the following are not uncommon and look fine as they are
b169c16d86/src/sixty_four.rs (L88-L93)
Avoids changing the drop order in an observable way, where the type of `x` has a drop with side effects and something between `x` and the first use also does, e.g.
48cc6cb791/tests/test_api.rs (L159-L167)
The implementation of `type_needs_ordered_drop_inner` was changed a bit, it now uses `Ty::has_significant_drop` and reordered the ifs to check diagnostic name before checking the implicit drop impl
changelog: [`needless_late_init`]: No longer lints `if let` statements, `let mut` bindings and no longer significantly changes drop order
mistyped_literal_suffix: improve integer suggestions, avoid wrong float suggestions
This PR fixes 2 things:
- The known problem that integer types are always suggested as signed, by suggesting an unsigned suffix for literals that wouldnt fit in the signed type, and ignores any literals too big for the corresponding unsigned type too.
- The lint would only look at the integer part of any floating point literals without an exponent, this causing #6129. This just ignores those literals.
Examples:
```rust
let _ = 2_32; // still 2_i32
let _ = 234_8; // would now suggest 234_u8
// these are now ignored
let _ = 500_8;
let _ = 123_32.123;
```
changelog: suggest correct integer types in [`mistyped_literal_suffix`], ignore float literals without an exponent
fixes#6129
Previously this lint would only look at the integer part of floating
point literals without an exponent, giving wrong suggestions like:
```
|
8 | let _ = 123_32.123;
| ^^^^^^^^^^ help: did you mean to write: `123.123_f32`
|
```
Instead, it now ignores these literals.
Fixes#6129
Instead of just always suggesting signed suffixes regardless of size
of the value, it now suggests an unsigned suffix when the value wouldn't
fit into the corresponding signed type, and ignores the literal entirely
if it is too big for the unsigned type as well.
wrong_self_convention allows `is_*` to take `&mut self`
fix#8480 and #8513
Allowing `is_*` to take `&self` or none is too restrictive.
changelog: FPs: [`wrong_self_convention`] now allows `&mut self` and no self as arguments for `is_*` methods
`manual_split_once`: lint manual iteration of `SplitN`
changelog: `manual_split_once`: lint manual iteration of `SplitN`
Now lints:
```rust
let mut iter = "a.b.c".splitn(2, '.');
let first = iter.next().unwrap();
let second = iter.next().unwrap();
let mut iter = "a.b.c".splitn(2, '.');
let first = iter.next()?;
let second = iter.next()?;
let mut iter = "a.b.c".rsplitn(2, '.');
let first = iter.next().unwrap();
let second = iter.next().unwrap();
let mut iter = "a.b.c".rsplitn(2, '.');
let first = iter.next()?;
let second = iter.next()?;
```
It suggests (minus leftover whitespace):
```rust
let (first, second) = "a.b.c".split_once('.').unwrap();
let (first, second) = "a.b.c".split_once('.')?;
let (second, first) = "a.b.c".rsplit_once('.').unwrap();
let (second, first) = "a.b.c".rsplit_once('.')?;
```
Currently only lints if the statements are next to each other, as detecting the various kinds of shadowing was tricky, so the following won't lint
```rust
let mut iter = "a.b.c".splitn(2, '.');
let something_else = 1;
let first = iter.next()?;
let second = iter.next()?;
```
Less authoritative stable_sort_primitive message
fixes#8241
Hey all - first contribution here so I'm deciding to start with something small.
Updated the linked message to be less authoritative as well as moved the lint grouping from `perf` to `pedantic` as suggested by `@camsteffen` under the issue.
changelog: [`stable_sort_primitive`]: emit less authoritative message and move to `pedantic`
Fix needless_match false positive for if-let when the else block doesn't match to given expr
<!--
Thank you for making Clippy better!
We're collecting our changelog from pull request descriptions.
If your PR only includes internal changes, you can just write
`changelog: none`. Otherwise, please write a short comment
explaining your change. Also, it's helpful for us that
the lint name is put into brackets `[]` and backticks `` ` ` ``,
e.g. ``[`lint_name`]``.
If your PR fixes an issue, you can add "fixes #issue_number" into this
PR description. This way the issue will be automatically closed when
your PR is merged.
If you added a new lint, here's a checklist for things that will be
checked during review or continuous integration.
- \[ ] Followed [lint naming conventions][lint_naming]
- \[ ] Added passing UI tests (including committed `.stderr` file)
- \[x] `cargo test` passes locally
- \[x] Executed `cargo dev update_lints`
- \[ ] Added lint documentation
- \[x] Run `cargo dev fmt`
[lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints
Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.
Delete this line and everything above before opening your PR.
--->
fix#8695
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: Fixed ``[`needless_match`]`` false positive when else block expression differs.
Take over: New lint bytes count to len
take over #8375close#8083
This PR adds new lint about considering replacing `.bytes().count()` with `.len()`.
Thank you in advance.
---
r! `@Manishearth`
changelog: adds new lint [`bytes_count_to_len`] to consider replacing `.bytes().count()` with `.len()`
adding test patterns
cargo dev bless
fix comment
add ;
delete :
fix suggestion code
and update stderr in tests.
use match_def_path when checking method name
Add `await_holding_invalid_type` lint
changelog: [`await_holding_invalid_type`]
This lint allows users to create a denylist of types which are not allowed to be
held across await points. This is essentially a re-implementation of the
language-level [`must_not_suspend`
lint](https://github.com/rust-lang/rust/issues/83310). That lint has a lot of
work still to be done before it will reach Rust stable, and in the meantime
there are a lot of types which can trip up developers if they are used
improperly.
I originally implemented this specifically for `tracing::span::Entered`, until I discovered #8434 and read the commentary on that PR. Given this implementation is fully user configurable, doesn't tie clippy to any one particular crate, and introduces no additional dependencies, it seems more appropriate.
Report undeclared lifetimes during late resolution.
First step in https://github.com/rust-lang/rust/pull/91557
We reuse the rib design of the current resolution framework. Specific `LifetimeRib` and `LifetimeRibKind` types are introduced. The most important variant is `LifetimeRibKind::Generics`, which happens each time we encounter something which may introduce generic lifetime parameters. It can be an item or a `for<...>` binder. The `LifetimeBinderKind` specifies how this rib behaves with respect to in-band lifetimes.
r? `@petrochenkov`
Refactor HIR item-like traversal (part 1)
Issue #95004
- Create hir_crate_items query which traverses tcx.hir_crate(()).owners to return a hir::ModuleItems
- use tcx.hir_crate_items in tcx.hir().items() to return an iterator of hir::ItemId
- use tcx.hir_crate_items to introduce a tcx.hir().par_items(impl Fn(hir::ItemId)) to traverse all items in parallel;
Signed-off-by: Miguel Guarniz <mi9uel9@gmail.com>
cc `@cjgillot`
changelog: [`await_holding_invalid_type`]
This lint allows users to create a denylist of types which are not allowed to be
held across await points. This is essentially a re-implementation of the
language-level [`must_not_suspend`
lint](https://github.com/rust-lang/rust/issues/83310). That lint has a lot of
work still to be done before it will reach Rust stable, and in the meantime
there are a lot of types which can trip up developers if they are used
improperly.
New lint `format_add_strings`
Closes#6261
changelog: Added [`format_add_string`]: recommend using `write!` instead of appending the result of `format!`
Add `usize` cast to `clippy::manual_bits` suggestion
A fix for the suggestion from https://github.com/rust-lang/rust-clippy/pull/8213
changelog: [`manual_bits`]: The suggestion now includes a cast for proper type conversion
This adds test to make sure correct behavior of lint
- The first test's option variable is not a temporary variable
- The second test does not make usage of `take()`
- The third test makes usage of `take()` and uses a temporary variable
This lint checks if Option::take() is used on a temporary value (a value
that is not of type &mut Option and that is not a Place expression) to
suggest omitting take()
Check for loops/closures in `local_used_after_expr`
Follow up to #8646, catches when a local is used multiple times because it's in a loop or a closure
changelog: none