fix(manual_find_map and manual_filter_map): check clone method
close#8920
Added conditional branching when the clone method is used.
Thank you in advance.
---
changelog: check `clone()` and other variant preserving methods in [`manual_find_map`] and [`manual_filter_map`]
When setting suggestion for significant_drop_in_scrutinee, add suggestion for MoveAndClone for non-ref
When trying to set the current suggestion, if the type of the expression
is not a reference and it is not trivially pure clone copy, we should still
trigger and emit a lint message. Since this fix may require cloning an
expensive-to-clone type, do not attempt to offer a suggested fix.
This change means that matches generated from TryDesugar and AwaitDesugar
would normally trigger a lint, but they are out of scope for this lint,
so we will explicitly ignore matches with sources of TryDesugar or
AwaitDesugar.
changelog: Update for ``[`significant_drop_in_scrutinee`]`` to correctly
emit lint messages for cases where the type is not a reference *and*
not trivially pure clone copy.
changelog: [`significant_drop_in_scrutinee`]: No longer lint on Try `?`
and `await` desugared expressions.
remove `large_enum_variant` suggestion for `Copy` types
Replaces the (erroneous) suggestion on `large_enum_variant` for `Copy` types by a note. This fixes#8894.
---
changelog: none
Set correct `ParamEnv` for `derive_partial_eq_without_eq`
fixes#8867
changelog: Handle differing predicates applied by `#[derive(PartialEq)]` and `#[derive(Eq)]` in `derive_partial_eq_without_eq`
new lint: `borrow_deref_ref`
changelog: ``[`borrow_deref_ref`]``
Related pr: #6837#7577
`@Jarcho` Could you please give a review?
`cargo lintcheck` gives no false negative (but tested crates are out-of-date).
TODO:
1. Not sure the name. `deref_on_immutable_ref` or some others?
Fix `manual_range_contains` false negative with chains of `&&` and `||`
Fixes#8745
Since the precedence for `&&` is the same as itself the HIR for a chain of `&&` ends up with a right skewed tree like:
```
&&
/ \
&& c2
/ \
... c1
```
So only the leftmost `&&` was actually "fully" checked, the top level was just `c2` and `&&` so the `manual_range_contains` lint won't apply. This change makes it also check `c2` with `c1`.
There's a bit of a hacky solution in the [second commit](257f09776a) to check if the number of open/closing parens in the snippet match. This is to prevent a case like `((x % 2 == 0) || (x < 0)) || (x >= 10)` from offering a suggestion like `((x % 2 == 0) || !(0..10).contains(&x)` which now won't compile.
Any suggestions for that paren hack welcome, kinda new to working on this so not too sure about possible solutions :) it's weird because I don't know how else to check for parens in HIR considering they're removed when lowering AST.
changelog: Fix [`manual_range_contains`] false negative with chains of `&&` and `||`
Don't lint `useless_transmute` on types with erased regions
fixes#6356fixes#3340fixes#2906
This should get a proper fix at some point, but this at least gets the lint running on some types.
cc #5343
changelog: Don't lint `useless_transmute` on types with erased regions
`cast_abs_to_unsigned`: do not remove cast if it's required
Fixes#8873
If `iX` is not cast to `uX` then keep the cast rather than removing it
changelog: [`cast_abs_to_unsigned`]: do not remove cast if it's required
needless_late_init: fix ICE when all branches return the never type
Fixes#8911
When the assignment is done in a match guard or the if condition and all of the branches return the never type `assignment_suggestions` would return an empty `Vec` which caused the ICE. It now returns `None` in that scenario
Also moves some tests to the top of the file
changelog: ICE Fixes: [`needless_late_init`] #8911
Fix `[use_self]` false negative with on struct and tuple struct patterns
fixes#8845
changelog: Triggered the warning for ``[`use_self`]`` on `TupleStruct` and `Struct` patterns, whereas currently it's only triggered for `Path` patterns
add doc_link_with_quotes lint
I'm not sure about wording, it seems OK to me but happy to change if other people have better ideas
closes#8383
---
changelog: add [`doc_link_with_quotes`] lint
Check `.fixed` paths' existence in `run_ui`
This PR adds a test to check that there exists a `.fixed` file for every `.stderr` file in `tests/ui` that mentions a `MachineApplicable` lint. The test leverages `compiletest-rs`'s `rustfix_coverage` option.
I tried to add `.fixed` files where they appeared to be missing. However, 38 exceptional `.rs` files remain. Several of those include comments indicating that they are exceptions, though not all do. Apologies, as I have not tried to associate the 38 files with GH issues. (I think that would be a lot of work, and I worry about linking the wrong issue.)
changelog: none
Fix `empty_line_after_outer_attribute` false positive
This PR fixes a false positive in `empty_line_after_outer_attribute`.
Here is a minimal example that trigger the FP:
```rust
#[derive(clap::Parser)]
#[clap(after_help = "This ia a help message.
You're welcome.
")]
pub struct Args;
```
changelog: PF: [`empty_line_after_outer_attribute`]: No longer lints empty lines in inner string values.
Introduce `allow-dbg-in-tests` config value
related to: Issue #8758, PR https://github.com/rust-lang/rust-clippy/pull/8838
changelog: Introduced `allow-dbg-in-tests` config value. [dbg_macro] does not allow `dbg!` in test code by default.
When trying to set the current suggestion, if the type of the expression
is not a reference and it is not trivially pure clone copy, we should still
trigger and emit a lint message. Since this fix may require cloning an
expensive-to-clone type, do not attempt to offer a suggested fix.
This change means that matches generated from TryDesugar and AwaitDesugar
would normally trigger a lint, but they are out of scope for this lint,
so we will explicitly ignore matches with sources of TryDesugar or
AwaitDesugar.
changelog: Update for [`significant_drop_in_scrutinee`] to correctly
emit lint messages for cases where the type is not a reference and
not trivially pure clone copy.
`get_last_with_len`: lint `VecDeque` and any deref to slice
changelog: [`get_last_with_len`]: lint `VecDeque` and any deref to slice
Previously only `Vec`s were linted, this will now catch any usages on slices, arrays, etc. It also suggests `.back()` for `VecDeque`s
Also moves the lint into `methods/`
Add some testcases for recent rustfix update
changelog: none
This adds a testcase for a bugfix that has been fixed by https://github.com/rust-lang/rustfix/tree/v0.6.1
`rustfix` is pulled in by `compiletest_rs`. So to test that the correct rustfix version is used, I added one (and a half) testcase.
I tried to add a testcase for #8734 as well, but interesting enough the rustfix is wrong:
```diff
fn issue8734() {
let _ = [0u8, 1, 2, 3]
.into_iter()
- .and_then(|n| match n {
+ .flat_map(|n| match n {
+ 1 => [n
+ .saturating_add(1)
1 => [n
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)
.saturating_add(1)],
n => [n],
});
}
```
this needs some investigation and then this testcase needs to be enabled by commenting it out
closes#8878
related to #8734
`identity_op`: add parenthesis to suggestions where required
changelog: [`identity_op`]: add parenthesis to suggestions where required
Follow up to #8730, wraps the cases we can't lint as-is in parenthesis rather than ignoring them
Catches a couple new FPs with mixed operator precedences and `as` casts
```rust
// such as
0 + { a } * 2;
0 + a as usize;
```
The suggestions are now applied using `span_lint_and_sugg` rather than appearing in just the message and have a `run-rustfix` test
Rustup
`@rust-lang/clippy,` `@Jarcho,` `@dswij,` `@Alexendoo.` Could someone review this? It should be pretty straight forward since it's just a sync. I think it's also fine if either one of `@Jarcho,` `@dswij,` `@Alexendoo` approves this, as these are usually not reviewed. I just want to make sure that I didn't break something obvious 🙃
It should be enough to look at the merge commit 🙃
changelog: none
changelog: move [`significant_drop_in_scrutinee`] to `suspicious`
[dbg_macro] tolerates use of `dbg!` in items which have `#[cfg(test)]` attribute
fix: #8758
changelog: [dbg_macro] tolerates use of `dbg!` in items with `#[cfg(test)]` attribute
Improve "unknown field" error messages
Fixes#8806
Sample output:
```
error: error reading Clippy's configuration file `/home/smoelius/github/smoelius/rust-clippy/clippy.toml`: unknown field `foobar`, expected one of
allow-expect-in-tests enable-raw-pointer-heuristic-for-send standard-macro-braces
allow-unwrap-in-tests enforced-import-renames third-party
allowed-scripts enum-variant-name-threshold too-large-for-stack
array-size-threshold enum-variant-size-threshold too-many-arguments-threshold
avoid-breaking-exported-api literal-representation-threshold too-many-lines-threshold
await-holding-invalid-types max-fn-params-bools trivial-copy-size-limit
blacklisted-names max-include-file-size type-complexity-threshold
cargo-ignore-publish max-struct-bools unreadable-literal-lint-fractions
cognitive-complexity-threshold max-suggested-slice-pattern-length upper-case-acronyms-aggressive
cyclomatic-complexity-threshold max-trait-bounds vec-box-size-threshold
disallowed-methods msrv verbose-bit-mask-threshold
disallowed-types pass-by-value-size-limit warn-on-all-wildcard-imports
doc-valid-idents single-char-binding-names-threshold
at line 1 column 1
```
You can test this by (say) adding `foobar = 42` to Clippy's root `clippy.toml` file, and running `cargo run --bin cargo-clippy`.
Note that, to get the terminal width, this PR adds `termize` as a dependency to `cargo-clippy`. However, `termize` is also [how `rustc_errors` gets the terminal width](481db40311/compiler/rustc_errors/src/emitter.rs (L1607)). So, hopefully, this is not a dealbreaker.
r? `@xFrednet`
changelog: Enhancements: the "unknown field" error messages for config files now wraps the field names.
add suggestions to rc_clone_in_vec_init
A followup to https://github.com/rust-lang/rust-clippy/pull/8769
I also switch the order of the 2 suggestions, since the loop initialization one is probably the common case.
`@xFrednet` I'm not letting you guys rest for a minute 😅
changelog: add suggestions to [`rc_clone_in_vec_init`]
`undocumented_unsafe_blocks` does not trigger on unsafe trait impls
Closes#8505
changelog: This lint checks unsafe impls NOT from macro expansions and checks ones in macro declarations.
~~`unsafe impl`s from macro invocations don't trigger the lint for now.~~
~~This lint checks unsafe impls from/not from macro expansions~~
Don't lint `vec_init_then_push` when further extended
fixes#7071
This will still lint when a larger number of pushes are done (four currently). The exact number could be debated, but this is more readable then a sequence of pushes so it shouldn't be too large.
changelog: Don't lint `vec_init_then_push` when further extended.
changelog: Remove `mut` binding from `vec_init_then_push` when possible.
Fix redundant_allocation warning for Rc<Box<str>>
changelog: [`redundant_allocation`] Fixes#8604
Fixes false positives where a fat pointer with `str` type was made thin by another allocation, but that thinning allocation was marked as redundant
This PR has implemented improved representation.
- Use "lib" instead of "lifb"
- Use "triggered" instead of "triggere"
- Use "blacklisted_name" instead of "blackisted_name"
- Use "stabilization" instead of "stabilisation"
- Use "behavior" instead of "behaviour"
- Use "target" instead of "tartet"
- Use "checked_add" instead of "chcked_add"
- Use "anti-pattern" instead of "antipattern"
- Use "suggestion" instead of "suggesttion"
- Use "example" instead of "exampel"
- Use "Cheat Sheet" instead of "Cheatsheet"
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
fix unnecessary_to_owned about msrv
This PR fixes ``[`unnecessary_owned`]``.
## What
```rust
# sample code
fn _msrv_1_35() {
#![clippy::msrv = "1.35"]
let _ = &["x"][..].to_vec().into_iter();
}
fn _msrv_1_36() {
#![clippy::msrv = "1.36"]
let _ = &["x"][..].to_vec().into_iter();
}
```
If we will check this code using clippy, ``[`unnecessary_owned`]`` will modify the code as follows.
```rust
error: unnecessary use of `to_vec`
--> $DIR/unnecessary_to_owned.rs:219:14
|
LL | let _ = &["x"][..].to_vec().into_iter();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `["x"][..].iter().copied()`
error: unnecessary use of `to_vec`
--> $DIR/unnecessary_to_owned.rs:224:14
|
LL | let _ = &["x"][..].to_vec().into_iter();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `["x"][..].iter().copied()`
```
This is incorrect. Because `Iterator::copied` was estabilished in 1.36.
## Why
This bug was caused by not separating "copied" and "clone" by reference to msrv.
89ee6aa6e3/clippy_lints/src/methods/unnecessary_to_owned.rs (L195)
So, I added a conditional branch and described the corresponding test.
Thank you in advance.
changelog: fix wrong suggestions about msrv in [`unnecessary_to_owned`]
r! `@giraffate`
Don't lint `manual_non_exhaustive` when the enum variant is used
fixes#5714
changelog: Don't lint `manual_non_exhaustive` when the enum variant is used
Do not trigger ``[`rest_pat_in_fully_bound_structs`]`` on `#[non_exhaustive]` structs
fixes#8029
Just adds an additional check to ensure that the`ty::VariantDef` is not marked as `#[non_exhaustive]`.
changelog: Do not apply ``[`rest_pat_in_fully_bound_structs`]`` on structs marked as non exhaustive.
adding condition for map_clone message
This PR fixes the message about `map_clone`.
if msrv >= 1.36, the message is correct.
```bash
$ cat main.rs
fn main() {
let x: Vec<&i32> = vec![&1, &2];
let y: Vec<_> = x.iter().map(|i| *i).collect();
println!("{:?}", y);
}
$ cargo clippy
warning: you are using an explicit closure for copying elements
--> main.rs:3:20
|
3 | let y: Vec<_> = x.iter().map(|i| *i).collect();
| ^^^^^^^^^^^^^^^^^^^^ help: consider calling the dedicated `copied` method: `x.iter().copied()`
|
= note: `#[warn(clippy::map_clone)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#map_clone
warning: `test` (build script) generated 1 warning
warning: `test` (bin "test") generated 1 warning (1 duplicate)
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
```
but, if msrv < 1.36, the suggestion is `cloned`, but the message is `copying`.
```bash
$ cat clippy.toml
msrv = "1.35"
$ cargo clippy
warning: you are using an explicit closure for copying elements
--> main.rs:3:20
|
3 | let y: Vec<_> = x.iter().map(|i| *i).collect();
| ^^^^^^^^^^^^^^^^^^^^ help: consider calling the dedicated `cloned` method: `x.iter().cloned()`
```
I think the separation of messages will make it more user-friendly.
thank you in advance.
changelog: Fixed a message in map_clone.
New lint `is_digit_ascii_radix`
Closes#6399
changelog: Added [`is_digit_ascii_radix`]: recommend `is_ascii_digit()` or `is_ascii_hexdigit()` in place of `is_digit(10)` and `is_digit(16)`
Fix subtraction overflow in `cast_possible_truncation`
changelog: Fix false negative due to subtraction overflow in `cast_possible_truncation`
I *think* a false negative is the worst that can happen from this
Don't lint various match lints when expanded by a proc-macro
fixes#4952
As always for proc-macro output this is a hack-job of a fix. It would be really nice if more proc-macro authors would set spans correctly.
changelog: Don't lint various lints on proc-macro output.
Fix `same_functions_in_if_condition` FP
fixes#8139
changelog: Don't consider `Foo<{ SomeConstant }>` and `Foo<{ SomeOtherConstant }>` to be the same, even if the constants have the same value.
Remove overlap between `manual_split_once` and `needless_splitn`
changelog: Remove overlap between [`manual_split_once`] and [`needless_splitn`]. Fixes some incorrect `rsplitn` suggestions for [`manual_split_once`]
Things that can trigger `needless_splitn` no longer trigger `manual_split_once`, e.g.
```rust
s.[r]splitn(2, '=').next();
s.[r]splitn(2, '=').nth(0);
s.[r]splitn(3, '=').next_tuple();
```
Fixes some suggestions:
```rust
let s = "should not match";
s.rsplitn(2, '.').nth(1);
// old -> Some("should not match")
Some(s.rsplit_once('.').map_or(s, |x| x.0));
// new -> None
s.rsplit_once('.').map(|x| x.0);
s.rsplitn(2, '.').nth(1)?;
// old -> "should not match"
s.rsplit_once('.').map_or(s, |x| x.0);
// new -> early returns
s.rsplit_once('.')?.0;
```
- 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
- add par_items(impl Fn(hir::ItemId)) to traverse all items in parallel
Signed-off-by: Miguel Guarniz <mi9uel9@gmail.com>
ignore `&x | &y` in unnested_or_patterns
replacing it with `&(x | y)` is actually more characters
Fixes#6973
changelog: [`unnested_or_patterns`] ignore `&x | &y`, nesting would result in more characters
Add a lint to detect cast to unsigned for abs() and suggest unsigned_…
…abs()
changelog: Add a [`cast_abs_to_unsigned`] that checks for uses of `abs()` that are cast to the corresponding unsigned integer type and suggest to replace them with `unsigned_abs()`.
Fix `as_deref_mut` false positives in `needless_option_as_deref`
Also moves it into `methods/`
Fixes#7846Fixes#8047
changelog: [`needless_option_as_deref`]: No longer lints for `as_deref_mut` on Options that cannot be moved
supersedes #8064
fix FP in lint `[needless_match]`
fixes: #8542fixes: #8551fixes: #8595fixes: #8599
---
changelog: check for more complex custom type, and ignore type coercion in [`needless_match`]
Suggest from_utf8_unchecked in const contexts
Unfortunately I couldn't figure out how to check whether a given expression is in an `unsafe` context or not, so I just unconditionally emit the wrapping `unsafe {}` block in the suggestion. If there is an easy way to get it to work better then I would love to hear it.
changelog: Suggest `from_utf8_unchecked` instead of `from_utf8` in const contexts for ``[`transmute_bytes_to_str`]``
refs: #8379
Fix unnecessary_cast suggestion for type aliasses
Fix#6923. The [`unnecessary_cast`] lint now will skip casting to non-primitive type.
changelog: fix lint [`unnecessary_cast `]
`indexing_slicing` should not fire if a valid array index comes from a constant function that is evaluated at compile-time
fix#8348
changelog: [`indexing_slicing`] fewer false positives in `const` contexts and with `const` indices
fix misspelling in diagnostic message of `bytes_nth`
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: fix misspelling in diagnostic message in ``[`bytes_nth`]``
Run fmt test before compile-test/dogfood
I seem to always forget to run `cargo dev fmt` before doing a test. This lets it fail fast rather than going through the much longer compile-test/dogfood tests first
changelog: none
Rework `undocumented_unsafe_blocks`
fixes: #8264fixes: #8449
One thing came up while working on this. Currently comments on the same line are supported like so:
```rust
/* SAFETY: reason */ unsafe {}
```
Is this worth supporting at all? Anything other than a couple of words doesn't really fit well.
edit: [zulip topic](https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/.60undocumented_unsafe_blocks.60.20same.20line.20comment)
changelog: Don't lint `undocumented_unsafe_blocks` when the unsafe block comes from a proc-macro.
changelog: Don't lint `undocumented_unsafe_blocks` when the preceding line has a safety comment and the unsafe block is a sub-expression.
add `empty_structs_with_brackets`
<!-- 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)
- \[ ] `cargo test` passes locally
- \[ ] Executed `cargo dev update_lints`
- \[ ] Added lint documentation
- \[ ] 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.
--
*Please write a short comment explaining your change (or "none" for internal only changes)*
-->
Closes#8591
I'm already sorry for the massive diff 😅
changelog: New lint [`empty_structs_with_brackets`]
Remove deps
This remove both `regex` and `cargo_metadata` as dependencies making `clippy_dev` compile ~3x faster (~46s -> ~16s locally). `cargo_metadata` was used to extract the `version` field from `Cargo.toml`, which is done trivially without that. `regex` was used to parse `define_clippy_lint` in `update_lints` which is now done using `rustc_lexer`. This isn't any simpler, but it compiles ~15s faster and runs ~3x faster (~2.1s -> ~0.7s locally).
The next biggest offenders to compile times are `clap` and `winapi` on windows. `clap` could be removed, but re-implementing enough is probably more work than it's worth. `winapi` is used by `opener` and `walkdir` so it's stuck there.
changelog: none
Handle relative paths in module_files lints
The problem being that when clippy is run in the project's directory `lp` would be a relative path, this wasn't caught by the tests as there `lp` is an absolute path. Being a relative path it did not start with `trim_src_path` and so was ignored
Also allowed the removal of some `.to_os_string`/`.to_owned`s
changelog: Fixes [`self_named_module_files`] and [`mod_module_files`] not linting
Fixes#8123, cc `@DevinR528`
single_element_loop: handle arrays for Edition2021
changelog: [`single_element_loop`] handle arrays in Edition 2021, handle `.iter_mut()` and `.into_iter()`, and wrap in parens if necessary
Add `crate_in_macro_def` lint
This PR adds a lint to check for `crate` as opposed to `$crate` used in a macro definition.
I think this can close#4798. That issue focused on the case where the macro author "imports something into said macro."
But I think use of `crate` is likely to be a bug whether it appears in a `use` statement or not. There could be some use case I am failing to see, though. (cc: `@nilscript` `@flip1995)`
changelog: `crate_in_macro_def`
new lint: `only_used_in_recursion`
changed:
- added `only_used_in_recursion`.
- fixed code that variables are only used in recursion.
- this would not lint when `unused_variable`
This fixes: #8390
-----
changelog: add lint [`only_used_in_recursion`]
Llint for casting between raw slice pointers with different element sizes
This lint disallows using `as` to convert from a raw pointer to a slice (e.g. `*const [i32]`, `*mut [Foo]`) to any other raw pointer to a slice if the element types have different sizes. When a raw slice pointer is cast, the data pointer and count metadata are preserved. This means that when the size of the inner slice's element type changes, the total number of bytes pointed to by the count changes. For example a `*const [i32]` with length 4 (four `i32` elements) is cast `as *const [u8]` the resulting pointer points to four `u8` elements at the same address, losing most of the data. When the size *increases* the resulting pointer will point to *more* data, and accessing that data will be UB.
On its own, *producing* the pointer isn't actually a problem, but because any use of the pointer as a slice will either produce surprising behavior or cause UB I believe this is a correctness lint. If the pointer is not intended to be used as a slice, the user should instead use any of a number of methods to produce just a data pointer including an `as` cast to a thin pointer (e.g. `p as *const i32`) or if the pointer is being created from a slice, the `as_ptr` method on slices. Detecting the intended use of the pointer is outside the scope of this lint, but I believe this lint will also lead users to realize that a slice pointer is only for slices.
There is an exception to this lint when either of the slice element types are zero sized (e.g `*mut [()]`). The total number of bytes pointed to by the slice with a zero sized element is zero. In that case preserving the length metadata is likely intended as a workaround to get the length metadata of a slice pointer though a zero sized slice.
The lint does not forbid casting pointers to slices with the *same* element size as the cast was likely intended to reinterpret the data in the slice as some equivalently sized data and the resulting pointer will behave as intended.
---
changelog: Added ``[`cast_slice_different_sizes`]``, a lint that disallows using `as`-casts to convert between raw pointers to slices when the elements have different sizes.