(Big performance change) Do not run lints that cannot emit
Before this change, adding a lint was a difficult matter because it always had some overhead involved. This was because all lints would run, no matter their default level, or if the user had `#![allow]`ed them. This PR changes that. This change would improve both the Rust lint infrastructure and Clippy, but Clippy will see the most benefit, as it has about 900 registered lints (and growing!)
So yeah, with this little patch we filter all lints pre-linting, and remove any lint that is either:
- Manually `#![allow]`ed in the whole crate,
- Allowed in the command line, or
- Not manually enabled with `#[warn]` or similar, and its default level is `Allow`
As some lints **need** to run, this PR also adds **loadbearing lints**. On a lint declaration, you can use the ``@eval_always` = true` marker to label it as loadbearing. A loadbearing lint will never be filtered (it will always run)
Fixes#106983
Use `Enabled{Lang,Lib}Feature` instead of n-tuples
Instead of passing around e.g. `(gate_name, attr_span, stable_since)` 3-tuples for enabled lang features or `(gate_name, attr_span)` 2-tuples for enabled lib features, use `Enabled{Lang,Lib}Feature` structs with named fields.
Also did some minor code-golfing of involved iterator chains to hopefully make them easier to follow.
Follow-up to https://github.com/rust-lang/rust/pull/132098#issuecomment-2434523431 cc `@RalfJung.`
Pass Ident by reference in ast Visitor
`MutVisitor`'s version of `visit_ident` passes around `&Ident`, but `Visitor` copies `Ident`. This PR changes that
r? `@petrochenkov`
related to #128974
Remove visit_expr_post from ast Visitor
`visit_expr_post` is only present in the immutable version of ast Visitors and its default implementation is a noop.
Given that its only implementer is on `rustc_lint/src/early.rs` and its name follows the same naming convention as some other lints (`_post`), it seems that `visit_expr_post` being in `Visitor` was a little mistake.
r? `@petrochenkov`
related to #128974
Stabilize shorter-tail-lifetimes
Close#131445
Tracked by #123739
We found a test case `tests/ui/drop/drop_order.rs` that had not been covered by the change. The test fixture is fixed now with the correct expectation.
Represent trait constness as a distinct predicate
cc `@rust-lang/project-const-traits`
r? `@ghost` for now
Also mirrored everything that is written below on this hackmd here: https://hackmd.io/`@compiler-errors/r12zoixg1l`
# Tl;dr:
* This PR removes the bulk of the old effect desugaring.
* This PR reimplements most of the effect desugaring as a new predicate and set of a couple queries. I believe it majorly simplifies the implementation and allows us to move forward more easily on its implementation.
I'm putting this up both as a request for comments and a vibe-check, but also as a legitimate implementation that I'd like to see land (though no rush of course on that last part).
## Background
### Early days
Once upon a time, we represented trait constness in the param-env and in `TraitPredicate`. This was very difficult to implement correctly; it had bugs and was also incomplete; I don't think this was anyone's fault though, it was just the limit of experimental knowledge we had at that point.
Dealing with `~const` within predicates themselves meant dealing with constness all throughout the trait solver. This was difficult to keep track of, and afaict was not handled well with all the corners of candidate assembly.
Specifically, we had to (in various places) remap constness according to the param-env constness:
574b64a97f/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1498)
This was annoying and manual and also error prone.
### Beginning of the effects desugaring
Later on, #113210 reimplemented a new desugaring for const traits via a `<const HOST: bool>` predicate. This essentially "reified" the const checking and separated it from any of the remapping or separate tracking in param-envs. For example, if I was in a const-if-const environment, but I wanted to call a trait that was non-const, this reification would turn the constness mismatch into a simple *type* mismatch of the effect parameter.
While this was a monumental step towards straightening out const trait checking in the trait system, it had its own issues, since that meant that the constness of a trait (or any item within it, like an associated type) was *early-bound*. This essentially meant that `<T as Trait>::Assoc` was *distinct* from `<T as ~const Trait>::Assoc`, which was bad.
### Associated-type bound based effects desugaring
After this, #120639 implemented a new effects desugaring. This used an associated type to more clearly represent the fact that the constness is not an input parameter of a trait, but a property that could be computed of a impl. The write-up linked in that PR explains it better than I could.
However, I feel like it really reached the limits of what can comfortably be expressed in terms of associated type and trait calculus. Also, `<const HOST: bool>` remains a synthetic const parameter, which is observable in nested items like RPITs and closures, and comes with tons of its own hacks in the astconv and middle layer.
For example, there are pieces of unintuitive code that are needed to represent semantics like elaboration, and eventually will be needed to make error reporting intuitive, and hopefully in the future assist us in implementing built-in traits (eventually we'll want something like `~const Fn` trait bounds!).
elaboration hack: 8069f8d17a/compiler/rustc_type_ir/src/elaborate.rs (L133-L195)
trait bound remapping hack for diagnostics: 8069f8d17a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs (L2370-L2413)
I want to be clear that I don't think this is a issue of implementation quality or anything like that; I think it's simply a very clear sign that we're using types and traits in a way that they're not fundamentally supposed to be used, especially given that constness deserves to be represented as a first-class concept.
### What now?
This PR implements a new desugaring for const traits. Specifically, it introduces a `HostEffect` predicate to represent the obligation an impl is const, rather than using associated type bounds and the compat trait that exists for effects today.
### `HostEffect` predicate
A `HostEffect` clause has two parts -- the `TraitRef` we're trying to prove, and a `HostPolarity::{Maybe, Const}`.
`HostPolarity::Const` corresponds to `T: const Trait` bounds, which must *always* be proven as const, and which can be written in any context. These are lowered directly into the predicates of an item, since they're not "context-specific".
On the other hand, `HostPolarity::Maybe` corresponds to `T: ~const Trait` bounds which must only exist in a conditionally-const context like a method in a `#[const_trait]`, or a `const fn` free function. We do not lower these immediately into the predicates of an item; instead, we collect them into a new query called the **`const_conditions`**. These are the set of trait refs that we need to prove have const implementations for an item to be const.
Notably, they're represented as bare (poly) trait refs because they are meant to be paired back together with a `HostPolarity` when they're being registered in typeck (see next section).
For example, given:
```rust
const fn foo<T: ~const A + const B>() {}
```
`foo`'s const conditions would contain `T: A`, but not `T: B`. On the flip side, foo's predicates (`predicates_of`) query would contain `HostEffect(T: B, HostPolarity::Const)` but not `HostEffect(T: A, HostPolarity::Maybe)` since we don't need to prove that predicate in a non-const environment (and it's not even the right predicate to prove in an unconditionally const environment).
### Type checking const bodies
When type checking bodies in HIR, when we encounter a call expression, we additionally register the callee item's const conditions with the `HostPolarity` from the body we're typechecking (`Const` for unconditionally const things like `const`/`static` items, and `Maybe` for conditionally const things like const fns; and we don't register `HostPolarity` predicates for non-const bodies).
When type-checking a conditionally const body, we augment its param-env with `HostEffect(..., Maybe)` predicates.
### Checking that const impls are WF
We extend the logic in `compare_method_predicate_entailment` to also check the const-conditions of the impl method, to make sure that we error for:
```rust
#[const_trait] Bar {}
#[const_trait] trait Foo {
fn method<T: Bar>();
}
impl Foo for () {
fn method<T: ~const Bar>() {} // stronger assumption!
}
```
We also extend the WF check for impls to register the const conditions of the trait that is being implemented. This is to make sure we error for:
```rust
#[const_trait] trait Bar {}
#[const_trait] trait Foo<T> where T: ~const Bar {}
impl<T> const Foo<T> for () {}
//~^ `T: ~const Bar` is missing!
```
### Proving a `HostEffect` predicate
We have several ways of proving a `HostEffect` predicate:
1. Matching a `HostEffect` predicate from the param-env
2. From an impl - we do impl selection very similar to confirming a trait goal, except we filter for only const impls, and we additionally register the impl's const conditions (i.e. the impl's `~const` where clauses).
Later I expect that we will add more built-in implementations for things like `Fn`.
## What next?
After this PR, I'd like to split out the work more so it can proceed in parallel and probably amongst others that are not me.
* Register `HostEffect` goal for places in HIR typeck that correspond to call terminators, like autoderef.
* Make traits in libstd const again.
* Probably need to impl host effect preds in old solver.
* Implement built-in `HostEffect` rules for traits like `Fn`.
* Rip out const checking from MIR altogether.
## So what?
This ends up being super convenient basically everywhere in the compiler. Due to the design of the new trait solver, we end up having an almost parallel structure to the existing trait and projection predicates for assembling `HostEffect` predicates; adding new candidates and especially new built-in implementations is now basically trivial, and it's quite straightforward to understand the confirmation logic for these predicates.
Same with diagnostics reporting; since we have predicates which represent the obligation to prove an impl is const, we can simplify and make these diagnostics richer without having to write a ton of logic to intercept and rewrite the existing `Compat` trait errors.
Finally, it gives us a much more straightforward path for supporting the const effect on the old trait solver. I'm personally quite passionate about getting const trait support into the hands of users without having to wait until the new solver lands[^1], so I think after this PR lands we can begin to gauge how difficult it would be to implement constness in the old trait solver too. This PR will not do this yet.
[^1]: Though this is not a prerequisite or by any means the only justification for this PR.
Taking a raw ref (`&raw (const|mut)`) of a deref of pointer (`*ptr`) is always safe
T-opsem decided in https://github.com/rust-lang/reference/pull/1387 that `*ptr` is only unsafe if the place is accessed. This means that taking a raw ref of a deref expr is always safe, since it doesn't constitute a read.
This also relaxes the `DEREF_NULLPTR` lint to stop warning in the case of raw ref of a deref'd nullptr, and updates its docs to reflect that change in the UB specification.
This does not change the behavior of `addr_of!((*ptr).field)`, since field projections still require the projection is in-bounds.
I'm on the fence whether this requires an FCP, since it's something that is guaranteed by the reference you could ostensibly call this a bugfix since we were counting truly safe operations as unsafe. Perhaps someone on opsem has a strong opinion? cc `@rust-lang/opsem`
terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it)
Mostly, we currently call a feature that has a corresponding `#[feature(name)]` attribute in the current crate a "declared" feature. I think that is confusing as it does not align with what "declaring" usually means. Furthermore, we *also* refer to `#[stable]`/`#[unstable]` as *declaring* a feature (e.g. in [these diagnostics](f25e5abea2/compiler/rustc_passes/messages.ftl (L297-L301))), which aligns better with what "declaring" usually means. To make things worse, the functions `tcx.features().active(...)` and `tcx.features().declared(...)` both exist and they are doing almost the same thing (testing whether a corresponding `#[feature(name)]` exists) except that `active` would ICE if the feature is not an unstable lang feature. On top of this, the callback when a feature is activated/declared is called `set_enabled`, and many comments also talk about "enabling" a feature.
So really, our terminology is just a mess.
I would suggest we use "declaring a feature" for saying that something is/was guarded by a feature (e.g. `#[stable]`/`#[unstable]`), and "enabling a feature" for `#[feature(name)]`. This PR implements that.
make unsupported_calling_conventions a hard error
This has been a future-compat lint (not shown in dependencies) since Rust 1.55, released 3 years ago. Hopefully that was enough time so this can be made a hard error now. Given that long timeframe, I think it's justified to skip the "show in dependencies" stage. There were [not many crates hitting this](https://github.com/rust-lang/rust/pull/86231#issuecomment-866300943) even when the lint was originally added.
This should get cratered, and I assume then it needs a t-compiler FCP. (t-compiler because this looks entirely like an implementation oversight -- for the vast majority of ABIs, we already have a hard error, but some were initially missed, and we are finally fixing that.)
Fixes https://github.com/rust-lang/rust/pull/87678
Finish stabilization of `result_ffi_guarantees`
The internal linting has been changed, so all that is left is making sure we stabilize what we want to stabilize.
Continue to get rid of `ty::Const::{try_}eval*`
This PR mostly does:
* Removes all of the `try_eval_*` and `eval_*` helpers from `ty::Const`, and replace their usages with `try_to_*`.
* Remove `ty::Const::eval`.
* Rename `ty::Const::normalize` to `ty::Const::normalize_internal`. This function is still used in the normalization code itself.
* Fix some weirdness around the `TransmuteFrom` goal.
I'm happy to split it out further; for example, I could probably land the first part which removes the helpers, or the changes to codegen which are more obvious than the changes to tools.
r? BoxyUwU
Part of https://github.com/rust-lang/rust/issues/130704
Allow `#[deny]` inside `#[forbid]` as a no-op
Forbid cannot be overriden. When someome tries to do this anyways, it results in a hard error. That makes sense.
Except it doesn't, because macros. Macros may reasonably use `#[deny]` (or `#[warn]` for an allow-by-default lint) in their expansion to assert that their expanded code follows the lint. This is doesn't work when the output gets expanded into a `forbid()` context. This is pretty silly, since both the macros and the code agree on the lint!
By making it a warning instead, we remove the problem with the macro, which is now nothing as warnings are suppressed in macro expanded code, while still telling users that something is up.
fixes#121483
warn less about non-exhaustive in ffi
Bindgen allows generating `#[non_exhaustive] #[repr(u32)]` enums. This results in nonintuitive nonlocal `improper_ctypes` warnings, even when the types are otherwise perfectly valid in C.
Adjust for actual tooling expectations by avoiding warning on simple enums with only unit variants.
Closes https://github.com/rust-lang/rust/issues/116831
Before this change, adding a lint was a difficult matter
because it always had some overhead involved. This was
because all lints would run, no matter their default level,
or if the user had #![allow]ed them. This PR changes that
Forbid cannot be overriden. When someome tries to do this anyways,
it results in a hard error. That makes sense.
Except it doesn't, because macros. Macros may reasonably use `#[deny]`
in their expansion to assert
that their expanded code follows the lint. This is doesn't work when the
output gets expanded into a `forbid()` context. This is pretty silly,
since both the macros and the code agree on the lint!
Therefore, we allow `#[deny(..)]`ing a lint that's already forbidden,
keeping the level at forbid.
Move polarity into `PolyTraitRef` rather than storing it on the side
Arguably we could move these modifiers into `TraitRef` instead of `PolyTraitRef`, but I see `TraitRef` as simply the *path* part of the trait ref. It doesn't really matter -- refactoring this further is much easier now.
Remove deprecation note in the `non_local_definitions` lint
This PR removes the edition deprecation note emitted by the `non_local_definitions` lint.
Specifically this part:
```
= note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue <https://github.com/rust-lang/rust/issues/120363>
```
because it [didn't make the cut](https://github.com/rust-lang/rust/issues/120363#issuecomment-2407833300) for the 2024 edition.
`@rustbot` label +L-non_local_definitions
Make unused_parens's suggestion considering expr's attributes.
For the expr with attributes,
like `let _ = (#[inline] || println!("Hello!"));`,
the suggestion's span should contains the attributes, or the suggestion will remove them.
fixes#129833
For the expr with attributes, like `let _ = (#[inline] || println!("Hello!"));`, the suggestion's span should contains the attributes, or the suggestion will remove them.
fixes#129833
Consider outermost const-anon in `non_local_def` lint
This PR change the logic for finding the parent of the `impl` definition in the `non_local_definitions` lint to consider multiple level of const-anon items, instead of only one currently.
I also took the opportunity to cleanup the related code.
cc ``@traviscross``
Fixes https://github.com/rust-lang/rust/issues/131474