Introduce support for `async gen` blocks
I'm delighted to demonstrate that `async gen` block are not very difficult to support. They're simply coroutines that yield `Poll<Option<T>>` and return `()`.
**This PR is WIP and in draft mode for now** -- I'm mostly putting it up to show folks that it's possible. This PR needs a lang-team experiment associated with it or possible an RFC, since I don't think it falls under the jurisdiction of the `gen` RFC that was recently authored by oli (https://github.com/rust-lang/rfcs/pull/3513, https://github.com/rust-lang/rust/issues/117078).
### Technical note on the pre-generator-transform yield type:
The reason that the underlying coroutines yield `Poll<Option<T>>` and not `Poll<T>` (which would make more sense, IMO, for the pre-transformed coroutine), is because the `TransformVisitor` that is used to turn coroutines into built-in state machine functions would have to destructure and reconstruct the latter into the former, which requires at least inserting a new basic block (for a `switchInt` terminator, to match on the `Poll` discriminant).
This does mean that the desugaring (at the `rustc_ast_lowering` level) of `async gen` blocks is a bit more involved. However, since we already need to intercept both `.await` and `yield` operators, I don't consider it much of a technical burden.
r? `@ghost`
never_patterns: Parse match arms with no body
Never patterns are meant to signal unreachable cases, and thus don't take bodies:
```rust
let ptr: *const Option<!> = ...;
match *ptr {
None => { foo(); }
Some(!),
}
```
This PR makes rustc accept the above, and enforces that an arm has a body xor is a never pattern. This affects parsing of match arms even with the feature off, so this is delicate. (Plus this is my first non-trivial change to the parser).
~~The last commit is optional; it introduces a bit of churn to allow the new suggestions to be machine-applicable. There may be a better solution? I'm not sure.~~ EDIT: I removed that commit
r? `@compiler-errors`
A refactoring in #117076 changed the `DefIdVisitorSkeleton` to avoid
calling `visit_projection_ty` for `ty::Projection` aliases, and instead
just iterate over the args - this makes sense, as `visit_projection_ty`
will indirectly visit all of the same args, but in doing so, will also
create a `TraitRef` containing the trait's `DefId`, which also gets
visited. The trait's `DefId` isn't visited when we only visit the
arguments without separating them into `TraitRef` and own args first.
Signed-off-by: David Wood <david@davidtw.co>
When MIR is built for an if-not expression, the `!` part of the condition
doesn't correspond to any MIR statement, so coverage instrumentation normally
can't see it.
We can fix that by deliberately injecting a dummy statement whose sole purpose
is to associate that span with its enclosing block.
There are cases where coverage instrumentation wants to show a span for some
syntax element, but there is no MIR node that naturally carries that span, so
the instrumentor can't see it.
MIR building can now use this new kind of coverage statement to deliberately
include those spans in MIR, attached to a dummy statement that has no other
effect.
Resolve associated item bindings by namespace
This is the 3rd commit split off from #118360 with tests reblessed (they no longer contain duplicated diags which were caused by 4c0addc80a) & slightly adapted (removed supertraits from a UI test, cc #118040).
> * Resolve all assoc item bindings (type, const, fn (feature `return_type_notation`)) by namespace instead of trying to resolve a type first (in the non-RTN case) and falling back to consts afterwards. This is consistent with RTN. E.g., for `Tr<K = {…}>` we now always try to look up assoc consts (this extends to supertrait bounds). This gets rid of assoc tys shadowing assoc consts in assoc item bindings which is undesirable & inconsistent (types and consts live in different namespaces after all)
> * Consolidate the resolution of assoc {ty, const} bindings and RTN (dedup, better diags for RTN)
> * Fix assoc consts being labeled as assoc *types* in several diagnostics
> * Make a bunch of diagnostics translatable
Fixes#112560 (error → pass).
As discussed
r? `@compiler-errors`
---
**Addendum**: What I call “associated item bindings” are commonly referred to as “type bindings” for historical reasons. Nowadays, “type bindings” include assoc type bindings, assoc const bindings and RTN (return type notation) which is why I prefer not to use this outdated term.
coverage: Merge refined spans in a separate final pass
Pulling this merge step out of `push_refined_span` and into a separate pass lets us push directly to `refined_spans` instead of calling a helper method.
Because the compiler can now see partial borrows of `refined_spans`, we can remove some extra code that was jumping through hoops to satisfy the borrow checker.
---
``@rustbot`` label +A-code-coverage
Tell MirUsedCollector that the pointer alignment checks calls its panic symbol
Fixes https://github.com/rust-lang/rust/pull/118683 (not an issue, but that PR is a basically a bug report)
When we had `panic_immediate_abort` start adding `#[inline]` to this panic function, builds started breaking because we failed to write up the MIR assert terminator to the correct panic shim. Things happened to work before by pure luck because without this feature enabled, the function we're inserting calls to is `#[inline(never)]` so we always generated code for it.
r? bjorn3
coverage: Avoid unnecessary macros in unit tests
These macros don't provide enough value to justify their complexity, when they can just as easily be functions instead.
---
`@rustbot` label +A-code-coverage
The instance evaluation is needed to handle intrinsics such as
`type_id` and `type_name`.
Since we now use Allocation to represent all evaluated constants,
provide a few methods to help process the data inside an allocation.
`GenKillAnalysis` has five methods that take a transfer function arg:
- `statement_effect`
- `before_statement_effect`
- `terminator_effect`
- `before_terminator_effect`
- `call_return_effect`
All the transfer function args have type `&mut impl GenKill<Self::Idx>`,
except for `terminator_effect`, which takes the simpler `Self::Domain`.
But only the first two need to be `impl GenKill`. The other
three can all be `Self::Domain`, just like `Analysis`. So this commit
changes the last two to take `Self::Domain`, making `GenKillAnalysis`
and `Analysis` more similar.
(Another idea would be to make all these methods `impl GenKill`. But
that doesn't work: `MaybeInitializedPlaces::terminator_effect` requires
the arg be `Self::Domain` so that `self_is_unwind_dead(place, state)`
can be called on it.)
This results in two non-generic types being used: `BorrowckResults` and
`BorrowckFlowState`. It's a net reduction in lines of code, and a little
easier to read.
Rollup of 6 pull requests
Successful merges:
- #116420 (discard invalid spans in external blocks)
- #118686 (Only check principal trait ref for object safety)
- #118688 (Add method to get type of an Rvalue in StableMIR)
- #118707 (Ping GuillaumeGomez for changes in rustc_codegen_gcc)
- #118712 (targets: remove not-added {i386,i486}-unknown-linux-gnu)
- #118719 (CFI: Add char to CFI integer normalization)
Failed merges:
- #117586 (Uplift the (new solver) canonicalizer into `rustc_next_trait_solver`)
r? `@ghost`
`@rustbot` modify labels: rollup
It is used just once. With it removed, the relevant code is a little
boilerplate-y but much easier to read, and is the same length. Overall I
think it's an improvement.
targets: remove not-added {i386,i486}-unknown-linux-gnu
These files were added to the repository but never wired up so they could be used - and that was a few years ago without anyone noticing - so let's remove these, they can be re-added if someone wants them.
cc #80662
r? ```@pnkfelix``` (familiar with the tier policy and Wesley is on vacation)
Add method to get type of an Rvalue in StableMIR
Provide a method to StableMIR users to retrieve the type of an Rvalue operation. There were two possible implementation:
1. Create the logic inside stable_mir to process the type according to the Rvalue semantics, which duplicates the logic of `rustc_middle::mir::Rvalue::ty()`.
2. Implement the Rvalue translation from StableMIR back to internal representation, invoke the `rustc_middle::mir::Rvalue::ty()`, and translate the return value to StableMIR.
I chose the first one for now since the duplication was fairly small, and the option 2 would require way more work to translate everything back to rustc internal representation. If we eventually add those translations, we could easily swap to the option 2.
```@compiler-errors``` / ```@ouz-a``` Please let me know if you have any strong opinion here.
r? ```@compiler-errors```
Only check principal trait ref for object safety
It should make things a bit faster, in case we end up registering a bunch of object safety preds.
r? ```@ghost```
discard invalid spans in external blocks
Fixes#116203
This PR has discarded the invalid `const_span`, thereby making the format more neat.
r? ``@Nilstrieb``
Avoid adding builtin functions to `symbols.o`
We found performance regressions in #113923. The problem seems to be that `--gc-sections` does not remove these symbols. I tested that lld removes these symbols, but ld and gold do not.
I found that `used` adds symbols to `symbols.o` at 3e202ead60/compiler/rustc_codegen_ssa/src/back/linker.rs (L1786-L1791).
The PR removes builtin functions.
Note that under LTO, ld still preserves these symbols. (lld will still remove them.)
The first commit also fixes#118559. But I think the second commit also makes sense.
compile-time evaluation: detect writes through immutable pointers
This has two motivations:
- it unblocks https://github.com/rust-lang/rust/pull/116745 (and therefore takes a big step towards `const_mut_refs` stabilization), because we can now detect if the memory that we find in `const` can be interned as "immutable"
- it would detect the UB that was uncovered in https://github.com/rust-lang/rust/pull/117905, which was caused by accidental stabilization of `copy` functions in `const` that can only be called with UB
When UB is detected, we emit a future-compat warn-by-default lint. This is not a breaking change, so completely in line with [the const-UB RFC](https://rust-lang.github.io/rfcs/3016-const-ub.html), meaning we don't need t-lang FCP here. I made the lint immediately show up for dependencies since it is nearly impossible to even trigger this lint without `const_mut_refs` -- the accidentally stabilized `copy` functions are the only way this can happen, so the crates that popped up in #117905 are the only causes of such UB (in the code that crater covers), and the three cases of UB that we know about have all been fixed in their respective crates already.
The way this is implemented is by making use of the fact that our interpreter is already generic over the notion of provenance. For CTFE we now use the new `CtfeProvenance` type which is conceptually an `AllocId` plus a boolean `immutable` flag (but packed for a more efficient representation). This means we can mark a pointer as immutable when it is created as a shared reference. The flag will be propagated to all pointers derived from this one. We can then check the immutable flag on each write to reject writes through immutable pointers.
I just hope perf works out.
Fix `rustc_codegen_gcc` build and tests failure in CI
https://github.com/rust-lang/rust/pull/118463 seems to have broke the PR CI, more specificaly the `x86_64-gnu-llvm-16` builder which [fail with](https://github.com/rust-lang/rust/actions/runs/7128709674/job/19411205695?pr=118705#step:26:1668):
```
Building stage1 codegen backend gcc (x86_64-unknown-linux-gnu)
Compiling libc v0.2.147
Compiling rustix v0.38.8
Compiling memchr v2.5.0
Compiling bitflags v2.4.0
Compiling linux-raw-sys v0.4.5
Compiling fastrand v2.0.0
Compiling smallvec v1.10.0
error: invalid `--check-cfg` argument: `values(freebsd10)` (expected `cfg(name, values("value1", "value2", ... "valueN"))`)
error: could not compile `libc` (lib) due to previous error
```
Updating to `libc` version 0.2.150 fixes the build issue since it includes the support for the new check-cfg syntax.
Then it [failed](https://github.com/rust-lang/rust/actions/runs/7129280743/job/19413025132?pr=118706#step:26:2218) with a missing `#![allow(internal_features)]` in one of the example.
r? `@GuillaumeGomez`
These files were added to the repository but never wired up so they could
be used - and that was a few years ago without anyone noticing - so let's
remove these, they can be re-added if someone wants them.
Signed-off-by: David Wood <david@davidtw.co>
`EvaluatedToUnknown` -> `EvaluatedToAmbigStackDependent`, `EvaluatedToRecur` -> `EvaluatedToErrStackDependent`
Less confusing names, since the only difference between them and their parallel `EvalutedTo..` is that they are stack dependent.
r? lcnr
Remove `PolyGenSig` since it's always a dummy binder
Coroutines are never polymorphic in their signature. This cleans up a FIXME in the code:
```
/// Returns the "coroutine signature", which consists of its yield
/// and return types.
///
/// N.B., some bits of the code prefers to see this wrapped in a
/// binder, but it never contains bound regions. Probably this
/// function should be removed.
```
Fix is_foreign_item for StableMIR instance
Change the implementation of `Instance::is_foreign_item` to directly query the compiler for the instance `def_id` instead of incorrectly relying on the conversion to `CrateItem`. I also added a method to check if the instance has body, since the function already existed and it just wasn't exposed via public APIs. This makes it much cheaper for the user to check if the instance has body.
## Background:
- In pull https://github.com/rust-lang/rust/pull/118524, I fixed the conversion from Instance to CrateItem to avoid the conversion if the instance didn't have a body available. This broke the `is_foreign_item`.
r? `@ouz-a`
rustc_arena: add `alloc_str`
Two places called `from_utf8_unchecked` for strings from `alloc_slice`,
and one's SAFETY comment said this was for lack of `alloc_str` -- so
let's just add that instead!
Enforce `must_use` on associated types and RPITITs that have a must-use trait in bounds
Warn when an RPITIT or (un-normalized) associated type with a `#[must_use]` trait in its bounds is unused.
This is pending T-lang approval, since it changes the semantics of the `#[must_use]` attribute slightly, but I think it strictly catches more strange errors.
I could also limit this to just RPITITs, but that seems less useful.
Fixes#118444
tip for define macro name after `macro_rules!`
Fixes#118295
~Note that there are some bad case such as `macro_rules![]` or `macro_rules!()`. However, I think these are acceptable as they are likely to be seldom used (feel free to close this if you think its shortcomings outweigh its benefits)~
Edit: this problem was resolved by utilizing the `source_map.span_to_next_source`.
r? `@petrochenkov`
Suppress warnings in LLVM wrapper when targeting MSVC
The LLVM header files generate many warnings when compiled using MSVC. This makes it difficult to work on the LLVM wrapper code, because the warnings and errors that are relevant to local edits are obscured by the hundreds of lines of warnings from the LLVM Headers.
Use the glob binding in resolve_rustdoc_path process
Fixes#117920
Returning `None` seems enough.
I reproduces and tests this locally by `cargo +stage1 build`, but I cannot reproduce this ICE by putting [the following code](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=8b3ca8f4a7676eb90baf30437ba041a2) into `tests/ui/...` and then compiling it using `rustc +stage1 /path/to/test.rs` or `x.py test`:
```rust
#![crate_type = "lib"]
use super::Hasher;
/// [`Hasher`]
pub use core:#️⃣:*;
```
r? `@petrochenkov`
Change the implementation of `Instance::is_foreign_item` to directly
query the compiler for the instance `def_id` instead of incorrectly
relying on the conversion to `CrateItem`.
Background:
- In pull https://github.com/rust-lang/rust/pull/118524, I fixed the
conversion from Instance to CrateItem to avoid the conversion if the
instance didn't have a body available. This broke the `is_foreign_item`.
Add ADT variant infomation to StableMIR and finish implementing TyKind::internal()
Introduce a `VariantDef` type and a mechanism to retrieve the definition from an `AdtDef`.
The `VariantDef` representation itself is just a combination of `AdtDef` and `VariantIdx`, which allow us to retrieve further information of a variant. I don't think we need to cache extra information for now, and we can translate on an on demand manner. I am leaving the fields public today due to https://github.com/rust-lang/project-stable-mir/issues/56, but they shouldn't. For this PR, I've only added a method to retrieve the variant name, and its fields. I also added an implementation of `RustcInternal` that allow users to retrieve more information using Rust internal APIs.
I have also finished the implementation of `RustcInternal` for `TyKind` which fixes https://github.com/rust-lang/project-stable-mir/issues/46.
## Motivation
Both of these changes are needed in order to properly interpret things like projections. For example,
- The variant definition is used to find out which variant we are downcasting to.
- Being able to create `Ty` from `TyKind` helps for example processing each stage of a projection, like the code in `place.ty()`.
`riscv32` platform support
This PR adds the following RISCV targets to the tier 2 list of targets:
- riscv32imafc-unknown-none-elf
- riscv32im-unknown-none-elf
The rationale behind adding them directly to tier 2, is that the other bare metal targets already exist at tier 2, and these new targets are the same with an additional target feature enabled.
As well as the additional targets, this PR fills out the platform support document(s) that were previously missing.
~~The RISC-V bare metal targets don't currently have a platform support document, but this will change soon as the RISC-V team from the Rust-embedded working group will maintain these once https://github.com/davidtwco/rust/pull/1 is merged (and `@davidtwco's` upstream PR is merged after). For the time being you can cc myself or any other member of the RISC-V team: https://github.com/orgs/rust-embedded/teams/riscv.~~
> A tier 2 target must have value to people other than its maintainers. (It may still be a niche target, but it must not be exclusively useful for an inherently closed group.)
RISC-V is an open specification, used and accessible to anyone including individuals.
> A tier 2 target must have a designated team of developers (the "target maintainers") available to consult on target-specific build-breaking issues, or if necessary to develop target-specific language or library implementation details. This team must have at least 2 developers.
This rust-embedded working group's [RISCV team](https://github.com/orgs/rust-embedded/teams/riscv) will maintain these targets.
> The target must not place undue burden on Rust developers not specifically concerned with that target. Rust developers are expected to not gratuitously break a tier 2 target, but are not expected to become experts in every tier 2 target, and are not expected to provide target-specific implementations for every tier 2 target.
I don't forsee this being an issue, the RISCV team will ensure we avoid undue burden for the general Rust community.
> The target must provide documentation for the Rust community explaining how to build for the target using cross-compilation, and explaining how to run tests for the target. If at all possible, this documentation should show how to run Rust programs and tests for the target using emulation, to allow anyone to do so. If the target cannot be feasibly emulated, the documentation should explain how to obtain and work with physical hardware, cloud systems, or equivalent.
There are links to resources we maintain in the re wg org in the platform support document.
> The target must document its baseline expectations for the features or versions of CPUs, operating systems, libraries, runtime environments, and similar.
Documented in the platform support document.
> If introducing a new tier 2 or higher target that is identical to an existing Rust target except for the baseline expectations for the features or versions of CPUs, operating systems, libraries, runtime environments, and similar, then the proposed target must document to the satisfaction of the approving teams why the specific difference in baseline expectations provides sufficient value to justify a separate target.
New target features in RISCV can drastically change the capability of a CPU, hence the need for a separate target to support different variants. We aim to support any ratified RISCV extensions.
> Tier 2 targets must not leave any significant portions of core or the standard library unimplemented or stubbed out, unless they cannot possibly be supported on the target.
`core` is fully implemented.
> The code generation backend for the target should not have deficiencies that invalidate Rust safety properties, as evaluated by the Rust compiler team. (This requirement does not apply to arbitrary security enhancements or mitigations provided by code generation backends, only to those properties needed to ensure safe Rust code cannot cause undefined behavior or other unsoundness.) If this requirement does not hold, the target must clearly and prominently document any such limitations as part of the target's entry in the target tier list, and ideally also via a failing test in the testsuite. The Rust compiler team must be satisfied with the balance between these limitations and the difficulty of implementing the necessary features.
RISCV is a well-established and well-maintained LLVM backend. To the best of my knowledge, the backend won't cause the generated code to have undefined behaviour.
> If the target supports C code, and the target has an interoperable calling convention for C code, the Rust target must support that C calling convention for the platform via extern "C". The C calling convention does not need to be the default Rust calling convention for the target, however.
The C calling convention is supported by RISCV.
> The target must build reliably in CI, for all components that Rust's CI considers mandatory.
For the last 4-5 years many of these RISCV targets have been building in CI without any known issues.
> The approving teams may additionally require that a subset of tests pass in CI, such as enough to build a functional "hello world" program, ./x.py test --no-run, or equivalent "smoke tests". In particular, this requirement may apply if the target builds host tools, or if the tests in question provide substantial value via early detection of critical problems.
Not applicable, in the future we may wish to add qemu tests but this is out of scope for now.
> Building the target in CI must not take substantially longer than the current slowest target in CI, and should not substantially raise the maintenance burden of the CI infrastructure. This requirement is subjective, to be evaluated by the infrastructure team, and will take the community importance of the target into account.
To the best of my knowledge, this will not induce a burden on the current CI infra.
> Tier 2 targets should, if at all possible, support cross-compiling. Tier 2 targets should not require using the target as the host for builds, even if the target supports host tools.
Cross-compilation is supported and documented in the platform support document.
> In addition to the legal requirements for all targets (specified in the tier 3 requirements), because a tier 2 target typically involves the Rust project building and supplying various compiled binaries, incorporating the target and redistributing any resulting compiled binaries (e.g. built libraries, host tools if any) must not impose any onerous license requirements on any members of the Rust project, including infrastructure team members and those operating CI systems. This is a subjective requirement, to be evaluated by the approving teams.
There are no additional license issues to worry about.
> Tier 2 targets must not impose burden on the authors of pull requests, or other developers in the community, to ensure that tests pass for the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on tests failing for the target. Do not send automated messages or notifications (via any medium, including via `@)` to a PR author or others involved with a PR regarding the PR breaking tests on a tier 2 target, unless they have opted into such messages.
The RISCV team agrees not to do this.
> The target maintainers should regularly run the testsuite for the target, and should fix any test failures in a reasonably timely fashion.
The RISCV team will fix any issues in a timely manner.
Provide context when `?` can't be called because of `Result<_, E>`
When a method chain ending in `?` causes an E0277 because the expression's `Result::Err` variant doesn't have a type that can be converted to the `Result<_, E>` type parameter in the return type, provide additional context of which parts of the chain can and can't support the `?` operator.
```
error[E0277]: `?` couldn't convert the error to `String`
--> $DIR/question-mark-result-err-mismatch.rs:27:25
|
LL | fn bar() -> Result<(), String> {
| ------------------ expected `String` because of this
LL | let x = foo();
| ----- this has type `Result<_, String>`
...
LL | .map_err(|_| ())?;
| ---------------^ the trait `From<()>` is not implemented for `String`
| |
| this can't be annotated with `?` because it has type `Result<_, ()>`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following other types implement trait `From<T>`:
<String as From<char>>
<String as From<Box<str>>>
<String as From<Cow<'a, str>>>
<String as From<&str>>
<String as From<&mut str>>
<String as From<&String>>
= note: required for `Result<(), String>` to implement `FromResidual<Result<Infallible, ()>>`
```
Fix#72124.
Currently LLVM uses emutls by default
for some targets (such as android, openbsd),
but rust does not use it, because `has_thread_local` is false.
This commit has some changes to allow users to enable emutls:
1. add `-Zhas-thread-local` flag to specify
that std uses `#[thread_local]` instead of pthread key.
2. when using emutls, decorate symbol names
to find thread local symbol correctly.
3. change `-Zforce-emulated-tls` to `-Ztls-model=emulated`
to explicitly specify whether to generate emutls.
Remove `#[rustc_host]`, use internal desugaring
Also removed a way for users to explicitly specify the host param since that isn't particularly useful. This should eliminate any pain with encoding attributes across crates and etc.
r? `@compiler-errors`
coverage: Be more strict about what counts as a "visible macro"
This is a follow-up to the workaround in #117827, and I believe it now properly fixes#117788.
The old code treats a span as having a “visible macro” if it is part of a macro-expansion, and its parent callsite's context is the same as the body span's context. But if the body span is itself part of an expansion, the macro in question might not actually be visible from the body span. That results in the macro name's length being meaningless as a span offset.
We now only consider spans whose parent callsite is the same as the source callsite, i.e. the parent has no parent.
---
I've also included some related cleanup for the code added by #117827. That code was more complicated than normal, because I wanted it to be easy to backport to stable/beta.
Added shadowed hint for overlapping associated types
Previously, when you tried to set an associated type that is shadowed by an associated type in a subtrait, like this:
```rust
trait A {
type X;
}
trait B: A {
type X; // note: this is legal
}
impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
fn clone(&self) -> Self {
todo!()
}
}
you got a confusing error message, that says nothing about the shadowing:
error[E0719]: the value of the associated type `X` (from trait `B`) is already specified
--> test.rs:9:34
|
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
| --- ^^^ re-bound here
| |
| `X` bound here first
error[E0191]: the value of the associated type `X` (from trait `A`) must be specified
--> test.rs:9:27
|
2 | type X;
| ------ `X` defined here
...
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
| ^^^^^^^^^^^ help: specify the associated type: `B<X=Y, X=Y, X = Type>`
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0191, E0719.
For more information about an error, try `rustc --explain E0191`.
```
Now instead, the error shows that the associated type is shadowed, and suggests renaming as a potential fix.
```rust
error[E0719]: the value of the associated type `X` in trait `B` is already specified
--> test.rs:9:34
|
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
| --- ^^^ re-bound here
| |
| `X` bound here first
error[E0191]: the value of the associated type `X` in `A` must be specified
--> test.rs:9:27
|
2 | type X;
| ------ `A::X` defined here
...
6 | type X; // note: this is legal
| ------ `A::X` shadowed here
...
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
| ^^^^^^^^^^^ associated type `X` must be specified
|
help: consider renaming this associated type
--> test.rs:2:5
|
2 | type X;
| ^^^^^^
help: consider renaming this associated type
--> test.rs:6:5
|
6 | type X; // note: this is legal
| ^^^^^^
```
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0191, E0719.
For more information about an error, try `rustc --explain E0191`.
The rename help message is only emitted when the trait is local. This is true both for the supertrait as for the subtrait.
There might be cases where you can use the fully qualified path (for instance, in a where clause), but this PR currently does not deal with that.
fixes#100109
(continues from #117642, because I didn't know renaming the branch would close the PR)
Shadowing the associated type of a supertrait is allowed.
This however makes it impossible to set the associated type
of the supertrait in a dyn object.
This PR makes the error message for that case clearer, like
adding a note that shadowing is happening, as well as suggesting
renaming of one of the associated types.
r=petrochenckov
Use `unwinding` crate for unwinding on Xous platform
This patch adds support for using [unwinding](https://github.com/nbdd0121/unwinding) on platforms where libunwinding isn't viable. An example of such a platform is `riscv32imac-unknown-xous-elf`.
### Background
The Rust project maintains a fork of llvm at [llvm-project](https://github.com/rust-lang/llvm-project/) where it applies patches on top of the llvm project. This mostly seems to be to get unwinding support for the SGX project, and there may be other patches that I'm unaware of.
There is a lot of machinery in the build system to support compiling `libunwind` on other platforms, and I needed to add additional patches to llvm in order to add support for Xous.
Rather than continuing down this path, it seemed much easier to use a Rust-based library. The `unwinding` crate by `@nbdd0121` fits this description perfectly.
### Future work
This could potentially replace the custom patches for `libunwind` on other platforms such as SGX, and could enable unwinding support on many more exotic platforms.
### Anti-goals
This is not designed to replace `libunwind` on tier-one platforms or those where unwinding support already exists. There is already a well-established approach for unwinding there. Instead, this aims to enable unwinding on new platforms where C++ code may be difficult to compile.
Two places called `from_utf8_unchecked` for strings from `alloc_slice`,
and one's SAFETY comment said this was for lack of `alloc_str` -- so
let's just add that instead!
When a method chain ending in `?` causes an E0277 because the
expression's `Result::Err` variant doesn't have a type that can be
converted to the `Result<_, E>` type parameter in the return type,
provide additional context of which parts of the chain can and can't
support the `?` operator.
```
error[E0277]: `?` couldn't convert the error to `String`
--> $DIR/question-mark-result-err-mismatch.rs:28:25
|
LL | fn bar() -> Result<(), String> {
| ------------------ expected `String` because of this
LL | let x = foo();
| ----- this can be annotated with `?` because it has type `Result<String, String>`
LL | let one = x
LL | .map(|s| ())
| ----------- this can be annotated with `?` because it has type `Result<(), String>`
LL | .map_err(|_| ())?;
| ---------------^ the trait `From<()>` is not implemented for `String`
| |
| this can't be annotated with `?` because it has type `Result<(), ()>`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following other types implement trait `From<T>`:
<String as From<char>>
<String as From<Box<str>>>
<String as From<Cow<'a, str>>>
<String as From<&str>>
<String as From<&mut str>>
<String as From<&String>>
= note: required for `Result<(), String>` to implement `FromResidual<Result<Infallible, ()>>`
```
Fix#72124.
`build_session` is passed an `EarlyErrorHandler` and then constructs a
`Handler`. But the `EarlyErrorHandler` is still used for some time after
that.
This commit changes `build_session` so it consumes the passed
`EarlyErrorHandler`, and also drops it as soon as the `Handler` is
built. As a result, `parse_cfg` and `parse_check_cfg` now take a
`Handler` instead of an `EarlyErrorHandler`.
Although, we would like to avoid crashes whenever
possible, and that's why I wanted to make this API fallible. It's
looking pretty hard to do proper validation.
I think many of our APIs will unfortunately depend on the user doing
the correct thing since at the MIR level we are working on,
we expect types to have been checked already.
Add `deeply_normalize_for_diagnostics`, use it in coherence
r? lcnr
Normalize trait refs used for coherence error reporting with `-Ztrait-solver=next-coherence`.
Two things:
1. I said before that we can't add this to `TyErrCtxt` because we compute `OverlapResult`s even if there are no diagnostics being emitted, e.g. for a reservation impl.
2. I didn't want to add this to an `InferCtxtExt` trait because I felt it was unnecessary. I don't particularly care about the API though.
Pretty print `Fn<(..., ...)>` trait refs with parentheses (almost) always
It's almost always better, at least in diagnostics, to print `Fn(i32, u32)` instead of `Fn<(i32, u32)>`.
Related to but doesn't fix#118225. That needs a separate fix.
Add support for making lib features internal
We have the notion of an "internal" lang feature: a feature that is never intended to be stabilized, and using which can cause ICEs and other issues without that being considered a bug.
This extends that idea to lib features as well. It is an alternative to https://github.com/rust-lang/rust/pull/115623: instead of using an attribute to declare lib features internal, we simply do this based on the name. Everything ending in `_internals` or `_internal` is considered internal.
Then we rename `core_intrinsics` to `core_intrinsics_internal`, which fixes https://github.com/rust-lang/rust/issues/115597.
Add support for `gen fn`
This builds on #116447 to add support for `gen fn` functions. For the most part we follow the same approach as desugaring `async fn`, but replacing `Future` with `Iterator` and `async {}` with `gen {}` for the body.
The version implemented here uses the return type of a `gen fn` as the yield type. For example:
```rust
gen fn count_to_three() -> i32 {
yield 1;
yield 2;
yield 3;
}
```
In the future, I think we should experiment with a syntax like `gen fn count_to_three() yield i32 { ... }`, but that can go in another PR.
cc `@oli-obk` `@compiler-errors`
rustc_symbol_mangling,rustc_interface,rustc_driver_impl: Enforce `rustc::potential_query_instability` lint
We currently allow the `rustc::potential_query_instability` lint in `rustc_symbol_mangling`, `rustc_interface` and `rustc_driver_impl`. Handle each instance of the lint in these crates and then begin to enforce the lint in these crates.
Part of #84447 which is **E-help-wanted**.
Remove the `precise_pointer_size_matching` feature gate
`usize` and `isize` are special for pattern matching because their range might depend on the platform. To make code portable across platforms, the following is never considered exhaustive:
```rust
let x: usize = ...;
match x {
0..=18446744073709551615 => {}
}
```
Because of how rust handles constants, this also unfortunately counts `0..=usize::MAX` as non-exhaustive. The [`precise_pointer_size_matching`](https://github.com/rust-lang/rust/issues/56354) feature gate was introduced both for this convenience and for the possibility that the lang team could decide to allow the above.
Since then, [half-open range patterns](https://github.com/rust-lang/rust/issues/67264) have been implemented, and since #116692 they correctly support `usize`/`isize`:
```rust
match 0usize { // exhaustive!
0..5 => {}
5.. => {}
}
```
I believe this subsumes all the use cases of the feature gate. Moreover no attempt has been made to stabilize it in the 5 years of its existence. I therefore propose we retire this feature gate.
Closes https://github.com/rust-lang/rust/issues/56354
Tweak unclosed generics errors
Remove unnecessary span label for parse errors that already have a suggestion.
Provide structured suggestion to close generics in more cases.
Change prefetch to avoid deadlock
Was abled to reproduce the deadlock in #118205 and created a coredump when it happen. When looking at the backtraces I noticed that the prefetch of exported_symbols (Thread 17 frame 4) started after the "actual" exported_symbols (Thread 2 frame 18) but it also is working on some of the collect_crate_mono_items (Thread 17 frame12 ) that Thread 2 is blocked on resulting in a deadlock.
This PR results in less parallell work that can be done at the same time but from what I can find we do not call the query exported_symbols from multiple places in the same join call any more.
```
Thread 17 (Thread 0x7f87b6299700 (LWP 11370)):
#0 syscall () at ../sysdeps/unix/sysv/linux/x86_64/syscall.S:38
#1 0x00007f87be5166a9 in <parking_lot::condvar::Condvar>::wait_until_internal () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#2 0x00007f87be12d854 in <rustc_query_system::query::job::QueryLatch>::wait_on () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#3 0x00007f87bd27d16f in rustc_query_system::query::plumbing::try_execute_query::<rustc_query_impl::DynamicConfig<rustc_query_system::query::caches::VecCache<rustc_span::def_id::CrateNum, rustc_middle::query::erase::Erased<[u8; 16]>>, false, false, false>, rustc_query_impl::plumbing::QueryCtxt, false> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#4 0x00007f87bd0b5b6a in rustc_query_impl::query_impl::exported_symbols::get_query_non_incr::__rust_end_short_backtrace () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#5 0x00007f87bdaebb0a in rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}::{closure#1} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#6 0x00007f87bdae1509 in rayon_core::join::join_context::call_b::<core::option::Option<rustc_data_structures::marker::FromDyn<&[(rustc_middle::middle::exported_symbols::ExportedSymbol, rustc_middle::middle::exported_symbols::SymbolExportInfo)]>>, rayon_core::join::join::call<core::option::Option<rustc_data_structures::marker::FromDyn<&[(rustc_middle::middle::exported_symbols::ExportedSymbol, rustc_middle::middle::exported_symbols::SymbolExportInfo)]>>, rustc_data_structures::sync::parallel::enabled::join<rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}::{closure#1}, (), &[(rustc_middle::middle::exported_symbols::ExportedSymbol, rustc_middle::middle::exported_symbols::SymbolExportInfo)]>::{closure#0}::{closure#1}>::{closure#0}>::{closure#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#7 0x00007f87bdae32ff in <rayon_core::job::StackJob<rayon_core::latch::SpinLatch, rayon_core::join::join_context::call_b<core::option::Option<rustc_data_structures::marker::FromDyn<&[(rustc_middle::middle::exported_symbols::ExportedSymbol, rustc_middle::middle::exported_symbols::SymbolExportInfo)]>>, rayon_core::join::join::call<core::option::Option<rustc_data_structures::marker::FromDyn<&[(rustc_middle::middle::exported_symbols::ExportedSymbol, rustc_middle::middle::exported_symbols::SymbolExportInfo)]>>, rustc_data_structures::sync::parallel::enabled::join<rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}::{closure#1}, (), &[(rustc_middle::middle::exported_symbols::ExportedSymbol, rustc_middle::middle::exported_symbols::SymbolExportInfo)]>::{closure#0}::{closure#1}>::{closure#0}>::{closure#0}, core::option::Option<rustc_data_structures::marker::FromDyn<&[(rustc_middle::middle::exported_symbols::ExportedSymbol, rustc_middle::middle::exported_symbols::SymbolExportInfo)]>>> as rayon_core::job::Job>::execute () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#8 0x00007f87b8338823 in <rayon_core::registry::WorkerThread>::wait_until_cold () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#9 0x00007f87bc2edbaf in rayon_core::join::join_context::<rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#0}, rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#1}, (), ()>::{closure#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#10 0x00007f87bc2ed313 in rayon_core::registry::in_worker::<rayon_core::join::join_context<rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#0}, rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#1}, (), ()>::{closure#0}, ((), ())> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#11 0x00007f87bc2db2a4 in rayon::iter::plumbing::bridge_producer_consumer::helper::<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#12 0x00007f87bc2eead2 in <rayon_core::job::StackJob<rayon_core::latch::SpinLatch, rayon_core::join::join_context::call_b<(), rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#1}>::{closure#0}, ()> as rayon_core::job::Job>::execute () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#13 0x00007f87b8338823 in <rayon_core::registry::WorkerThread>::wait_until_cold () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#14 0x00007f87be52d1f9 in <rayon_core::registry::ThreadBuilder>::run () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#15 0x00007f87b8461c57 in <scoped_tls::ScopedKey<rustc_span::SessionGlobals>>::set::<rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#0}::{closure#0}, ()> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#16 0x00007f87b846e465 in rustc_span::set_session_globals_then::<(), rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#0}::{closure#0}> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#17 0x00007f87b844f282 in <<crossbeam_utils:🧵:ScopedThreadBuilder>::spawn<<rayon_core::ThreadPoolBuilder>::build_scoped<rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#0}, rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#1}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}::{closure#0}::{closure#0}, ()>::{closure#0} as core::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#18 0x00007f87b846af58 in <<std:🧵:Builder>::spawn_unchecked_<alloc::boxed::Box<dyn core::ops::function::FnOnce<(), Output = ()> + core::marker::Send>, ()>::{closure#1} as core::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#19 0x00007f87b7898e85 in std::sys::unix:🧵:Thread:🆕:thread_start () from /home/andjo403/.rustup/toolchains/stage1/lib/libstd-d570b0650d35d951.so
#20 0x00007f87b7615609 in start_thread (arg=<optimized out>) at pthread_create.c:477
#21 0x00007f87b7755133 in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
Thread 2 (Thread 0x7f87b729b700 (LWP 11368)):
#0 syscall () at ../sysdeps/unix/sysv/linux/x86_64/syscall.S:38
#1 0x00007f87b7887b51 in std::sys::unix::locks::futex_condvar::Condvar::wait () from /home/andjo403/.rustup/toolchains/stage1/lib/libstd-d570b0650d35d951.so
#2 0x00007f87b8339478 in <rayon_core::sleep::Sleep>::sleep () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#3 0x00007f87b83387c3 in <rayon_core::registry::WorkerThread>::wait_until_cold () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#4 0x00007f87bc2edbaf in rayon_core::join::join_context::<rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#0}, rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#1}, (), ()>::{closure#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#5 0x00007f87bc2ed313 in rayon_core::registry::in_worker::<rayon_core::join::join_context<rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#0}, rayon::iter::plumbing::bridge_producer_consumer::helper<rayon::vec::DrainProducer<rustc_middle::mir::mono::MonoItem>, rayon::iter::for_each::ForEachConsumer<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}>>::{closure#1}, (), ()>::{closure#0}, ((), ())> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#6 0x00007f87bc2db50c in <rayon::vec::IntoIter<rustc_middle::mir::mono::MonoItem> as rayon::iter::ParallelIterator>::for_each::<rustc_data_structures::sync::parallel::enabled::par_for_each_in<rustc_middle::mir::mono::MonoItem, alloc::vec::Vec<rustc_middle::mir::mono::MonoItem>, rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}::{closure#0}>::{closure#0}::{closure#0}> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#7 0x00007f87bc2e8cd7 in <rustc_session::session::Session>::time::<(), rustc_monomorphize::collector::collect_crate_mono_items::{closure#1}> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#8 0x00007f87bc2b8f2c in rustc_monomorphize::collector::collect_crate_mono_items () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#9 0x00007f87bc2c30d9 in rustc_monomorphize::partitioning::collect_and_partition_mono_items () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#10 0x00007f87bcf2cde6 in rustc_query_impl::plumbing::__rust_begin_short_backtrace::<rustc_query_impl::query_impl::collect_and_partition_mono_items::dynamic_query::{closure#2}::{closure#0}, rustc_middle::query::erase::Erased<[u8; 24]>> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#11 0x00007f87bd156a3c in <rustc_query_impl::query_impl::collect_and_partition_mono_items::dynamic_query::{closure#2} as core::ops::function::FnOnce<(rustc_middle::ty::context::TyCtxt, ())>>::call_once () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#12 0x00007f87bd1c6a7d in rustc_query_system::query::plumbing::try_execute_query::<rustc_query_impl::DynamicConfig<rustc_query_system::query::caches::SingleCache<rustc_middle::query::erase::Erased<[u8; 24]>>, false, false, false>, rustc_query_impl::plumbing::QueryCtxt, false> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#13 0x00007f87bd15df40 in rustc_query_impl::query_impl::collect_and_partition_mono_items::get_query_non_incr::__rust_end_short_backtrace () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#14 0x00007f87bd7a0ad9 in rustc_codegen_ssa:🔙:symbol_export::exported_symbols_provider_local () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#15 0x00007f87bcf29acb in rustc_query_impl::plumbing::__rust_begin_short_backtrace::<rustc_query_impl::query_impl::exported_symbols::dynamic_query::{closure#2}::{closure#0}, rustc_middle::query::erase::Erased<[u8; 16]>> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#16 0x00007f87bcfdb350 in <rustc_query_impl::query_impl::exported_symbols::dynamic_query::{closure#2} as core::ops::function::FnOnce<(rustc_middle::ty::context::TyCtxt, rustc_span::def_id::CrateNum)>>::call_once () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#17 0x00007f87bd27d64f in rustc_query_system::query::plumbing::try_execute_query::<rustc_query_impl::DynamicConfig<rustc_query_system::query::caches::VecCache<rustc_span::def_id::CrateNum, rustc_middle::query::erase::Erased<[u8; 16]>>, false, false, false>, rustc_query_impl::plumbing::QueryCtxt, false> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#18 0x00007f87bd0b5b6a in rustc_query_impl::query_impl::exported_symbols::get_query_non_incr::__rust_end_short_backtrace () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#19 0x00007f87bda927ce in rustc_middle::query::plumbing::query_get_at::<rustc_query_system::query::caches::VecCache<rustc_span::def_id::CrateNum, rustc_middle::query::erase::Erased<[u8; 16]>>> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#20 0x00007f87bda9c93f in <rustc_metadata::rmeta::encoder::EncodeContext>::encode_crate_root () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#21 0x00007f87bdaa6ef7 in rustc_metadata::rmeta::encoder::encode_metadata_impl () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#22 0x00007f87bdae0b77 in rayon_core::join::join_context::<rayon_core::join::join::call<core::option::Option<rustc_data_structures::marker::FromDyn<()>>, rustc_data_structures::sync::parallel::enabled::join<rustc_metadata::rmeta::encoder::encode_metadata::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}, (), ()>::{closure#0}::{closure#0}>::{closure#0}, rayon_core::join::join::call<core::option::Option<rustc_data_structures::marker::FromDyn<()>>, rustc_data_structures::sync::parallel::enabled::join<rustc_metadata::rmeta::encoder::encode_metadata::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}, (), ()>::{closure#0}::{closure#1}>::{closure#0}, core::option::Option<rustc_data_structures::marker::FromDyn<()>>, core::option::Option<rustc_data_structures::marker::FromDyn<()>>>::{closure#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#23 0x00007f87bdaded2f in rayon_core::registry::in_worker::<rayon_core::join::join_context<rayon_core::join::join::call<core::option::Option<rustc_data_structures::marker::FromDyn<()>>, rustc_data_structures::sync::parallel::enabled::join<rustc_metadata::rmeta::encoder::encode_metadata::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}, (), ()>::{closure#0}::{closure#0}>::{closure#0}, rayon_core::join::join::call<core::option::Option<rustc_data_structures::marker::FromDyn<()>>, rustc_data_structures::sync::parallel::enabled::join<rustc_metadata::rmeta::encoder::encode_metadata::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}, (), ()>::{closure#0}::{closure#1}>::{closure#0}, core::option::Option<rustc_data_structures::marker::FromDyn<()>>, core::option::Option<rustc_data_structures::marker::FromDyn<()>>>::{closure#0}, (core::option::Option<rustc_data_structures::marker::FromDyn<()>>, core::option::Option<rustc_data_structures::marker::FromDyn<()>>)> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#24 0x00007f87bdaa5a03 in rustc_metadata::rmeta::encoder::encode_metadata () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#25 0x00007f87bdaed628 in rustc_metadata::fs::encode_and_write_metadata () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#26 0x00007f87b86608be in rustc_interface::passes::start_codegen () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#27 0x00007f87b8664946 in <rustc_middle::ty::context::GlobalCtxt>::enter::<<rustc_interface::queries::Queries>::codegen_and_build_linker::{closure#0}, core::result::Result<rustc_interface::queries::Linker, rustc_span::ErrorGuaranteed>> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#28 0x00007f87b864db00 in <rustc_interface::queries::Queries>::codegen_and_build_linker () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#29 0x00007f87b849400f in <rustc_interface::interface::Compiler>::enter::<rustc_driver_impl::run_compiler::{closure#0}::{closure#0}, core::result::Result<core::option::Option<rustc_interface::queries::Linker>, rustc_span::ErrorGuaranteed>> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#30 0x00007f87b846e067 in rustc_span::set_source_map::<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}::{closure#0}> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#31 0x00007f87b844dc13 in <rayon_core::thread_pool::ThreadPool>::install::<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#32 0x00007f87b84509a1 in <rayon_core::job::StackJob<rayon_core::latch::LatchRef<rayon_core::latch::LockLatch>, <rayon_core::registry::Registry>::in_worker_cold<<rayon_core::thread_pool::ThreadPool>::install<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>> as rayon_core::job::Job>::execute () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#33 0x00007f87b8338823 in <rayon_core::registry::WorkerThread>::wait_until_cold () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#34 0x00007f87be52d1f9 in <rayon_core::registry::ThreadBuilder>::run () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#35 0x00007f87b8461c57 in <scoped_tls::ScopedKey<rustc_span::SessionGlobals>>::set::<rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#0}::{closure#0}, ()> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#36 0x00007f87b846e465 in rustc_span::set_session_globals_then::<(), rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#0}::{closure#0}> () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#37 0x00007f87b844f282 in <<crossbeam_utils:🧵:ScopedThreadBuilder>::spawn<<rayon_core::ThreadPoolBuilder>::build_scoped<rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#0}, rustc_interface::util::run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#0}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#3}::{closure#0}::{closure#1}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}::{closure#0}::{closure#0}, ()>::{closure#0} as core::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#38 0x00007f87b846af58 in <<std:🧵:Builder>::spawn_unchecked_<alloc::boxed::Box<dyn core::ops::function::FnOnce<(), Output = ()> + core::marker::Send>, ()>::{closure#1} as core::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} () from /home/andjo403/.rustup/toolchains/stage1/lib/librustc_driver-70ddb84e8f7ce707.so
#39 0x00007f87b7898e85 in std::sys::unix:🧵:Thread:🆕:thread_start () from /home/andjo403/.rustup/toolchains/stage1/lib/libstd-d570b0650d35d951.so
#40 0x00007f87b7615609 in start_thread (arg=<optimized out>) at pthread_create.c:477
#41 0x00007f87b7755133 in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
```
fixes#118205fixes#117759 from the latest logs it is the same query map as in #118205fixes#118529fixes#117784
cc #118206
r? `@SparrowLii`
Tweak `.clone()` suggestion to work in more cases
When going through auto-deref, the `<T as Clone>` impl sometimes needs to be specified for rustc to actually clone the value and not the reference.
```
error[E0507]: cannot move out of dereference of `S`
--> $DIR/needs-clone-through-deref.rs:15:18
|
LL | for _ in self.clone().into_iter() {}
| ^^^^^^^^^^^^ ----------- value moved due to this method call
| |
| move occurs because value has type `Vec<usize>`, which does not implement the `Copy` trait
|
note: `into_iter` takes ownership of the receiver `self`, which moves value
--> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL
help: you can `clone` the value and consume it, but this might not be your desired behavior
|
LL | for _ in <Vec<usize> as Clone>::clone(&self.clone()).into_iter() {}
| ++++++++++++++++++++++++++++++ +
```
When encountering a move error, look for implementations of `Clone` for the moved type. If there is one, check if all its obligations are met. If they are, we suggest cloning without caveats. If they aren't, we suggest cloning while mentioning the unmet obligations, potentially suggesting `#[derive(Clone)]` when appropriate.
```
error[E0507]: cannot move out of a shared reference
--> $DIR/suggest-clone-when-some-obligation-is-unmet.rs:20:28
|
LL | let mut copy: Vec<U> = map.clone().into_values().collect();
| ^^^^^^^^^^^ ------------- value moved due to this method call
| |
| move occurs because value has type `HashMap<T, U, Hash128_1>`, which does not implement the `Copy` trait
|
note: `HashMap::<K, V, S>::into_values` takes ownership of the receiver `self`, which moves value
--> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL
help: you could `clone` the value and consume it, if the `Hash128_1: Clone` trait bound could be satisfied
|
LL | let mut copy: Vec<U> = <HashMap<T, U, Hash128_1> as Clone>::clone(&map.clone()).into_values().collect();
| ++++++++++++++++++++++++++++++++++++++++++++ +
help: consider annotating `Hash128_1` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
LL | pub struct Hash128_1;
|
```
Fix#109429.
When encountering multiple mutable borrows, suggest cloning and adding
derive annotations as needed.
```
error[E0596]: cannot borrow `sm.x` as mutable, as it is behind a `&` reference
--> $DIR/accidentally-cloning-ref-borrow-error.rs:32:9
|
LL | foo(&mut sm.x);
| ^^^^^^^^^ `sm` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: `Str` doesn't implement `Clone`, so this call clones the reference `&Str`
--> $DIR/accidentally-cloning-ref-borrow-error.rs:31:21
|
LL | let mut sm = sr.clone();
| ^^^^^^^
help: consider annotating `Str` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
LL | struct Str {
|
help: consider specifying this binding's type
|
LL | let mut sm: &mut Str = sr.clone();
| ++++++++++
```
Fix#34629. Fix#76643. Fix#91532.
Instead of allowing `rustc::potential_query_instability` on the whole
crate we go over each lint and allow it individually if it is safe to
do. Turns out there were no instances of this lint in this crate.
Instead of allowing `rustc::potential_query_instability` on the whole
crate we go over each lint and allow it individually if it is safe to
do. Turns out all instances were safe to allow in this crate.
Instead of allowing `rustc::potential_query_instability` on the whole
crate we go over each lint and allow it individually if it is safe to
do. Turns out there were no instances of this lint in this crate.
Structured `use` suggestion on privacy error
When encoutering a privacy error on an item through a re-export that is accessible in an alternative path, provide a structured suggestion with that path.
```
error[E0603]: module import `mem` is private
--> $DIR/private-std-reexport-suggest-public.rs:4:14
|
LL | use foo::mem;
| ^^^ private module import
|
note: the module import `mem` is defined here...
--> $DIR/private-std-reexport-suggest-public.rs:8:9
|
LL | use std::mem;
| ^^^^^^^^
note: ...and refers to the module `mem` which is defined here
--> $SRC_DIR/std/src/lib.rs:LL:COL
|
= note: you could import this
help: import `mem` through the re-export
|
LL | use std::mem;
| ~~~~~~~~
```
Fix#42909.
Streamline MIR dataflow cursors
`rustc_mir_dataflow` has two kinds of results (`Results` and `ResultsCloned`) and three kinds of results cursor (`ResultsCursor`, `ResultsClonedCursor`, `ResultsRefCursor`). I found this quite confusing.
This PR removes `ResultsCloned`, `ResultsClonedCursor`, and `ResultsRefCursor`, leaving just `Results` and `ResultsCursor`. This makes the relevant code shorter and easier to read, and there is no performance penalty.
r? `@cjgillot`
When encoutering a privacy error on an item through a re-export that is
accessible in an alternative path, provide a structured suggestion with
that path.
```
error[E0603]: module import `mem` is private
--> $DIR/private-std-reexport-suggest-public.rs:4:14
|
LL | use foo::mem;
| ^^^ private module import
|
note: the module import `mem` is defined here...
--> $DIR/private-std-reexport-suggest-public.rs:8:9
|
LL | use std::mem;
| ^^^^^^^^
note: ...and refers to the module `mem` which is defined here
--> $SRC_DIR/std/src/lib.rs:LL:COL
|
= note: you could import this
help: import `mem` through the re-export
|
LL | use std::mem;
| ~~~~~~~~
```
Fix#42909.
When encountering multiple mutable borrows, suggest cloning and adding
derive annotations as needed.
```
error[E0596]: cannot borrow `sm.x` as mutable, as it is behind a `&` reference
--> $DIR/accidentally-cloning-ref-borrow-error.rs:32:9
|
LL | foo(&mut sm.x);
| ^^^^^^^^^ `sm` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: `Str` doesn't implement `Clone`, so this call clones the reference `&Str`
--> $DIR/accidentally-cloning-ref-borrow-error.rs:31:21
|
LL | let mut sm = sr.clone();
| ^^^^^^^
help: consider annotating `Str` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
LL | struct Str {
|
help: consider specifying this binding's type
|
LL | let mut sm: &mut Str = sr.clone();
| ++++++++++
```
```
error[E0596]: cannot borrow `*inner` as mutable, as it is behind a `&` reference
--> $DIR/issue-91206.rs:14:5
|
LL | inner.clear();
| ^^^^^ `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: you can `clone` the `Vec<usize>` value and consume it, but this might not be your desired behavior
--> $DIR/issue-91206.rs:11:17
|
LL | let inner = client.get_inner_ref();
| ^^^^^^^^^^^^^^^^^^^^^^
help: consider specifying this binding's type
|
LL | let inner: &mut Vec<usize> = client.get_inner_ref();
| +++++++++++++++++
```
When encountering a case where `let x: T = (val: &T).clone();` and
`T: !Clone`, already mention that the reference is being cloned. We now
also suggest `#[derive(Clone)]` not only on `T` but also on type
parameters to satisfy blanket implementations.
```
error[E0308]: mismatched types
--> $DIR/assignment-of-clone-call-on-ref-due-to-missing-bound.rs:17:39
|
LL | let mut x: HashSet<Day> = v.clone();
| ------------ ^^^^^^^^^ expected `HashSet<Day>`, found `&HashSet<Day>`
| |
| expected due to this
|
= note: expected struct `HashSet<Day>`
found reference `&HashSet<Day>`
note: `HashSet<Day>` does not implement `Clone`, so `&HashSet<Day>` was cloned instead
--> $DIR/assignment-of-clone-call-on-ref-due-to-missing-bound.rs:17:39
|
LL | let mut x: HashSet<Day> = v.clone();
| ^
= help: `Clone` is not implemented because the trait bound `Day: Clone` is not satisfied
help: consider annotating `Day` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
LL | enum Day {
|
```
Case taken from # #41825.
When encountering a move error, look for implementations of `Clone` for
the moved type. If there is one, check if all its obligations are met.
If they are, we suggest cloning without caveats. If they aren't, we
suggest cloning while mentioning the unmet obligations, potentially
suggesting `#[derive(Clone)]` when appropriate.
```
error[E0507]: cannot move out of a shared reference
--> $DIR/suggest-clone-when-some-obligation-is-unmet.rs:20:28
|
LL | let mut copy: Vec<U> = map.clone().into_values().collect();
| ^^^^^^^^^^^ ------------- value moved due to this method call
| |
| move occurs because value has type `HashMap<T, U, Hash128_1>`, which does not implement the `Copy` trait
|
note: `HashMap::<K, V, S>::into_values` takes ownership of the receiver `self`, which moves value
--> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL
help: you could `clone` the value and consume it, if the `Hash128_1: Clone` trait bound could be satisfied
|
LL | let mut copy: Vec<U> = <HashMap<T, U, Hash128_1> as Clone>::clone(&map.clone()).into_values().collect();
| ++++++++++++++++++++++++++++++++++++++++++++ +
help: consider annotating `Hash128_1` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
LL | pub struct Hash128_1;
|
```
Fix#109429.
When going through auto-deref, the `<T as Clone>` impl sometimes needs
to be specified for rustc to actually clone the value and not the
reference.
```
error[E0507]: cannot move out of dereference of `S`
--> $DIR/needs-clone-through-deref.rs:15:18
|
LL | for _ in self.clone().into_iter() {}
| ^^^^^^^^^^^^ ----------- value moved due to this method call
| |
| move occurs because value has type `Vec<usize>`, which does not implement the `Copy` trait
|
note: `into_iter` takes ownership of the receiver `self`, which moves value
--> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL
help: you can `clone` the value and consume it, but this might not be your desired behavior
|
LL | for _ in <Vec<usize> as Clone>::clone(&self.clone()).into_iter() {}
| ++++++++++++++++++++++++++++++ +
```
CC #109429.
rustc: Harmonize `DefKind` and `DefPathData`
Follow up to https://github.com/rust-lang/rust/pull/118188.
`DefPathData::(ClosureExpr,ImplTrait)` are renamed to match `DefKind::(Closure,OpaqueTy)`.
`DefPathData::ImplTraitAssocTy` is replaced with `DefPathData::TypeNS(kw::Empty)` because both correspond to `DefKind::AssocTy`.
It's possible that introducing `(DefKind,DefPathData)::AssocOpaqueTy` instead could be a better solution, but that would be a much more invasive change.
Const generic parameters introduced for effects are moved from `DefPathData::TypeNS` to `DefPathData::ValueNS`, because constants are values.
`DefPathData` is no longer passed to `create_def` functions to avoid redundancy.
more targeted errors when extern types end up in places they should not
Cc https://github.com/rust-lang/rust/issues/115709 -- this does not fix that bug but it makes the panics less obscure and makes it more clear that this is a deeper issue than just a little codegen oversight. (In https://github.com/rust-lang/rust/pull/116115 we decided we'd stick to causing ICEs here for now, rather than nicer errors. We can't currently show any errors pre-mono and probably we don't want post-mono checks when this gets stabilized anyway.)
Restrict what symbols can be used in `#[diagnostic::on_unimplemented]` format strings
This commit restricts what symbols can be used in a format string for any option of the `diagnostic::on_unimplemented` attribute. We previously allowed all the ad-hoc options supported by the internal `#[rustc_on_unimplemented]` attribute. For the stable attribute we only want to support generic parameter names and `{Self}` as parameters. For any other parameter an warning is emitted and the parameter is replaced by the literal parameter string, so for example `{integer}` turns into `{integer}`. This follows the general design of attributes in the `#[diagnostic]` attribute namespace, that any syntax "error" is treated as warning and subsequently ignored.
r? `@compiler-errors`
This commit restricts what symbols can be used in a format string for
any option of the `diagnostic::on_unimplemented` attribute. We
previously allowed all the ad-hoc options supported by the internal
`#[rustc_on_unimplemented]` attribute. For the stable attribute we only
want to support generic parameter names and `{Self}` as parameters. For
any other parameter an warning is emitted and the parameter is replaced
by the literal parameter string, so for example `{integer}` turns into
`{integer}`. This follows the general design of attributes in the
`#[diagnostic]` attribute namespace, that any syntax "error" is treated
as warning and subsequently ignored.
This is weird: `HandlerInner::emit` calls
`HandlerInner::emit_diagnostic`, but only after doing a
`treat-err-as-bug` check. Which is fine, *except* that there are
multiple others paths for an `Error` or `Fatal` diagnostic to be passed
to `HandlerInner::emit_diagnostic` without going through
`HandlerInner::emit`, e.g. `Handler::span_err` call
`Handler::emit_diag_at_span`, which calls `emit_diagnostic`.
So that suggests that the coverage for `treat-err-as-bug` is incomplete.
This commit removes `HandlerInner::emit` and moves the
`treat-err-as-bug` check to `HandlerInner::emit_diagnostic`, so it
cannot by bypassed.
`Handler` is a wrapper around `HanderInner`. Some functions on
on `Handler` just forward to the samed-named functions on
`HandlerInner`.
This commit removes as many of those as possible, implementing functions
on `Handler` where possible, to avoid the boilerplate required for
forwarding. The commit is moderately large but it's very mechanical.
These impls are all needed for just a single `IntoDiagnostic` type, not
a family of them.
Note that `ErrorGuaranteed` is the default type parameter for
`IntoDiagnostic`.
Exhaustiveness: allocate memory better
Exhaustiveness is a recursive algorithm that allocates a bunch of slices at every step. Let's see if I can improve performance by improving allocations.
Already just using `Vec::with_capacity` is showing impressive improvements on my local measurements.
r? `@ghost`
Currently, `Handler::fatal` returns `FatalError`. But `Session::fatal`
returns `!`, because it calls `Handler::fatal` and then calls `raise` on
the result. This inconsistency is unfortunate.
This commit changes `Handler::fatal` to do the `raise` itself, changing
its return type to `!`. This is safe because there are only two calls to
`Handler::fatal`, one in `rustc_session` and one in
`rustc_codegen_cranelift`, and they both call `raise` on the result.
`HandlerInner::fatal` still returns `FatalError`, so I renamed it
`fatal_no_raise` to emphasise the return type difference.
miri: support 'promising' alignment for symbolic alignment check
Then use that ability in `slice::align_to`, so that even with `-Zmiri-symbolic-alignment-check`, it no longer has to return spuriously empty "middle" parts.
Fixes https://github.com/rust-lang/miri/issues/3068
Rollup of 3 pull requests
Successful merges:
- #117869 ([rustdoc] Add highlighting for comments in items declaration)
- #118525 (coverage: Skip spans that can't be un-expanded back to the function body)
- #118574 (rustc_session: Address all `rustc::potential_query_instability` lints)
r? `@ghost`
`@rustbot` modify labels: rollup
rustc_session: Address all `rustc::potential_query_instability` lints
Instead of allowing `rustc::potential_query_instability` on the whole crate we go over each lint and allow it individually if it is safe to do. Turns out all instances were safe to allow in this crate.
Part of #84447 which is **E-help-wanted**.
coverage: Skip spans that can't be un-expanded back to the function body
When we extract coverage spans from MIR, we try to "un-expand" them back to spans that are inside the function's body span.
In cases where that doesn't succeed, the current code just swaps in the entire body span instead. But that tends to result in coverage spans that are completely unrelated to the control flow of the affected code, so it's better to just discard those spans.
---
Extracted from #118305, since this is a general improvement that isn't specific to branch coverage.
---
`@rustbot` label +A-code-coverage
Provide structured suggestion for type mismatch in loop
We currently provide only a `help` message, this PR introduces the last two structured suggestions instead:
```
error[E0308]: mismatched types
--> $DIR/issue-98982.rs:2:5
|
LL | fn foo() -> i32 {
| --- expected `i32` because of return type
LL | / for i in 0..0 {
LL | | return i;
LL | | }
| |_____^ expected `i32`, found `()`
|
note: the function expects a value to always be returned, but loops might run zero times
--> $DIR/issue-98982.rs:2:5
|
LL | for i in 0..0 {
| ^^^^^^^^^^^^^ this might have zero elements to iterate on
LL | return i;
| -------- if the loop doesn't execute, this value would never get returned
help: return a value for the case when the loop has zero elements to iterate on
|
LL ~ }
LL ~ /* `i32` value */
|
help: otherwise consider changing the return type to account for that possibility
|
LL ~ fn foo() -> Option<i32> {
LL | for i in 0..0 {
LL ~ return Some(i);
LL ~ }
LL ~ None
|
```
Fix#98982.
Report errors in jobserver inherited through environment variables
This pr attempts to catch situations, when jobserver exists, but is not being inherited.
r? `@petrochenkov`
Instead of allowing `rustc::potential_query_instability` on the whole
crate we go over each lint and allow it individually if it is safe to
do. Turns out all instances were safe to allow in this crate.
`DefPathData::(ClosureExpr,ImplTrait)` are renamed to match `DefKind::(Closure,OpaqueTy)`.
`DefPathData::ImplTraitAssocTy` is replaced with `DefPathData::TypeNS(kw::Empty)` because both correspond to `DefKind::AssocTy`.
It's possible that introducing `(DefKind,DefPathData)::AssocOpaqueTy` could be a better solution, but that would be a much more invasive change.
Const generic parameters introduced for effects are moved from `DefPathData::TypeNS` to `DefPathData::ValueNS`, because constants are values.
`DefPathData` is no longer passed to `create_def` functions to avoid redundancy.
Because a macro invocation can expand to a never pattern, we can't rule
out a `arm!(),` arm at parse time. Instead we detect that case at
expansion time, if the macro tries to output a pattern followed by `=>`.
When we extract coverage spans from MIR, we try to "un-expand" them back to
spans that are inside the function's body span.
In cases where that doesn't succeed, the current code just swaps in the entire
body span instead. But that tends to result in coverage spans that are
completely unrelated to the control flow of the affected code, so it's better
to just discard those spans.
Add more information to StableMIR Instance
Allow stable MIR users to retrieve an instance function signature, the index for a VTable instance and more information about its underlying definition.
These are needed to properly interpret function calls, either via VTable or direct calls. The `CrateDef` implementation will also allow users to emit diagnostic messages.
I also fixed a few issues that we had identified before with how we were retrieving body of things that may not have a body available.
Handle recursion limit for subtype and well-formed predicates
Adds a recursion limit check for subtype predicates and well-formed predicates.
`-Ztrait-solver=next` currently panics with unimplemented for these cases.
These cases are arguably bugs in the occurs check but:
- I could not find a simple way to fix the occurs check
- There should still be a recursion limit check to prevent hangs anyway.
closes#117151
r? types
Centralize live loans maintenance to fix scope differences due to liveness
As found in the recent [polonius crater run](https://github.com/rust-lang/rust/pull/117593#issuecomment-1801398892), NLLs and the location-insensitive polonius computed different scopes on some specific CFG shapes, e.g. the following.
![image](https://github.com/rust-lang/rust/assets/247183/c3649f5e-3058-454e-854e-1a6b336bdd5e)
I had missed that liveness data was pushed from different sources than just the liveness computation: there are a few places that do this -- and some of them may be unneeded or at the very least untested, as no tests changed when I tried removing some of them.
Here, `_6` is e.g. dead on entry to `bb2[0]` during `liveness::trace`, but its regions will be marked as live later during "constraint generation" (which I plan to refactor away and put in the liveness module soon). This should cause the inflowing loans to be marked live, but they were only computed in `liveness::trace`.
Therefore, this PR moves live loan maintenance to `LivenessValues`, so that the various places pushing liveness data will all also update live loans at the same time -- except for promoteds which I don't believe need them, and their liveness handling is already interesting/peculiar.
All the regressions I saw in the initial crater run were related to this kind of shapes, and this change did fix all of them on the [next run](https://github.com/rust-lang/rust/pull/117593#issuecomment-1826132145).
r? `@matthewjasper`
(This will conflict with #117880 but whichever lands first is fine by me, the end goal is the same for both)