Implementing traits marked with `#[rustc_specialization_trait]` normally
requires (min-)specialization to be enabled for the enclosing crate.
With this change, that permission can also be granted by an
`allow_internal_unstable` attribute on the macro that generates the impl.
[rustdoc] Correctly generate path for non-local items in source code pages
While browsing some crates using the "jump to def" feature, I realized that a lot of items didn't have a link generated. The reason is because we only cache foreign items if they appear in the documented API. This means that for the others, we need to infer them.
r? ``@notriddle``
For a rigid projection, recursively look at the self type's item bounds to fix the `associated_type_bounds` feature
Given a deeply nested rigid projection like `<<<T as Trait1>::Assoc1 as Trait2>::Assoc2 as Trait3>::Assoc3`, this PR adjusts both trait solvers to look at the item bounds for all of `Assoc3`, `Assoc2`, and `Assoc1` in order to satisfy a goal. We do this because the item bounds for projections may contain relevant bounds for *other* nested projections when the `associated_type_bounds` (ATB) feature is enabled. For example:
```rust
#![feature(associated_type_bounds)]
trait Trait1 {
type Assoc1: Trait2<Assoc2: Foo>;
// Item bounds for `Assoc1` are:
// `<Self as Trait1>::Assoc1: Trait2`
// `<<Self as Trait1>::Assoc1 as Trait2>::Assoc2: Foo`
}
trait Trait2 {
type Assoc2;
}
trait Foo {}
fn hello<T: Trait1>(x: <<T as Trait1>::Assoc1 as Trait2>::Assoc2) {
fn is_foo(_: impl Foo) {}
is_foo(x);
// Currently fails with:
// ERROR the trait bound `<<Self as Trait1>::Assoc1 as Trait2>::Assoc2: Foo` is not satisfied
}
```
This has been a long-standing place of brokenness for ATBs, and is also part of the reason why ATBs currently desugar so differently in various positions (i.e. sometimes desugaring to param-env bounds, sometimes desugaring to RPITs, etc). For example, in RPIT and TAIT position, `impl Foo<Bar: Baz>` currently desugars to `impl Foo<Bar = impl Baz>` because we do not currently take advantage of these nested item bounds if we desugared them into a single set of item bounds on the opaque. This is obviously both strange and unnecessary if we just take advantage of these bounds as we should.
## Approach
This PR repeatedly peels off each projection of a given goal's self type and tries to match its item bounds against a goal, repeating with the self type of the projection. This is pretty straightforward to implement in the new solver, only requiring us to loop on the self type of a rigid projection to discover inner rigid projections, and we also need to introduce an extra probe so we can normalize them.
In the old solver, we can do essentially the same thing, however we rely on the fact that projections *should* be normalized already. This is obviously not always the case -- however, in the case that they are not fully normalized, such as a projection which has both infer vars and, we bail out with ambiguity if we hit an infer var for the self type.
## Caveats
⚠️ In the old solver, this has the side-effect of actually stalling some higher-ranked trait goals of the form `for<'a> <?0 as Tr<'a>>: Tr2`. Because we stall them, they no longer are eagerly treated as error -- this cause some existing `known-bug` tests to go from fail -> pass.
I'm pretty unconvinced that this is a problem since we make code that we expect to pass in the *new* solver also pass in the *old* solver, though this obviously doesn't solve the *full* problem.
## And then also...
We also adjust the desugaring of ATB to always desugar to a regular associated bound, rather than sometimes to an impl Trait **except** for when the ATB is present in a `dyn Trait`. We need to lower `dyn Trait<Assoc: Bar>` to `dyn Trait<Assoc = impl Bar>` because object types need all of their associated types specified.
I would also be in favor of splitting out the ATB feature and/or removing support for object types in order to stabilize just the set of positions for which the ATB feature is consistent (i.e. always elaborates to a bound).
The meaning of this assertion changed in #120828 when the meaning of
`has_errors` changed to exclude stashed errors. Evidently the new
meaning is too restrictive.
Fixes#120856.
Build DebugInfo for async closures
The test is pretty bare, because I don't really know how to write debuginfo tests. I'd like to land this first, and then flesh it out correctly one it's no longer ICEing on master (which breaks people's ability to test using async closures).
r? oli-obk cc `@rust-lang/wg-debugging` (if any of y'all want to help me write a more fleshed out async closures test)
Emit more specific diagnostics when enums fail to cast with `as`
Fixes#120756
Changes this diagnostic reported in the issue:
```
error[E0605]: non-primitive cast: `Bad` as `u32`
--> src/main.rs:18:10
|
18 | dbg!(bad as u32);
| ^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
```
to this:
```
error[E0605]: non-primitive cast: `Bad` as `u32`
--> src/main.rs:18:10
|
18 | dbg!(bad as u32);
| ^^^^^^^^^^ an `as` expression can be used to convert enum types to numeric types only if the enum type is unit-only or field-less
|
= note: see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information
```
This change is only for enums. The diagnostic remains unchanged for all other cases.
improve normalization of `Pointee::Metadata`
This PR makes it so that `<Wrapper<Tail> as Pointee>::Metadata` is normalized to `<Tail as Pointee>::Metadata` if we don't know `Wrapper<Tail>: Sized`. With that, the trait solver can prove projection predicates like `<Wrapper<Tail> as Pointee>::Metadata == <Tail as Pointee>::Metadata`, which makes it possible to use the metadata APIs to cast between the tail and the wrapper:
```rust
#![feature(ptr_metadata)]
use std::ptr::{self, Pointee};
fn cast_same_meta<T: ?Sized, U: ?Sized>(ptr: *const T) -> *const U
where
T: Pointee<Metadata = <U as Pointee>::Metadata>,
{
let (thin, meta) = ptr.to_raw_parts();
ptr::from_raw_parts(thin, meta)
}
struct Wrapper<T: ?Sized>(T);
fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
cast_same_meta(ptr)
}
```
Previously, this failed to compile:
```
error[E0271]: type mismatch resolving `<Wrapper<T> as Pointee>::Metadata == <T as Pointee>::Metadata`
--> src/lib.rs:16:5
|
15 | fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
| - found this type parameter
16 | cast_same_meta(ptr)
| ^^^^^^^^^^^^^^ expected `Wrapper<T>`, found type parameter `T`
|
= note: expected associated type `<Wrapper<T> as Pointee>::Metadata`
found associated type `<T as Pointee>::Metadata`
= note: an associated type was expected, but a different one was found
```
(Yes, you can already do this with `as` casts. But using functions is so much ✨ *safer* ✨, because you can't change the metadata on accident.)
---
This PR essentially changes the built-in impls of `Pointee` from this:
```rust
// before
impl Pointee for u8 {
type Metadata = ();
}
impl Pointee for [u8] {
type Metadata = usize;
}
// ...
impl Pointee for Wrapper<u8> {
type Metadata = ();
}
impl Pointee for Wrapper<[u8]> {
type Metadata = usize;
}
// ...
// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T: ?Sized> Pointee for Wrapper<T>
where
Wrapper<T>: Sized
{
type Metadata = ();
}
// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
type Metadata = ();
}
```
to this:
```rust
// after
impl Pointee for u8 {
type Metadata = ();
}
impl Pointee for [u8] {
type Metadata = usize;
}
// ...
impl<T: ?Sized> Pointee for Wrapper<T> {
// in the old solver this will instead project to the "deep" tail directly,
// e.g. `Wrapper<Wrapper<T>>::Metadata = T::Metadata`
type Metadata = <T as Pointee>::Metadata;
}
// ...
// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
type Metadata = ();
}
```
Fix more `ty::Error` ICEs in MIR passes
Fixes#120791 - Add a check for `ty::Error` in the `ByMove` coroutine pass
Fixes#120816 - Add a check for `ty::Error` in the MIR validator
Also a drive-by fix for a FIXME I had asked oli to add
r? oli-obk
Make privacy visitor use types more (instead of HIR)
r? ``@petrochenkov``
This is a prerequisite to normalizing projections, as otherwise we have too many invalid bound vars (hir_ty_to_ty is creating types that have bound vars, but no binder).
The commits are still chaotic, I'm gonna clean them up, but I just wanted to let you know about the general direction and wondering if we could land this before adding normalization, as normalization is where behavioral changes happen, and I'd like to keep that part as minimal as possible.
[context can be found on zulip](https://rust-lang.zulipchat.com/#narrow/stream/315482-t-compiler.2Fetc.2Fopaque-types/topic/weak.20type.20aliases.20and.20privacy)
Toggle assert_unsafe_precondition in codegen instead of expansion
The goal of this PR is to make some of the unsafe precondition checks in the standard library available in debug builds. Some UI tests are included to verify that it does that.
The diff is large, but most of it is blessing mir-opt tests and I've also split up this PR so it can be reviewed commit-by-commit.
This PR:
1. Adds a new intrinsic, `debug_assertions` which is lowered to a new MIR NullOp, and only to a constant after monomorphization
2. Rewrites `assume_unsafe_precondition` to check the new intrinsic, and be monomorphic.
3. Skips codegen of the `assume` intrinsic in unoptimized builds, because that was silly before but with these checks it's *very* silly
4. The checks with the most overhead are `ptr::read`/`ptr::write` and `NonNull::new_unchecked`. I've simply added `#[cfg(debug_assertions)]` to the checks for `ptr::read`/`ptr::write` because I was unable to come up with any (good) ideas for decreasing their impact. But for `NonNull::new_unchecked` I found that the majority of callers can use a different function, often a safe one.
Yes, this PR slows down the compile time of some programs. But in our benchmark suite it's never more than 1% icount, and the average icount change in debug-full programs is 0.22%. I think that is acceptable for such an improvement in developer experience.
https://github.com/rust-lang/rust/issues/120539#issuecomment-1922687101
Make `min_exhaustive_patterns` match `exhaustive_patterns` better
Split off from https://github.com/rust-lang/rust/pull/120742.
There remained two edge cases where `min_exhaustive_patterns` wasn't behaving like `exhaustive_patterns`. This fixes them, and tests the feature in a bunch more cases. I essentially went through all uses of `exhaustive_patterns` to see which ones would be interesting to compare between the two features.
r? `@compiler-errors`
Rollup of 9 pull requests
Successful merges:
- #119592 (resolve: Unload speculatively resolved crates before freezing cstore)
- #120103 (Make it so that async-fn-in-trait is compatible with a concrete future in implementation)
- #120206 (hir: Make sure all `HirId`s have corresponding HIR `Node`s)
- #120214 (match lowering: consistently lower bindings deepest-first)
- #120688 (GVN: also turn moves into copies with projections)
- #120702 (docs: also check the inline stmt during redundant link check)
- #120727 (exhaustiveness: Prefer "`0..MAX` not covered" to "`_` not covered")
- #120734 (Add `SubdiagnosticMessageOp` as a trait alias.)
- #120739 (improve pretty printing for associated items in trait objects)
r? `@ghost`
`@rustbot` modify labels: rollup
improve pretty printing for associated items in trait objects
* Don't print a binder in front of associated items, because it's not valid syntax.
* e.g. print `dyn for<'a> Trait<'a, Assoc = &'a u8>` instead of `dyn for<'a> Trait<'a, for<'a> Assoc = &'a u8>`.
* Don't print associated items that are implied by a supertrait bound.
* e.g. if we have `trait Sub: Super<Assoc = u8> {}`, then just print `dyn Sub` instead of `dyn Sub<Assoc = u8>`.
I've added the test in the first commit, so you can see the diff of the compiler output in the second commit.
exhaustiveness: Prefer "`0..MAX` not covered" to "`_` not covered"
There was an exception when reporting integer ranges as missing, it's been there for as long as I can remember. This PR removes it. I think it's nicer to report "`0..MAX` not covered" than "`_` not covered". This also makes it consistent with enums, where we report individual enum variants in this case (as showcased in the rest of the `empty-match.rs` test).
r? ``@estebank``
docs: also check the inline stmt during redundant link check
Fixes#120444
This issue was brought about by querying `root::webdavfs::A`, a key that doesn't exist in `doc_link_resolutions`. To avoid a panic, I've altered the gating mechanism to allow this lint pass to be skipped.
I'm not certain if this is the best solution. An alternative approach might be to leverage other info from the name resolutions instead of `doc_link_resolutions`. After all, all we need is to get the resolution from a combination of `(module, name)`. However, I believe they would yield the same outcome, both skipping this lint.
match lowering: consistently lower bindings deepest-first
Currently when lowering match expressions to MIR, we do a funny little dance with the order of bindings. I attempt to explain it in the third commit: we handle refutable (i.e. needing a test) patterns differently than irrefutable ones. This leads to inconsistencies, as reported in https://github.com/rust-lang/rust/issues/120210. The reason we need a dance at all is for situations like:
```rust
fn foo1(x: NonCopyStruct) {
let y @ NonCopyStruct { copy_field: z } = x;
// the above should turn into
let z = x.copy_field;
let y = x;
}
```
Here the `y ```````@```````` binding will move out of `x`, so we need to copy the field first.
I believe that the inconsistency came about when we fixed https://github.com/rust-lang/rust/issues/69971, and didn't notice that the fix didn't extend to refutable patterns. My guess then is that ordering bindings by "deepest-first, otherwise source order" is a sound choice. This PR implements that (at least I hope, match lowering is hard to follow 🥲).
Fixes https://github.com/rust-lang/rust/issues/120210
r? ```````@oli-obk``````` since you merged the original fix to https://github.com/rust-lang/rust/issues/69971
cc ```````@matthewjasper```````
Make it so that async-fn-in-trait is compatible with a concrete future in implementation
There's no technical reason why an AFIT like `async fn foo()` cannot be satisfied with an implementation signature like `fn foo() -> Pin<Box<dyn Future<Output = ()> + 'static>>`.
We rejected this previously because we were uncertain about how AFITs worked with refinement, but I don't believe this needs to be a restriction any longer.
r? oli-obk
resolve: Unload speculatively resolved crates before freezing cstore
Name resolution sometimes loads additional crates to improve diagnostics (e.g. suggest imports).
Not all of these diagnostics result in errors, sometimes they are just warnings, like in #117772.
If additional crates loaded speculatively stay and gets listed by things like `query crates` then they may produce further errors like duplicated lang items, because lang items from speculatively loaded crates are as good as from non-speculatively loaded crates.
They can probably do things like adding unintended impls from speculatively loaded crates to method resolution as well.
The extra crates will also get into the crate's metadata as legitimate dependencies.
In this PR I remove the speculative crates from cstore when name resolution is finished and cstore is frozen.
This is better than e.g. filtering away speculative crates in `query crates` because things like `DefId`s referring to these crates and leaking to later compilation stages can produce ICEs much easier, allowing to detect them.
The unloading could potentially be skipped if any errors were reported (to allow using `DefId`s from speculatively loaded crates for recovery), but I didn't do it in this PR because I haven't seen such cases of recovery. We can reconsider later if any relevant ICEs are reported.
Unblocks https://github.com/rust-lang/rust/pull/117772.
Stop bailing out from compilation just because there were incoherent traits
fixes#120343
but also has a lot of "type annotations needed" fallout. Some are fixed in the second commit.
Make `NonZero` constructors generic.
This makes `NonZero` constructors generic, so that `NonZero::new` can be used without turbofish syntax.
Tracking issue: https://github.com/rust-lang/rust/issues/120257
~~I cannot figure out how to make this work with `const` traits. Not sure if I'm using it wrong or whether there's a bug:~~
```rust
101 | if n == T::ZERO {
| ^^^^^^^^^^^^ expected `host`, found `true`
|
= note: expected constant `host`
found constant `true`
```
r? `@dtolnay`
Reconstify `Add`
r? project-const-traits
I'm not happy with the ui test changes (or failures because I did not bless them and include the diffs in this PR). There is at least some bugs I need to look and try fix:
1. A third duplicated diagnostic when a consumer crate that does not have `effects` enabled has a trait selection error for an upstream const_trait trait. See tests/ui/ufcs/ufcs-qpath-self-mismatch.rs.
2. For some reason, making `Add` a const trait would stop us from suggesting `T: Add` when we try to add two `T`s without that bound. See tests/ui/suggestions/issue-97677.rs
```
error: equality constraints are not yet supported in `where` clauses
--> $DIR/equality-bound.rs:50:9
|
LL | IntoIterator::Item = A,
| ^^^^^^^^^^^^^^^^^^^^^^ not supported
|
= note: see issue #20041 <https://github.com/rust-lang/rust/issues/20041> for more information
help: if `IntoIterator::Item` is an associated type you're trying to set, use the associated type binding syntax
|
LL ~ fn from_iter<T: IntoIterator<Item = A>>(_: T) -> Self
LL | where
LL ~
|
error: equality constraints are not yet supported in `where` clauses
--> $DIR/equality-bound.rs:63:9
|
LL | T::Item = A,
| ^^^^^^^^^^^ not supported
|
= note: see issue #20041 <https://github.com/rust-lang/rust/issues/20041> for more information
help: if `IntoIterator::Item` is an associated type you're trying to set, use the associated type binding syntax
|
LL ~ fn from_iter<T: IntoIterator<Item = A>>(_: T) -> Self
LL | where
LL ~
|
```
Fix#68982.
Record coroutine kind in coroutine generics
Oops, added a new substitution (the "kind" ty) to coroutines but forgot to record it in the `generics_of`. I'm surprised I left this out of the coroutine-closure PR -- I thought I made this change; I possibly rebased it out by accident.
Fixes#120732
r? oli-obk
Add parallel rustc ui tests
Updates #118698
Add some ui tests for parallel rustc front end
This is a relatively large feature so I think it's worth creating a new entity in tests/ui folder, so we need to modify the limit in tidy.
Suggest turning `if let` into irrefutable `let` if appropriate
When encountering an `if let` tail expression without an `else` arm for an enum with a single variant, suggest writing an irrefutable `let` binding instead.
```
error[E0317]: `if` may be missing an `else` clause
--> $DIR/irrefutable-if-let-without-else.rs:8:5
|
LL | fn foo(x: Enum) -> i32 {
| --- expected `i32` because of this return type
LL | / if let Enum::Variant(value) = x {
LL | | value
LL | | }
| |_____^ expected `i32`, found `()`
|
= note: `if` expressions without `else` evaluate to `()`
= help: consider adding an `else` block that evaluates to the expected type
help: consider using an irrefutable `let` binding instead
|
LL ~ let Enum::Variant(value) = x;
LL ~ value
|
```
Fix#61788.
Mark "unused binding" suggestion as maybe incorrect
Ignoring unused bindings should be a determination made by a human, `rustfix` shouldn't auto-apply the suggested change.
Fix#54196.
Add FileCheck annotations to MIR-opt SROA tests
Part of #116971, adds FileCheck annotations to SROA MIR-opt tests in `tests/mir-opt/sroa` and a few uncategorized files.
r? cjgillot
Use the same mir-opt bless targets on all platforms
This undoes some of the implementation in https://github.com/rust-lang/rust/pull/119035, but not the effect. Sorry for the churn, I've learned a lot about how all this works over the past few weeks.
The objective here is to make `x test mir-opt --bless` use the same set of targets on all platforms. It didn't do that from the start because bootstrap assumes that a target linker is available, so the availability of cross-linkers is how we ended up with `MIR_OPT_BLESS_TARGET_MAPPING` and poor support for blessing mir-opt tests from Aarch64 MacOS. This PR corrects that.
So I've adjusted the bless targets for mir-opt tests, as well as tweaked some of the logic in bootstrap about linker configuration so that we don't try to access the cache of cc/linker configuration when doing the mir-opt builds.
While working on that I realized that if I swapped from the `cargo rustc -p std` strategy to `cargo check` on the sysroot, I could use the existing code for check builds to bypass some linker logic. Sweet.
But just doing that doesn't work, because then mir-opt tests complain that they can't find an rlib for any of the standard library crates. That happens because nearly all the mir-opt tests are attempting to build `CrateType::Executable`. We already have all the MIR required for mir-opt tests from the rmeta files, but since rustc think we're trying to build an executable it demands we have access to all the upstream monomorphizations that only exist in rlibs, not the meta files in a MIR-only sysroot.
So to fix that, I've swapped all the mir-opt tests be passed `--crate-type=rlib`. That works, but leaves us with a few broken mir-opt tests which I've blessed or fixed up; we also lose MIR for some functions so I added `-Clink-dead-code` to paper over that. The inlining changes are because changing the crate-type perturbs the hashes that are compared here to sometimes let us do inlining even in a possibly-recursive call: 4cb17b4e78/compiler/rustc_mir_transform/src/inline.rs (L332-L341)
Rollup of 9 pull requests
Successful merges:
- #119939 (Improve 'generic param from outer item' error for `Self` and inside `static`/`const` items)
- #120331 (pattern_analysis: use a plain `Vec` in `DeconstructedPat`)
- #120396 (Account for unbounded type param receiver in suggestions)
- #120423 (update indirect structural match lints to match RFC and to show up for dependencies)
- #120435 (Suggest name value cfg when only value is used for check-cfg)
- #120502 (Remove `ffi_returns_twice` feature)
- #120507 (Account for non-overlapping unmet trait bounds in suggestion)
- #120513 (Normalize type outlives obligations in NLL for new solver)
- #120707 (Don't expect early-bound region to be local when reporting errors in RPITIT well-formedness)
r? `@ghost`
`@rustbot` modify labels: rollup
Don't expect early-bound region to be local when reporting errors in RPITIT well-formedness
The implicit lifetime in the example code gets replaced with `ReError`, which fails a `sub_regions` check in the lexical region solver. Error reporting ends up calling `is_suitable_region` on an early bound region in the *trait* definition. This causes an ICE because we `expect_local()`.
This is kind of a bad explanation, but this code just makes diagnostics reporting a bit more gracefully fallible. If the reviewer wants a thorough investigation of exactly where we get this region outlives obligation, I can write one up. Doesn't really seem worth it, though, imo.
Fixes#120638Fixes#120648
Normalize type outlives obligations in NLL for new solver
Normalize the type outlives assumptions and obligations in MIR borrowck. This should fix any of the lazy-norm-related MIR borrowck problems.
Also some cleanups from last PR:
1. Normalize obligations in a loop in lexical region resolution
2. Use `deeply_normalize_with_skipped_universes` in lexical resolution since we may have, e.g. `for<'a> Alias<'a>: 'b`.
r? lcnr
Account for non-overlapping unmet trait bounds in suggestion
When a method not found on a type parameter could have been provided by any
of multiple traits, suggest each trait individually, instead of a single
suggestion to restrict the type parameter with *all* of them.
Before:
```
error[E0599]: the method `cmp` exists for reference `&T`, but its trait bounds were not satisfied
--> $DIR/method-on-unbounded-type-param.rs:5:10
|
LL | (&a).cmp(&b)
| ^^^ method cannot be called on `&T` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`T: Ord`
which is required by `&T: Ord`
`&T: Iterator`
which is required by `&mut &T: Iterator`
`T: Iterator`
which is required by `&mut T: Iterator`
help: consider restricting the type parameters to satisfy the trait bounds
|
LL | fn g<T>(a: T, b: T) -> std::cmp::Ordering where T: Iterator, T: Ord {
| +++++++++++++++++++++++++
```
After:
```
error[E0599]: the method `cmp` exists for reference `&T`, but its trait bounds were not satisfied
--> $DIR/method-on-unbounded-type-param.rs:5:10
|
LL | (&a).cmp(&b)
| ^^^ method cannot be called on `&T` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`T: Ord`
which is required by `&T: Ord`
`&T: Iterator`
which is required by `&mut &T: Iterator`
`T: Iterator`
which is required by `&mut T: Iterator`
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following traits define an item `cmp`, perhaps you need to restrict type parameter `T` with one of them:
|
LL | fn g<T: Ord>(a: T, b: T) -> std::cmp::Ordering {
| +++++
LL | fn g<T: Iterator>(a: T, b: T) -> std::cmp::Ordering {
| ++++++++++
```
Fix#108428.
Follow up to #120396, only last commit is relevant.
update indirect structural match lints to match RFC and to show up for dependencies
This is a large step towards implementing https://github.com/rust-lang/rfcs/pull/3535.
We currently have five lints related to "the structural match situation":
- nontrivial_structural_match
- indirect_structural_match
- pointer_structural_match
- const_patterns_without_partial_eq
- illegal_floating_point_literal_pattern
This PR concerns the first 3 of them. (The 4th already is set up to show for dependencies, and the 5th is removed by https://github.com/rust-lang/rust/pull/116284.) nontrivial_structural_match is being removed as per the RFC; the other two are enabled to show up in dependencies.
Fixes https://github.com/rust-lang/rust/issues/73448 by removing the affected analysis.
Account for unbounded type param receiver in suggestions
When encountering
```rust
fn f<T>(a: T, b: T) -> std::cmp::Ordering {
a.cmp(&b) //~ ERROR E0599
}
```
output
```
error[E0599]: no method named `cmp` found for type parameter `T` in the current scope
--> $DIR/method-on-unbounded-type-param.rs:2:7
|
LL | fn f<T>(a: T, b: T) -> std::cmp::Ordering {
| - method `cmp` not found for this type parameter
LL | a.cmp(&b)
| ^^^ method cannot be called on `T` due to unsatisfied trait bounds
|
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following traits define an item `cmp`, perhaps you need to restrict type parameter `T` with one of them:
|
LL | fn f<T: Ord>(a: T, b: T) -> std::cmp::Ordering {
| +++++
LL | fn f<T: Iterator>(a: T, b: T) -> std::cmp::Ordering {
| ++++++++++
```
Fix#120186.
revert stabilization of const_intrinsic_copy
`@rust-lang/wg-const-eval` I don't know what we were thinking when we approved https://github.com/rust-lang/rust/pull/97276... const-eval isn't supposed to be able to mutate anything yet! It's also near impossible to actually call `copy` in const on stable since `&mut` expressions are generally unstable. However, there's one exception...
```rust
static mut INT: i32 = unsafe {
let val = &mut [1]; // `&mut` on arrays is allowed in `static mut`
(val as *mut [i32; 1]).copy_from(&[42], 1);
val[0]
};
fn main() { unsafe {
dbg!(INT);
} }
```
Inside `static mut`, we accept some `&mut` since ~forever, to make `static mut FOO: &mut [T] = &mut [...];` work. We reject any attempt to actually write to that mutable reference though... except for the `copy` functions.
I think we should revert stabilizing these functions that take `*mut`, and then re-stabilize them together with `ptr.write` once mutable references are stable.
(This will likely fail on PowerPC until https://github.com/rust-lang/stdarch/pull/1497 lands. But we'll need a crater run first anyway.)
Suggest `[tail @ ..]` on `[..tail]` and `[...tail]` where `tail` is unresolved
Fixes#120591.
~~Will conflict with #120570~~ (rebased).
r? estebank or compiler
Some cleanups around diagnostic levels.
Plus some refactoring in and around diagnostic levels and emission. Details in the individual commit logs.
r? ````@oli-obk````
Rework support for async closures; allow them to return futures that borrow from the closure's captures
This PR implements a new lowering for async closures via `TyKind::CoroutineClosure` which handles the curious relationship between the closure and the coroutine that it returns.
I wrote up a bunch in [this hackmd](https://hackmd.io/`@compiler-errors/S1HvqQxca)` which will be copied to the dev guide after this PR lands, and hopefully left sufficient comments in the source code explaining why this change is as large as it is.
This also necessitates that they begin implementing the `AsyncFn`-family of traits, rather than the `Fn`-family of traits -- if you need `Fn` implementations, you should probably use the non-sugar `|| async {}` syntax instead.
Notably this PR does not yet implement `async Fn()` syntax sugar for bounds, but I expect to add those soon (**edit:** #120392). For now, users must use `AsyncFn()` traits directly, which necessitates adding the `async_fn_traits` feature gate as well. I will add this as a follow-up very soon.
r? oli-obk
This is based on top of #120322, but that PR is minimal.
Actually abort in -Zpanic-abort-tests
When a test fails in panic=abort, it can be useful to have a debugger or other tooling hook into the `abort()` call for debugging. Doing this some other way would require it to hard code details of Rust's panic machinery.
There's no reason we couldn't have done this in the first place; using a single exit code for "success" or "failed" was just simpler. Now we are aware of the special exit codes for posix and windows platforms, logging a special error if an unrecognized code is used on those platforms, and falling back to just "failure" on other platforms.
This continues to account for `#[should_panic]` inside the test process itself, so there's no risk of misinterpreting a random call to `abort()` as an expected panic. Any exit code besides `TR_OK` is logged as a test failure.
As an added benefit, this would allow us to support panic=immediate_abort (but not `#[should_panic]`), without noise about unexpected exit codes when a test fails.
When encountering an `if let` tail expression without an `else` arm for an
enum with a single variant, suggest writing an irrefutable `let` binding
instead.
```
error[E0317]: `if` may be missing an `else` clause
--> $DIR/irrefutable-if-let-without-else.rs:8:5
|
LL | fn foo(x: Enum) -> i32 {
| --- expected `i32` because of this return type
LL | / if let Enum::Variant(value) = x {
LL | | value
LL | | }
| |_____^ expected `i32`, found `()`
|
= note: `if` expressions without `else` evaluate to `()`
= help: consider adding an `else` block that evaluates to the expected type
help: consider using an irrefutable `let` binding instead
|
LL ~ let Enum::Variant(value) = x;
LL ~ value
|
```
Fix#61788.
Introduce support for `async` bound modifier on `Fn*` traits
Adds `async` to the list of `TraitBoundModifiers`, which instructs AST lowering to map the trait to an async flavor of the trait. For now, this is only supported for `Fn*` to `AsyncFn*`, and I expect that this manual mapping via lang items will be replaced with a better system in the future.
The motivation for adding these bounds is to separate the users of async closures from the exact trait desugaring of their callable bounds. Instead of users needing to be concerned with the `AsyncFn` trait, they should be able to write `async Fn()` and it will desugar to whatever underlying trait we decide is best for the lowering of async closures.
Note: rustfmt support can be done in the rustfmt repo after a subtree sync.
make matching on NaN a hard error, and remove the rest of illegal_floating_point_literal_pattern
These arms would never be hit anyway, so the pattern makes little sense. We have had a future-compat lint against float matches in general for a *long* time, so I hope we can get away with immediately making this a hard error.
This is part of implementing https://github.com/rust-lang/rfcs/pull/3535.
Closes https://github.com/rust-lang/rust/issues/41620 by removing the lint.
https://github.com/rust-lang/reference/pull/1456 updates the reference to match.
coverage: Improve handling of function/closure spans
This is a combination of some loosely-related changes that touch the same code:
1. Make unexpansion of closure bodies more precise, by unexpanding back to the context of the closure declaration, instead of unexpanding all the way back to the top-level context. This preserves the way we handle async desugaring and closures containing a single bang-macro, while also giving better results for closures defined in macros.
2. Skip the normal span-refinement code when dealing with the trivial outer part of an async function.
3. Be more explicit about the fact that `fn_sig_span` has been extended to the start of the function body, and is not necessarily present.
---
`@rustbot` label +A-code-coverage
The two kinds of delayed bug have quite different semantics so a
stronger conceptual separation is nice. (`is_error` is a good example,
because the two kinds have different behaviour.)
The commit also moves the `DelayedBug` variant after `Error` in `Level`,
to reflect the fact that it's weaker than `Error` -- it might trigger an
error but also might not. (The pre-existing `downgrade_to_delayed_bug`
function also reflects the notion that delayed bugs are lower/after
normal errors.)
Plus it condenses some of the comments on `Level` into a table, for
easier reading, and introduces `can_be_top_or_sub` to indicate which
levels can be used in top-level diagnostics vs. subdiagnostics.
Finally, it renames `DiagCtxtInner::span_delayed_bugs` as
`DiagCtxtInner::delayed_bugs`. The `span_` prefix is unnecessary because
some delayed bugs don't have a span.
Rollup of 8 pull requests
Successful merges:
- #119759 (Add FileCheck annotations to dataflow-const-prop tests)
- #120323 (On E0277 be clearer about implicit `Sized` bounds on type params and assoc types)
- #120473 (Only suggest removal of `as_*` and `to_` conversion methods on E0308)
- #120540 (add test for try-block-in-match-arm)
- #120547 (`#![feature(inline_const_pat)]` is no longer incomplete)
- #120552 (Correctly check `never_type` feature gating)
- #120555 (put pnkfelix (me) back on the review queue.)
- #120556 (Improve the diagnostics for unused generic parameters)
r? `@ghost`
`@rustbot` modify labels: rollup
Rollup of 8 pull requests
Successful merges:
- #120484 (Avoid ICE when is_val_statically_known is not of a supported type)
- #120516 (pattern_analysis: cleanup manual impls)
- #120517 (never patterns: It is correct to lower `!` to `_`.)
- #120523 (Improve `io::Read::read_buf_exact` error case)
- #120528 (Store SHOULD_CAPTURE as AtomicU8)
- #120529 (Update data layouts in custom target tests for LLVM 18)
- #120531 (Remove a bunch of `has_errors` checks that have no meaningful or the wrong effect)
- #120533 (Correct paths for hexagon-unknown-none-elf platform doc)
r? `@ghost`
`@rustbot` modify labels: rollup
Improve the diagnostics for unused generic parameters
* Don't emit two errors (namely E0091 *and* E0392) for unused type parameters on *lazy* type aliases
* Fix the diagnostic help message of E0392 for *lazy* type aliases: Don't talk about the “fields” of lazy type aliases (use the term “body” instead) and don't suggest `PhantomData` for them, it doesn't make much sense
* Consolidate the diagnostics for E0091 (unused type parameters in type aliases) and E0392 (unused generic parameters due to bivariance) and make it translatable
* Still keep the error codes distinct (for now)
* Naturally leads to better diagnostics for E0091
r? ```@oli-obk``` (to ballast your review load :P) or compiler
Correctly check `never_type` feature gating
Fixes#120542.
The feature wasn't tested on return type of a generic function type, so it got under the radar in https://github.com/rust-lang/rust/pull/120316.
r? ```@compiler-errors```
`#![feature(inline_const_pat)]` is no longer incomplete
Now that borrow checking and safety checking is implemented for inline constant patterns, the incomplete feature status is not necessary. Stabilizing this feature requires more testing and has some of the same unresolved questions as inline constants.
cc #76001
add test for try-block-in-match-arm
This is noted as an implementation concern under the tracking issue for `?` and `try` blocks. (Issue 31436)
Refs: https://github.com/rust-lang/rust/issues/31436
On E0277 be clearer about implicit `Sized` bounds on type params and assoc types
```
error[E0277]: the size for values of type `[i32]` cannot be known at compilation time
--> f100.rs:2:33
|
2 | let _ = std::mem::size_of::<[i32]>();
| ^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[i32]`
note: required by an implicit `Sized` bound in `std::mem::size_of`
--> /home/gh-estebank/rust/library/core/src/mem/mod.rs:312:22
|
312 | pub const fn size_of<T>() -> usize {
| ^ required by the implicit `Sized` requirement on this bound in `size_of`
```
Fix#120178.
Avoid ICE when is_val_statically_known is not of a supported type
2 ICE with 1 stone!
1. Implement `llvm.is.constant.ptr` to avoid first ICE in linked issue.
2. return `false` when the argument is not one of `i*`/`f*`/`ptr` to avoid second ICE.
fixes#120480
Suggest changing type to const parameters if we encounter a type in the trait bound position
The first commit is just drive-by cleanup.
Provide a structured suggestion if the user forgot to prefix a “const parameter” with `const`, e.g., in `struct Tagged<TAG: u64>;`. This happens to me from time to time. Maybe C++ devs are also prone to this mistake given template syntax looks like `template<typename T, uint32_t N>`.
coverage: Use normal `edition:` headers in coverage tests
Some of these tests were originally written as part of a custom `run-make` test, so at that time they weren't able to use the normal compiletest header directive parser.
Now that they're properly integrated, there's no need for them to use `compile-flags` to specify the edition, since they can use `edition` instead.
In most cases the `.cov-map` snapshot isn't affected at all, but in a few cases we add or remove a line, which slightly disturbs the first line number in each instrumented function.
Some of these tests were originally written as part of a custom `run-make`
test, so at that time they weren't able to use the normal compiletest header
directive parser.
Now that they're properly integrated, there's no need for them to use
`compile-flags` to specify the edition, since they can use `edition` instead.
In #119972 the code should have become `E0123` rather than `0123`. This
fix doesn't affect the outcome because the proc macro errors out before
the type of the code is checked, but the fix makes the test's code
consistent with other similar code elsewhere.
Given the previous change to add implicit `Sized` bounds only if there
isn't already an explicit `Sized` bound, now the incr comp machinery
doesn't consider adding the explicit bound as being dirty, as long as
`-Zincremental-ignore-spans` is set.
```
error[E0277]: the size for values of type `[i32]` cannot be known at compilation time
--> f100.rs:2:33
|
2 | let _ = std::mem::size_of::<[i32]>();
| ^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[i32]`
note: required by an implicit `Sized` bound in `std::mem::size_of`
--> /home/gh-estebank/rust/library/core/src/mem/mod.rs:312:22
|
312 | pub const fn size_of<T>() -> usize {
| ^ required by the implicit `Sized` requirement on this bound in `size_of`
```
Fix#120178.
rustdoc: Correctly handle attribute merge if this is a glob reexport
Fixes#120487.
The regression was introduced in https://github.com/rust-lang/rust/pull/113091. Only non-glob reexports should have been impacted.
cc `````@Nemo157`````
r? `````@notriddle`````
Don't hash lints differently to non-lints.
`Diagnostic::keys`, which is used for hashing and equating diagnostics, has a surprising behaviour: it ignores children, but only for lints. This was added in #88493 to fix some duplicated diagnostics, but it doesn't seem necessary any more.
This commit removes the special case and only four tests have changed output, with additional errors. And those additional errors aren't exact duplicates, they're just similar. For example, in src/tools/clippy/tests/ui/same_name_method.rs we currently have this error:
```
error: method's name is the same as an existing method in a trait
--> $DIR/same_name_method.rs:75:13
|
LL | fn foo() {}
| ^^^^^^^^^^^
|
note: existing `foo` defined here
--> $DIR/same_name_method.rs:79:9
|
LL | impl T1 for S {}
| ^^^^^^^^^^^^^^^^
```
and with this change we also get this error:
```
error: method's name is the same as an existing method in a trait
--> $DIR/same_name_method.rs:75:13
|
LL | fn foo() {}
| ^^^^^^^^^^^
|
note: existing `foo` defined here
--> $DIR/same_name_method.rs:81:9
|
LL | impl T2 for S {}
|
```
I think printing this second argument is reasonable, possibly even preferable to hiding it. And the other cases are similar.
r? `@estebank`
Provide more context on derived obligation error primary label
Expand the primary span of E0277 when the immediate unmet bound is not what the user wrote:
```
error[E0277]: the trait bound `i32: Bar` is not satisfied
--> f100.rs:6:6
|
6 | <i32 as Foo>::foo();
| ^^^ the trait `Bar` is not implemented for `i32`, which is required by `i32: Foo`
|
help: this trait has no implementations, consider adding one
--> f100.rs:2:1
|
2 | trait Bar {}
| ^^^^^^^^^
note: required for `i32` to implement `Foo`
--> f100.rs:3:14
|
3 | impl<T: Bar> Foo for T {}
| --- ^^^ ^
| |
| unsatisfied trait bound introduced here
```
Fix#40120.