Remap impl-trait lifetimes on HIR instead of AST lowering
Current AST->HIR lowering goes out of its way to remap lifetimes for opaque types. This is complicated and leaks into upstream and downstream code.
This PR stops trying to be clever during lowering, and prefers to do this remapping during the HIR->ty lowering. The remapping computation easily fits into the bound var resolution code. Its result can be used in by `generics_of` and `hir_ty_lowering::new_opaque` to add the proper parameters and arguments.
See an example on the doc for query `opaque_captured_lifetimes`.
Based on https://github.com/rust-lang/rust/pull/129244/
Fixes https://github.com/rust-lang/rust/issues/125249
Fixes https://github.com/rust-lang/rust/issues/126850
cc `@compiler-errors` `@spastorino`
r? `@petrochenkov`
The RFC for arbitrary self types v2 declares that we should reject
"generic" self types. This commit does so.
The definition of "generic" was unclear in the RFC, but has been
explored in
https://github.com/rust-lang/rust/issues/129147
and the conclusion is that "generic" means any `self` type which
is a type parameter defined on the method itself, or references
to such a type.
This approach was chosen because other definitions of "generic"
don't work. Specifically,
* we can't filter out generic type _arguments_, because that would
filter out Rc<Self> and all the other types of smart pointer
we want to support;
* we can't filter out all type params, because Self itself is a
type param, and because existing Rust code depends on other
type params declared on the type (as opposed to the method).
This PR decides to make a new error code for this case, instead of
reusing the existing E0307 error. This makes the code a
bit more complex, but it seems we have an opportunity to provide
specific diagnostics for this case so we should do so.
This PR filters out generic self types whether or not the
'arbitrary self types' feature is enabled. However, it's believed
that it can't have any effect on code which uses stable Rust, since
there are no stable traits which can be used to indicate a valid
generic receiver type, and thus it would have been impossible to
write code which could trigger this new error case.
It is however possible that this could break existing code which
uses either of the unstable `arbitrary_self_types` or
`receiver_trait` features. This breakage is intentional; as
we move arbitrary self types towards stabilization we don't want
to continue to support generic such types.
This PR adds lots of extra tests to arbitrary-self-from-method-substs.
Most of these are ways to trigger a "type mismatch" error which
9b82580c73/compiler/rustc_hir_typeck/src/method/confirm.rs (L519)
hopes can be minimized by filtering out generics in this way.
We remove a FIXME from confirm.rs suggesting that we make this change.
It's still possible to cause type mismatch errors, and a subsequent
PR may be able to improve diagnostics in this area, but it's harder
to cause these errors without contrived uses of the turbofish.
This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? @wesleywiser
TypingMode: merge intercrate, reveal, and defining_opaque_types
This adds `TypingMode` and uses it in most places. We do not yet remove `Reveal` from `param_env`s. This and other future work as tracked in #132279 and via `FIXME`s.
Fetching the `TypingMode` of the `InferCtxt` asserts that the `TypingMode` agrees with `ParamEnv::reveal` to make sure we don't introduce any subtle bugs here. This will be unnecessary once `ParamEnv::reveal` no longer exists.
As the `TypingMode` is now a part of the query input, I've merged the coherence and non-coherence caches for the new solver. I've also enabled the local `infcx` cache during coherence by clearing the cache when forking it with a different `TypingMode`.
#### `TypingMode::from_param_env`
I am using this even in cases where I know that the `param_env` will always be `Reveal::UserFacing`. This is to make it easier to correctly refactor this code in the future, any time we use `Reveal::UserFacing` in a body while not defining its opaque types is incorrect and should use a `TypingMode` which only reveals opaques defined by that body instead, cc #124598
r? ``@compiler-errors``
Collect item bounds for RPITITs from trait where clauses just like associated types
We collect item bounds from trait where clauses for *associated types*, i.e. this:
```rust
trait Foo
where
Self::Assoc: Send
{
type Assoc;
}
```
Becomes this:
```rust
trait Foo {
type Assoc: Send;
}
```
Today, with RPITITs/AFIT and return-type notation, we don't do that, i.e.:
```rust
trait Foo where Self::method(..): Send {
fn method() -> impl Sized;
}
fn is_send(_: impl Send) {}
fn test<T: Foo>() {
is_send(T::method());
}
```
...which fails on nightly today.
Turns out it's super easy to fix this, and we just need to use the `associated_type_bounds` lowering function in `explicit_item_bounds_with_filter`, which has that logic baked in.
Hack out effects support for old solver
Opening this for vibes ✨
Turns out that a basic, somewhat incomplete implementation of host effects is achievable in the old trait solver pretty easily. This should be sufficient for us to use in the standard library itself.
Regarding incompleteness, maybe we should always treat host predicates as ambiguous in intercrate mode (at least in the old solver) to avoid any worries about accidental impl overlap or something.
r? ```@lcnr``` cc ```@fee1-dead```
Add `LayoutS::is_uninhabited` and use it
Use accessors for the things that accessors are good at: reducing everyone's need to be nosy and peek at the internals of every data structure.
compiler: Add rustc_abi dependence to the compiler
Depend on rustc_abi in compiler crates that use it indirectly but have not yet taken on that dependency, and are not *significantly* entangled in my other PRs. This leaves an "excise rustc_target" step after the dust settles.
Remove `ObligationCause::span()` method
I think it's an incredibly confusing footgun to expose both `obligation_cause.span` and `obligation_cause.span()`. Especially because `ObligationCause::span()` (the method) seems to just be hacking around a single quirk in the way we set up obligation causes for match arms.
First commit removes the need for that hack, with only one diagnostic span changing (but IMO not really getting worse -- I'd argue that it was already confusing).
Depend on rustc_abi in compiler crates that use it indirectly but have
not yet taken on that dependency, and are not entangled in my other PRs.
This leaves an "excise rustc_target" step after the dust settles.
Cleanup: Move an impl-Trait check from AST validation to AST lowering
Namely the one that rejects `impl Trait` in qself types and non-final path segments.
There's no good reason to perform this during AST validation.
We have better infrastructure in place in the AST lowerer (`ImplTraitContext`).
This shaves off a lot of code.
We now lower `impl Trait` in bad positions to `{type error}` which allows us to
remove a special case from HIR ty lowering.
Coincidentally fixes#126725. Well, it only *masks* it by passing `{type error}` to HIR analysis instead of a "bad" opaque. I was able to find a new reproducer for it. See the issue.
Simplify param handling in `resolve_bound_vars`
I always found the flow of the `ResolvedArg` constructors to be a bit confusing; turns out they're also kinda redundantly passing around their data, too.
Also, deduplicate some code handling early-bound var to late-bound var conversion between return type notation's two styles: `where <T as Trait>::method(..): Bound` and `where T: Trait<method(..): Bound>`.
Effects cleanup
- removed extra bits from predicates queries that are no longer needed in the new system
- removed the need for `non_erasable_generics` to take in tcx and DefId, removed unused arguments in callers
r? compiler-errors
- removed extra bits from predicates queries that are no longer needed in the new system
- removed the need for `non_erasable_generics` to take in tcx and DefId, removed unused arguments in callers
Then we can rename the _raw functions to drop their suffix, and instead
explicitly use is_stable_const_fn for the few cases where that is really what
you want.
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.
Deeply normalize `TypeTrace` when reporting type error in new solver
Normalize the values that come from the `TypeTrace` for various type mismatches.
Side-note: We can't normalize the `TypeError` itself bc it may come from instantiated binders, so it may reference values from within the probe...
r? lcnr
Rename Receiver -> LegacyReceiver
As part of the "arbitrary self types v2" project, we are going to replace the current `Receiver` trait with a new mechanism based on a new, different `Receiver` trait.
This PR renames the old trait to get it out the way. Naming is hard. Options considered included:
* HardCodedReceiver (because it should only be used for things in the standard library, and hence is sort-of hard coded)
* LegacyReceiver
* TargetLessReceiver
* OldReceiver
These are all bad names, but fortunately this will be temporary. Assuming the new mechanism proceeds to stabilization as intended, the legacy trait will be removed altogether.
Although we expect this trait to be used only in the standard library, we suspect it may be in use elsehwere, so we're landing this change separately to identify any surprising breakages.
It's known that this trait is used within the Rust for Linux project; a patch is in progress to remove their dependency.
This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? `@wesleywiser`
Minor tweaks to `compare_impl_item.rs`
1. Stop using the `InstantiatedPredicates` struct for `hybrid_preds` in `compare_impl_item.rs`, since we never actually push anything into the `spans` part of it.
2. Remove redundant impl args and don't do useless identity substitution, prefer calling `instantiate_identity`.
Validate args are correct for `UnevaluatedConst`, `ExistentialTraitRef`/`ExistentialProjection`
For the `Existential*` ones, we have to do some adjustment to the args list to deal with the missing `Self` type, so we introduce a `debug_assert_existential_args_compatible` function to the interner as well.
As part of the "arbitrary self types v2" project, we are going to
replace the current `Receiver` trait with a new mechanism based on a
new, different `Receiver` trait.
This PR renames the old trait to get it out the way. Naming is hard.
Options considered included:
* HardCodedReceiver (because it should only be used for things in the
standard library, and hence is sort-of hard coded)
* LegacyReceiver
* TargetLessReceiver
* OldReceiver
These are all bad names, but fortunately this will be temporary.
Assuming the new mechanism proceeds to stabilization as intended, the
legacy trait will be removed altogether.
Although we expect this trait to be used only in the standard library,
we suspect it may be in use elsehwere, so we're landing this change
separately to identify any surprising breakages.
It's known that this trait is used within the Rust for Linux project; a
patch is in progress to remove their dependency.
This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? @wesleywiser
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
Rollup of 4 pull requests
Successful merges:
- #126588 (Added more scenarios where comma to be removed in the function arg)
- #131728 (bootstrap: extract builder cargo to its own module)
- #131968 (Rip out old effects var handling code from traits)
- #131981 (Remove the `BoundConstness::NotConst` variant)
r? `@ghost`
`@rustbot` modify labels: rollup
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
Get rid of `OnlySelfBounds`
We turn `PredicateFilter` into a newtyped bool called `OnlySelfBounds`. There's no reason to lose the information of the `PredicateFilter`, so let's just pass it all the way through.
Don't report bivariance error when nesting a struct with field errors into another struct
We currently have logic to avoid reporting lifetime bivariance ("lifetime parameter ... is never used") errors when a struct has field resolution errors. However, this doesn't apply transitively. This PR implements a simple visitor to do so.
This was reported [here](https://twitter.com/fasterthanlime/status/1846257921086165033) since a `derive(Deserialize, Serialize)` ends up generating helper structs which have bivariant lifetimes due to containing the offending struct (that's being derived on).
Use `ThinVec` for PredicateObligation storage
~~I noticed while profiling clippy on a project that a large amount of time is being spent allocating `Vec`s for `PredicateObligation`, and the `Vec`s are often quite small. This is an attempt to optimise this by using SmallVec to avoid heap allocations for these common small Vecs.~~
This PR turns all the `Vec<PredicateObligation>` into a single type alias while avoiding referring to `Vec` around it, then swaps the type over to `ThinVec<PredicateObligation>` and fixes the fallout. This also contains an implementation of `ThinVec::extract_if`, copied from `Vec::extract_if` and currently being upstreamed to https://github.com/Gankra/thin-vec/pull/66.
This leads to a small (0.2-0.7%) performance gain in the latest perf run.
Rollup of 9 pull requests
Successful merges:
- #122670 (Fix bug where `option_env!` would return `None` when env var is present but not valid Unicode)
- #131095 (Use environment variables instead of command line arguments for merged doctests)
- #131339 (Expand set_ptr_value / with_metadata_of docs)
- #131652 (Move polarity into `PolyTraitRef` rather than storing it on the side)
- #131675 (Update lint message for ABI not supported)
- #131681 (Fix up-to-date checking for run-make tests)
- #131702 (Suppress import errors for traits that couldve applied for method lookup error)
- #131703 (Resolved python deprecation warning in publish_toolstate.py)
- #131710 (Remove `'apostrophes'` from `rustc_parse_format`)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove unnecessary sorts in `rustc_hir_analysis`
A follow-up after #131140. Here the related objects are `IndexSet` so do not require a sort to stay stable. And they don't need to be `mut` anymore.
r? ```@compiler-errors```
Update lint message for ABI not supported
Tracking issue: #130260
As requested in https://github.com/rust-lang/rust/pull/128784#pullrequestreview-2364026550 I updated the error message.
I could also change it to be the same message as if it was a hard error on a normal function:
> "`{abi}` is not a supported ABI for the current target"
Or would that get confusing when people try to google the error message?
r? compiler-errors
Check ABI target compatibility for function pointers
Tracking issue: https://github.com/rust-lang/rust/issues/130260
Related tracking issue: #87678
Compatibility of an ABI for a target was previously only performed on function definitions and `extern` blocks. This PR adds it also to function pointers to be consistent.
This might have broken some of the `tests/ui/` depending on the platform, so a try run seems like a good idea.
Also this might break existing code, because we now emit extra errors. Does this require a crater run?
# Example
```rust
// build with: --target=x86_64-unknown-linux-gnu
// These raise E0570
extern "thiscall" fn foo() {}
extern "thiscall" { fn bar() }
// This did not raise any error
fn baz(f: extern "thiscall" fn()) { f() }
```
# Open Questions
* [x] Should this report a future incompatibility warning like #87678 ?
* [ ] Is this the best place to perform the check?
Add intrinsics `fmuladd{f16,f32,f64,f128}`. This computes `(a * b) +
c`, to be fused if the code generator determines that (i) the target
instruction set has support for a fused operation, and (ii) that the
fused operation is more efficient than the equivalent, separate pair
of `mul` and `add` instructions.
https://llvm.org/docs/LangRef.html#llvm-fmuladd-intrinsic
MIRI support is included for f32 and f64.
The codegen_cranelift uses the `fma` function from libc, which is a
correct implementation, but without the desired performance semantic. I
think this requires an update to cranelift to expose a suitable
instruction in its IR.
I have not tested with codegen_gcc, but it should behave the same
way (using `fma` from libc).
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#117942Fixes#121161Fixes#121263Fixes#121299Fixes#121722Fixes#121799Fixes#126969Fixes#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
Compiler & its UI tests: Rename remaining occurrences of "object safe" to "dyn compatible"
Follow-up to #130826.
Part of #130852.
1. 1st commit: Fix stupid oversights. Should've been part of #130826.
2. 2nd commit: Rename the unstable feature `object_safe_for_dispatch` to `dyn_compatible_for_dispatch`. Might not be worth the churn, you decide.
3. 3rd commit: Apply the renaming to all UI tests (contents and paths).
Make opaque types regular HIR nodes
Having opaque types as HIR owner introduces all sorts of complications. This PR proposes to make them regular HIR nodes instead.
I haven't gone through all the test changes yet, so there may be a few surprises.
Many thanks to `@camelid` for the first draft.
Fixes https://github.com/rust-lang/rust/issues/129023Fixes#129099Fixes#125843Fixes#119716Fixes#121422
Account for `impl Trait {` when `impl Trait for Type {` was intended
On editions where bare traits are never allowed, detect if the user has written `impl Trait` with no type, silence any dyn-compatibility errors, and provide a structured suggestion for the potentially missing type:
```
error[E0782]: trait objects must include the `dyn` keyword
--> $DIR/missing-for-type-in-impl.rs:8:6
|
LL | impl Foo<i64> {
| ^^^^^^^^
|
help: add `dyn` keyword before this trait
|
LL | impl dyn Foo<i64> {
| +++
help: you might have intended to implement this trait for a given type
|
LL | impl Foo<i64> for /* Type */ {
| ++++++++++++++
```
CC #131051.
Check elaborated projections from dyn don't mention unconstrained late bound lifetimes
Check that the projections that are *not* explicitly written but which we deduce from elaborating the principal of a `dyn` *also* do not reference unconstrained late-bound lifetimes, just like the ones that the user writes by hand.
That is to say, given:
```
trait Foo<T>: Bar<Assoc = T> {}
trait Bar {
type Assoc;
}
```
The type `dyn for<'a> Foo<&'a T>` (basically) elaborates to `dyn for<'a> Foo<&'a T> + for<'a> Bar<Assoc = &'a T>`[^1]. However, the `Bar` projection predicate is not well-formed, since `'a` must show up in the trait's arguments to be referenced in the term of a projection. We must error in this situation[^well], or else `dyn for<'a> Foo<&'a T>` is unsound.
We already detect this for user-written projections during HIR->rustc_middle conversion, so this largely replicates that logic using the helper functions that were already conveniently defined.
---
I'm cratering this first to see the fallout; if it's minimal or zero, then let's land it as-is. If not, the way that this is implemented is very conducive to an FCW.
---
Fixes#130347
[^1]: We don't actually elaborate it like that in rustc; we only keep the principal trait ref `Foo<&'a T>` and the projection part of `Bar<Assoc = ...>`, but it's useful to be a bit verbose here for the purpose of explaining the issue.
[^well]: Well, we could also make `dyn for<'a> Foo<&'a T>` *not* implement `for<'a> Bar<Assoc = &'a T>`, but this is inconsistent with the case where the user writes `Assoc = ...` in the type itself, and it overly complicates the implementation of trait objects' built-in impls.
On editions where bare traits are never allowed, detect if the user has
written `impl Trait` with no type, silence any dyn-compatibility errors,
and provide a structured suggestion for the potentially missing type:
```
error[E0782]: trait objects must include the `dyn` keyword
--> $DIR/missing-for-type-in-impl.rs:8:6
|
LL | impl Foo<i64> {
| ^^^^^^^^
|
help: add `dyn` keyword before this trait
|
LL | impl dyn Foo<i64> {
| +++
help: you might have intended to implement this trait for a given type
|
LL | impl Foo<i64> for /* Type */ {
| ++++++++++++++
```
Stabilize the `map`/`value` methods on `ControlFlow`
And fix the stability attribute on the `pub use` in `core::ops`.
libs-api in https://github.com/rust-lang/rust/issues/75744#issuecomment-2231214910 seemed reasonably happy with naming for these, so let's try for an FCP.
Summary:
```rust
impl<B, C> ControlFlow<B, C> {
pub fn break_value(self) -> Option<B>;
pub fn map_break<T>(self, f: impl FnOnce(B) -> T) -> ControlFlow<T, C>;
pub fn continue_value(self) -> Option<C>;
pub fn map_continue<T>(self, f: impl FnOnce(C) -> T) -> ControlFlow<B, T>;
}
```
Resolves#75744
``@rustbot`` label +needs-fcp +t-libs-api -t-libs
---
Aside, in case it keeps someone else from going down the same dead end: I looked at the `{break,continue}_value` methods and tried to make them `const` as part of this, but that's disallowed because of not having `const Drop`, so put it back to not even unstably-const.
Refactoring to `OpaqueTyOrigin`
Pulled out of a larger PR that uses these changes to do cross-crate encoding of opaque origin, so we can use them for edition 2024 migrations. These changes should be self-explanatory on their own, tho 😄