check std::panic::panic_any in panic lint
close#13292
This PR detects `std::panic::panic_any` in panic lint.
changelog: check std::panic::panic_any in panic lint
Rewrite `empty_line_after_doc_comments` and `empty_line_after_outer_attr`, move them from `nursery` to `suspicious`
changelog: [`empty_line_after_doc_comments`], [`empty_line_after_outer_attr`]: rewrite and move them from `nursery` to `suspicious`
They now lint when there's a comment between the last attr/doc comment and the empty line, to cover the case:
```rust
/// Docs for `old_code
// fn old_code() {}
fn new_code() {}
```
When these lints or `suspicious_doc_comments` trigger we no longer trigger any other doc lint as a broad fix for #12917, reverts some of #13002 as the empty line lints cover it
I ended up not doing https://github.com/rust-lang/rust-clippy/issues/12917#issuecomment-2161828859 as I don't think it's needed
Remove `find_format_arg_expr` AST fallback
If the function fails where it shouldn't we can fix that directly, but the fallback path is untested as I'm not aware of a case where it would fail
changelog: none
Shrink `TyKind::FnPtr`.
By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and `FnHeader`, which can be packed more efficiently. This reduces the size of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms. This reduces peak memory usage by a few percent on some benchmarks. It also reduces cache misses and page faults similarly, though this doesn't translate to clear cycles or wall-time improvements on CI.
r? `@compiler-errors`
Replace `rustc_semver` with `rustc_session::RustcVersion`
Allows dropping a dependency but there is a behaviour change here, the following versions are no longer accepted:
* `1` (would need to be `1.0` or `1.0.0`)
* `1.0.0-alpha`
* `1.0.0-alpha.2`
* `1.0.0-beta`
But this seems unlikely to effect anybody, I did some GitHub searching and found no occurrences outside our UI tests
r? `@flip1995`
changelog: none
Miscellaneous improvements to struct tail normalization
1. Make checks for foreign tails more accurate by normalizing the struct tail. I didn't write a test for this one.
2. Normalize when computing struct tail for `offset_of` for slice/str. This fixes the new solver only.
3. Normalizing when computing tails for disaligned reference check. This fixes both solvers.
r? lcnr
By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and
`FnHeader`, which can be packed more efficiently. This reduces the size
of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms.
This reduces peak memory usage by a few percent on some benchmarks. It
also reduces cache misses and page faults similarly, though this doesn't
translate to clear cycles or wall-time improvements on CI.
Don't use `LateContext` in the constant evaluator
This also changes the interface to require explicitly creating the context. `constant` could be added back in, but the others are probably not worth it.
A couple of bugs have been fixed. The wrong `TypeckResults` was used once when evaluating a constant, and the wrong `ParamEnv` was used by some callers (there wasn't a way to use the correct one).
changelog: none
Fix while_let_on_iterator dropping loop label when applying fix.
Loop label was not persisted when displaying help and was therefore producing broken rust code when applying fixes.
Solution was to store the `ast::Label` when creating a `higher::WhileLet` from an expression and add the label name to the lint suggestion and diagnostics.
---
Fixes: https://github.com/rust-lang/rust-clippy/issues/13123
changelog: [`while_let_on_iterator`]: Fix issue dropping loop label when displaying help and applying fixes.
Remove unnecessary `res` field in `for_each_expr` visitors
Small refactor in the `for_each_expr*` visitors. This should not change anything functionally.
Instead of storing the final value `Option<B>` in the visitor and setting it to `Some` when we get a `ControlFlow::Break(B)` from the closure, we can just directly return it from the visitor itself now that visitors support that.
cc #12829 and https://github.com/rust-lang/rust-clippy/pull/12830#discussion_r1627882827
changelog: none
* Construct lint passes by taking `Conf` by reference.
* Use `HashSet` configs in less places
* Move some `check_crate` code into the pass constructor when possible.
This is a very large commit since a lot needs to be changed in order to
make the tests pass. The salient changes are:
- `ConstArgKind` gets a new `Path` variant, and all const params are now
represented using it. Non-param paths still use `ConstArgKind::Anon`
to prevent this change from getting too large, but they will soon use
the `Path` variant too.
- `ConstArg` gets a distinct `hir_id` field and its own variant in
`hir::Node`. This affected many parts of the compiler that expected
the parent of an `AnonConst` to be the containing context (e.g., an
array repeat expression). They have been changed to check the
"grandparent" where necessary.
- Some `ast::AnonConst`s now have their `DefId`s created in
rustc_ast_lowering rather than `DefCollector`. This is because in some
cases they will end up becoming a `ConstArgKind::Path` instead, which
has no `DefId`. We have to solve this in a hacky way where we guess
whether the `AnonConst` could end up as a path const since we can't
know for sure until after name resolution (`N` could refer to a free
const or a nullary struct). If it has no chance as being a const
param, then we create a `DefId` in `DefCollector` -- otherwise we
decide during ast_lowering. This will have to be updated once all path
consts use `ConstArgKind::Path`.
- We explicitly use `ConstArgHasType` for array lengths, rather than
implicitly relying on anon const type feeding -- this is due to the
addition of `ConstArgKind::Path`.
- Some tests have their outputs changed, but the changes are for the
most part minor (including removing duplicate or almost-duplicate
errors). One test now ICEs, but it is for an incomplete, unstable
feature and is now tracked at #127009.
Rollup of 10 pull requests
Successful merges:
- #126841 ([`macro_metavar_expr_concat`] Add support for literals)
- #126881 (Make `NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE` a deny-by-default lint in edition 2024)
- #126921 (Give VaList its own home)
- #127367 (Run alloc sync tests)
- #127431 (Use field ident spans directly instead of the full field span in diagnostics on local fields)
- #127437 (Uplift trait ref is knowable into `rustc_next_trait_solver`)
- #127439 (Uplift elaboration into `rustc_type_ir`)
- #127451 (Improve `run-make/output-type-permutations` code and improve `filename_not_in_denylist` API)
- #127452 (Fix intrinsic const parameter counting with `effects`)
- #127459 (rustdoc-json: add type/trait alias tests)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove `is_in_test_module_or_function`
Uses are replaced with `is_in_test` for consistency with other lints and to simplify the implementation of the lints. This means the module name is no longer checked, but that was a horrible hack from a time when late passes couldn't see `#[cfg(..)]` attributes.
changelog: none
[`unnecessary_to_owned`]: catch `to_owned` on byte slice to create temporary `&str`
Closes#11648
Detects the pattern `&String::from_utf8(bytes.to_vec()).unwrap()` and suggests `core::str::from_utf8(bytes).unwrap()`, which avoids the unnecessary intermediate allocation.
I decided to put this in the existing `unnecessary_to_owned` lint (rather than creating a new lint) for a few reasons:
- we get to use some of its logic (for example, recognizing any of the functions in the `to_owned` family, e.g. `to_vec`)
- the actual inefficient operation that can be avoided here is the call to `.to_vec()`, so this is in a way similar to the other cases caught by `unnecessary_to_owned`, just through a bunch of type conversions
- we can make this more "generic" later and catch other cases, so imo it's best not to tie this lint specifically to the `String` type
changelog: [`unnecessary_to_owned`]: catch `&String::from_utf8(bytes.to_vec()).unwrap()` and suggest `core::str::from_utf8(bytes).unwrap()`
Fix some false-positive cases of `explicit_auto_deref`
changelog: [`explicit_auto_deref`] Fix some false-positive cases
Fix part of #9841
Fix #12969
r? xFrednet
Don't lint `assertions_on_constants` on any const assertions
close#12816close#12847
cc #12817
----
changelog: Fix false positives in consts for `assertions_on_constants` and `unnecessary_operation`.
Tighten `fn_decl_span` for async blocks
Tightens the span of `async {}` blocks in diagnostics, and subsequently async closures and async fns, by actually setting the `fn_decl_span` correctly. This is kinda a follow-up on #125078, but it fixes the problem in a more general way.
I think the diagnostics are significantly improved, since we no longer have a bunch of overlapping spans. I'll point out one caveat where I think the diagnostic may get a bit more confusing, but where I don't think it matters.
r? ````@estebank```` or ````@oli-obk```` or someone else on wg-diag or compiler i dont really care lol
resolve `clippy::invalid_paths` on `bool::then`
*Please write a short comment explaining your change (or "none" for internal only changes)*
changelog: none
This removes the ICE codepaths for `f16` and `f128` in Clippy.
`rustc_apfloat` is used as a dependency for the parsing of these types,
since their `FromStr` implementation will not be available in the
standard library for a while.
Add more types to `is_from_proc_macro`
I've been running through going through all the lint implementations to clean them up. I'll be separating out the changes into small PRs to make reviewing easier.
changelog: none
* Delay the parsing of the use node
* Mark when the `SyntaxContext` changes rather than return `None`
* Return a default value if the HIR tree is broken rather than `None`
Avoid emitting `assigning_clones` when cloned data borrows from the place to clone into
Fixes#12444Fixes#12460Fixes#12749Fixes#12757Fixes#12929
I think the documentation for the function should describe what- and how this is fixing the issues well.
It avoids emitting a warning when the data being cloned borrows from the place to clone into, which is information that we can get from `PossibleBorrowerMap`. Unfortunately, it is a tiny bit tedious to match on the MIR like that and I'm not sure if this is possibly relying a bit too much on the exact MIR lowering for assignments.
Things left to do:
- [x] Handle place projections (or verify that they work as expected)
- [x] Handle non-`Drop` types
changelog: [`assigning_clones`]: avoid warning when the suggestion would lead to a borrow-check error
Let `qualify_min_const_fn` deal with drop terminators
Fixes#12677
The `method_accepts_droppable` check that was there seemed overly conservative.
> Returns true if any of the method parameters is a type that implements `Drop`.
> The method can't be made const then, because `drop` can't be const-evaluated.
Accepting parameters that implement `Drop` should still be fine as long as the parameter isn't actually dropped, as is the case in the linked issue where the droppable is moved into the return place. This more accurate analysis ("is there a `drop` terminator") is already done by `qualify_min_const_fn` [here](f5e250180c/clippy_utils/src/qualify_min_const_fn.rs (L298)), so I don't think this additional check is really necessary?
Fixing the other, second case in the linked issue was only slightly more involved, since `Vec::new()` is a function call that has the ability to panic, so there must be a `drop()` terminator for cleanup, however we should be able to freely ignore that. [Const checking ignores cleanup blocks](https://github.com/rust-lang/rust/blob/master/compiler/rustc_const_eval/src/transform/check_consts/check.rs#L382-L388), so we should, too?
r? `@Jarcho`
----
changelog: [`missing_const_for_fn`]: continue linting on fns with parameters implementing `Drop` if they're not actually dropped
Make `for_each_expr` visit closures by default, rename the old version `for_each_expr_without_closures`
A lot of the time `for_each_expr` is picked when closures should be visited so I think it makes sense for this to be the default with the alternative available for when you don't need to visit them.
The first commit renames `for_each_expr` to `for_each_expr_without_closures` and `for_each_expr_with_closures` to `for_each_expr`
The second commit switches a few uses that I caught over to include closures to fix a few bugs
changelog: none
Handle const effects inherited from parent correctly in `type_certainty`
This fixes a (debug) ICE in `type_certainty` that happened in the [k256 crate]. (I'm sure you can also specifically construct an edge test case that will run into type_certainty false positives visible outside of debug builds from this bug)
<details>
<summary>Minimal ICE repro</summary>
```rs
use std::ops::Add;
Add::add(1_i32, 1).add(i32::MIN);
```
</details>
The subtraction here overflowed:
436675b477/clippy_utils/src/ty/type_certainty/mod.rs (L209)
... when we have something like `Add::add` where `add` fn has 0 generic params but the `host_effect_index` is `Some(2)` (inherited from the parent generics, the const trait `Add`), and we end up executing `0 - 1`.
(Even if the own generics weren't empty and we didn't overflow, this would still be wrong because it would assume that a trait method with 1 generic parameter didn't have any generics).
So, *only* exclude the "host" generic parameter if it's actually bound by the own generics
changelog: none
[k256 crate]: https://github.com/RustCrypto/elliptic-curves/tree/master/k256
Rename HIR `TypeBinding` to `AssocItemConstraint` and related cleanup
Rename `hir::TypeBinding` and `ast::AssocConstraint` to `AssocItemConstraint` and update all items and locals using the old terminology.
Motivation: The terminology *type binding* is extremely outdated. "Type bindings" not only include constraints on associated *types* but also on associated *constants* (feature `associated_const_equality`) and on RPITITs of associated *functions* (feature `return_type_notation`). Hence the word *item* in the new name. Furthermore, the word *binding* commonly refers to a mapping from a binder/identifier to a "value" for some definition of "value". Its use in "type binding" made sense when equality constraints (e.g., `AssocTy = Ty`) were the only kind of associated item constraint. Nowadays however, we also have *associated type bounds* (e.g., `AssocTy: Bound`) for which the term *binding* doesn't make sense.
---
Old terminology (HIR, rustdoc):
```
`TypeBinding`: (associated) type binding
├── `Constraint`: associated type bound
└── `Equality`: (associated) equality constraint (?)
├── `Ty`: (associated) type binding
└── `Const`: associated const equality (constraint)
```
Old terminology (AST, abbrev.):
```
`AssocConstraint`
├── `Bound`
└── `Equality`
├── `Ty`
└── `Const`
```
New terminology (AST, HIR, rustdoc):
```
`AssocItemConstraint`: associated item constraint
├── `Bound`: associated type bound
└── `Equality`: associated item equality constraint OR associated item binding (for short)
├── `Ty`: associated type equality constraint OR associated type binding (for short)
└── `Const`: associated const equality constraint OR associated const binding (for short)
```
r? compiler-errors
[perf] Delay the construction of early lint diag structs
Attacks some of the perf regressions from https://github.com/rust-lang/rust/pull/124417#issuecomment-2123700666.
See individual commits for details. The first three commits are not strictly necessary.
However, the 2nd one (06bc4fc671, *Remove `LintDiagnostic::msg`*) makes the main change way nicer to implement.
It's also pretty sweet on its own if I may say so myself.
* instead simply set the primary message inside the lint decorator functions
* it used to be this way before [#]101986 which introduced `msg` to prevent
good path delayed bugs (which no longer exist) from firing under certain
circumstances when lints were suppressed / silenced
* this is no longer necessary for various reasons I presume
* it shaves off complexity and makes further changes easier to implement
Rename Unsafe to Safety
Alternative to #124455, which is to just have one Safety enum to use everywhere, this opens the posibility of adding `ast::Safety::Safe` that's useful for unsafe extern blocks.
This leaves us today with:
```rust
enum ast::Safety {
Unsafe(Span),
Default,
// Safe (going to be added for unsafe extern blocks)
}
enum hir::Safety {
Unsafe,
Safe,
}
```
We would convert from `ast::Safety::Default` into the right Safety level according the context.
make sure the msrv for `const_raw_ptr_deref` is met when linting [`missing_const_for_fn`]
fixes: #8864
---
changelog: make sure the msrv for `const_ptr_deref` is met when linting [`missing_const_for_fn`]