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 😄
Fix `adt_const_params` leaking `{type error}` in error msg
Fixes the confusing diagnostic described in #118179. (users would see `{type error}` in some situations, which is pretty weird)
`adt_const_params` tracking issue: #95174
properly elaborate effects implied bounds for super traits
Summary: This PR makes it so that we elaborate `<T as Tr>::Fx: EffectsCompat<somebool>` into `<T as SuperTr>::Fx: EffectsCompat<somebool>` when we know that `trait Tr: ~const SuperTr`.
Some discussion at https://github.com/rust-lang/project-const-traits/issues/2.
r? project-const-traits
`@rust-lang/project-const-traits:` how do we feel about this approach?
Assert that `explicit_super_predicates_of` and `explicit_item_super_predicates` truly only contains bounds for the type itself
We distinguish _implied_ predicates (anything that is implied from elaborating a trait bound) from _super_ predicates, which are are the subset of implied predicates that share the same self type as the trait predicate we're elaborating. This was originally done in #107614, which fixed a large class of ICEs and strange errors where the compiler expected the self type of a trait predicate not to change when elaborating super predicates.
Specifically, super predicates are special for various reasons: they're the valid candidates for trait upcasting, are the only predicates we elaborate when doing closure signature inference, etc. So making sure that we get this list correct and don't accidentally "leak" any other predicates into this list is quite important.
This PR adds some debug assertions that we're in fact not doing so, and it fixes an oversight in the effect desugaring rework.
Implement Return Type Notation (RTN)'s path form in where clauses
Implement return type notation (RTN) in path position for where clauses. We already had RTN in associated type position ([e.g.](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=627a4fb8e2cb334863fbd08ed3722c09)), but per [the RFC](https://rust-lang.github.io/rfcs/3654-return-type-notation.html#where-rtn-can-be-used-for-now):
> As a standalone type, RTN can only be used as the Self type of a where-clause [...]
Specifically, in order to enable code like:
```rust
trait Foo {
fn bar() -> impl Sized;
}
fn is_send(_: impl Send) {}
fn test<T>()
where
T: Foo,
T::bar(..): Send,
{
is_send(T::bar());
}
```
* In the resolver, when we see a `TyKind::Path` whose final segment is `GenericArgs::ParenthesizedElided` (i.e. `(..)`), resolve that path in the *value* namespace, since we're looking for a method.
* When lowering where clauses in HIR lowering, we first try to intercept an RTN self type via `lower_ty_maybe_return_type_notation`. If we find an RTN type, we lower it manually in a way that respects its higher-ranked-ness (see below) and resolves to the corresponding RPITIT. Anywhere else, we'll emit the same "return type notation not allowed in this position yet" error we do when writing RTN in every other position.
* In `resolve_bound_vars`, we add some special treatment for RTN types in where clauses. Specifically, we need to add new lifetime variables to our binders for the early- and late-bound vars we encounter on the method. This implements the higher-ranked desugaring [laid out in the RFC](https://rust-lang.github.io/rfcs/3654-return-type-notation.html#converting-to-higher-ranked-trait-bounds).
This PR also adds a bunch of tests, mostly negative ones (testing error messages).
In a follow-up PR, I'm going to mark RTN as no longer incomplete, since this PR basically finishes the impl surface that we should initially stabilize, and the RFC was accepted.
cc [RFC 3654](https://github.com/rust-lang/rfcs/pull/3654) and https://github.com/rust-lang/rust/issues/109417