self-profiler: record spans for proc-macro expansions
This PR is a follow-up to #95473, using the arg recorder feature from #95689:
- it adds support code to easily record spans in the event's arguments, when using `generic_activity_with_arg_recorder`.
- uses that to record the spans where proc-macro expansions happen in addition to their name.
As for the other 2 PRs, the goal here is to provide visibility into proc-macro expansion performance, so that users can diagnose which uses of proc-macros in their code could be causing compile time issues.
Some areas where I'd love feedback:
- [x] the API and names: the `SpannedEventArgRecorder` trait and its method, much like #95689 had the same question about the `EventArgRecorder` naming
- [x] we don't currently have a way to record the names of the event arguments, so should `record_arg_spanned` record the span as "location: {}" or similar ?
Make the lifetime accurate which is used in the region constraints part
This PR fixes the FIXME about lifetime using in the region constraints part.
We cannot write `<'graph, 'tcx, D>` because the definition of `Successors<'0, '1, D>` requires `'1 : '0`.
We cannot add bound to `'graph` either because `'graph` is required to be an arbitrary value in the definition of `WithSuccessors`
So the most accurate way is to use `<'s, 'tcx, D>`.
cc `@Aaron1011` who added this FIXME in #85343
The self-profiler's `EventArgRecorder` is general-purpose in its ability to record Strings (and `rustc_span` depends on the crate its defined in, `rustc_data_structure`).
Some generic activities could use recording locations where they happen in the user's code: to allow e.g. to track macro expansions and diagnose performance issues there.
This adds a `SpannedEventArgRecorder` that can record an argument given as a span, rather than a String, since turning spans into Strings can be tricky if you're not happy with its default Debug output. This way the recorder can have a `record_arg_spanned` method which will do that.
Make all thir types implement clone
This PR adds `Clone` impl to all of the `Thir<'tcx>` types.
I would like to be able to clone a `Thir` body so that I can make a copy in my rustc driver without breaking further compilation. Without this my driver is forced to run in the `after_expansion` callback and thus doesn't benefit from running all the safety checks that `rustc` usually does, instead i need to do them all myself.
errors: minor translation-related changes
- For one error in typeck, specifying "suggestion" as the attribute for the only suggestion is unnecessary, it's the default of the derive.
- The documentation comment for the `SessionDiagnostic` derive is out-of-date, it should have been updated in #95512.
r? `@oli-obk`
Only output DepKind in dump-dep-graph.
When printing the whole DepNode, the output file is simply too massive to
be actually useful for profiling.
This trimmed down version mixes a lot of information together, but it also
allows to ask questions such that "why does this query ever access HIR?".
bootstrap: add split-debuginfo config
Replace `run-dysutil` option with more general `split-debuginfo` option that works on all platforms.
r? `@Mark-Simulacrum`
This lets us clone just the parts within a `TokenTree` that need
cloning, rather than the entire thing. This is a surprisingly large
performance win, up to 4% on `async-std-1.10.0`.
Specifying "suggestion" as the attribute for the only suggestion is
unnecessary, it's the default of the derive.
Signed-off-by: David Wood <david.wood@huawei.com>
This makes `CloseDelim` handling more like `OpenDelim` handling, which
produces `OpenDelim` and pushes the stack at the same time. It requires
some adjustment to `parse_token_tree` now that we don't remain within
the frame after getting the `CloseDelim`.
Add an explicit `Span` field to `OutlivesConstraint`
Previously, we would retrieve the span from the `Body` using
the `locations` field. However, we may end up changing the
`locations` field when moving a constraint from a promoted
to a different body.
We now store the original `Span` in a dedication field, so that
changes to the `locations` do not affect the quality of our
diagnostics.
Check if call return type is visibly uninhabited when building MIR
The main motivation behind the change is to expose information about diverging
calls to the generator transform and match the precision of drop range tracking
which already understands that call expressions with visibly uninhabited types
diverges.
This change should also accept strictly more programs than before. That is
programs that were previously rejected due to errors raised by control-flow
sensitive checks in a code that is no longer considered reachable.
Fixes#93161.
A Google search of the error message fails to return any relevant
resuts, suggesting this has never occurred in practice. And removeing it
reduces instruction counts by up to 2% on some benchmarks.
Previously, we would retrieve the span from the `Body` using
the `locations` field. However, we may end up changing the
`locations` field when moving a constraint from a promoted
to a different body.
We now store the original `Span` in a dedication field, so that
changes to the `locations` do not affect the quality of our
diagnostics.
The loop is there to handle a `NoDelim` open/close token. This commit
changes `TokenCursor::inlined_next` so it never returns such a token.
This is a performance win because the conditional test in `bump()` is
removed.
If the parser needs changing in the future to handle `NoDelim` tokens,
then `inlined_next()` can easily be changed to return them.
The `DelimToken` here is `NoDelim`, which means the returned delim
tokens will just be ignored by `Parser::bump()`. This commit changes
things so the delim tokens won't be returned.
Miri provenance cleanup
Reviewing https://github.com/rust-lang/rust/pull/95826 by ``@carbotaniuman`` made me realize that we could clean things up a little here.
``@carbotaniuman`` please let me know if you're okay with landing this (it will create a lot of conflicts with your PR), or if you'd prefer incorporating the ideas from this PR into yours. I think we want to end up in a situation where the function you called `ptr_reify_alloc` returns just two things, a concrete tag and an offset. Getting an `AllocId` from a concrete tag should be infallible like now. However a concrete tag and `Tag` don't have to be the same type.
r? ``@oli-obk``
interpret: Fix writing uninit to an allocation
When calling `mark_init`, we need to also be mindful of what happens with the relocations! Specifically, when we de-init memory, we need to clear relocations in that range as well or else strange things will happen (and printing will not show the de-init, since relocations take precedence there).
Fixes https://github.com/rust-lang/miri/issues/2068.
Here's the Miri testcase that this fixes (requires `-Zmiri-disable-validation`):
```rust
use std::mem::MaybeUninit;
fn main() { unsafe {
let mut x = MaybeUninit::<i64>::uninit();
// Put in a ptr.
x.as_mut_ptr().cast::<&i32>().write_unaligned(&0);
// Overwrite parts of that pointer with 'uninit' through a Scalar.
let ptr = x.as_mut_ptr().cast::<i32>();
*ptr = MaybeUninit::uninit().assume_init();
// Reading this back should hence work fine.
let _c = *ptr;
} }
```
Previously this failed with
```
error: unsupported operation: unable to turn pointer into raw bytes
--> ../miri/uninit.rs:11:14
|
11 | let _c = *ptr;
| ^^^^ unable to turn pointer into raw bytes
|
= help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support
= note: inside `main` at ../miri/uninit.rs:11:14
```
Refactor loop into iterator; simplify negation logic.
is_dummy should return when a non-dummy is found, but instead is iterated until completion. With some inspiration from line 323 this was refactored to a single line that returns once a single counterexample is found.
asm: Add a kreg0 register class on x86 which includes k0
Previously we only exposed a kreg register class which excludes the k0
register since it can't be used in many instructions. However k0 is a
valid register and we need to have a way of marking it as clobbered for
clobber_abi.
Fixes#94977
Previously we only exposed a kreg register class which excludes the k0
register since it can't be used in many instructions. However k0 is a
valid register and we need to have a way of marking it as clobbered for
clobber_abi.
Fixes#94977
Rollup of 6 pull requests
Successful merges:
- #94493 (Improved diagnostic on failure to meet send bound on future in a foreign crate)
- #95809 (Fix typo in bootstrap.py)
- #96086 (Remove `--extern-location` and all associated code)
- #96089 (`alloc`: make `vec!` unavailable under `no_global_oom_handling`)
- #96122 (Fix an invalid error for a suggestion to add a slice in pattern-matching)
- #96142 (Stop using CRATE_DEF_INDEX outside of metadata encoding.)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Stop using CRATE_DEF_INDEX outside of metadata encoding.
`CRATE_DEF_ID` and `CrateNum::as_def_id` are almost always what we want. We should not manipulate raw `DefIndex` outside of metadata encoding.
Remove `--extern-location` and all associated code
`--extern-location` was an experiment to investigate the best way to
generate useful diagnostics for unused dependency warnings by enabling a
build system to identify the corresponding build config.
While I did successfully use this, I've since been convinced the
alternative `--json unused-externs` mechanism is the way to go, and
there's no point in having two mechanisms with basically the same
functionality.
This effectively reverts https://github.com/rust-lang/rust/pull/72603
Improved diagnostic on failure to meet send bound on future in a foreign crate
Provide a better diagnostic on failure to meet send bound on futures in a foreign crate.
fixes#78543
This will facilitate the change in the next commit.
`boolean` arguments aren't great, but the function is only used in three
places within this one file.
In particular, avoid wrapping a token within `TokenTree::Token` and then
immediately matching it and returning the token within. Just return the
token immediately.
show suggestion to replace generic bounds with associated types in more cases
Moves the hint to replace generic parameters with associated type bounds from the "not all associated type bounds are specified"(`E0191`) to "to many generic type parameters provided"(`E0107`).
Since `E0191` is only emitted in places where all associated types must be specified (when creating `dyn` types), the suggesting is currently not shown for other generic type uses (such as in generic type bounds). With this change the suggesting is always emitted when the number of excess generic parameters matches the number of unbound associated types.
Main motivation for the change was a lack of useful suggesting when doing
```rust
fn foo<I: Iterator<usize>>(i: I) {}
```
Report undeclared lifetimes during late resolution.
First step in https://github.com/rust-lang/rust/pull/91557
We reuse the rib design of the current resolution framework. Specific `LifetimeRib` and `LifetimeRibKind` types are introduced. The most important variant is `LifetimeRibKind::Generics`, which happens each time we encounter something which may introduce generic lifetime parameters. It can be an item or a `for<...>` binder. The `LifetimeBinderKind` specifies how this rib behaves with respect to in-band lifetimes.
r? `@petrochenkov`
Remove last vestiges of skippng ident span hashing
This removes a comment that no longer applies, and properly hashes
the full ident for path segments.
Refactor HIR item-like traversal (part 1)
Issue #95004
- Create hir_crate_items query which traverses tcx.hir_crate(()).owners to return a hir::ModuleItems
- use tcx.hir_crate_items in tcx.hir().items() to return an iterator of hir::ItemId
- use tcx.hir_crate_items to introduce a tcx.hir().par_items(impl Fn(hir::ItemId)) to traverse all items in parallel;
Signed-off-by: Miguel Guarniz <mi9uel9@gmail.com>
cc `@cjgillot`
Strict provenance lint diagnostics improvements
Use `multipart_suggestion` instead of `span_suggestion` and getting a snippet for the expression. Also don't suggest unnecessary parenthesis in `lossy_provenance_casts`.
cc ``@estebank``
``@rustbot`` label A-diagnostics
rustc_metadata: Do not encode unnecessary module children
This should remove the syntax context shift and the special case for `ExternCrate` in decoder in https://github.com/rust-lang/rust/pull/95880.
This PR also shifts some work from decoding to encoding, which is typically useful for performance (but probably not much in this case).
r? `@cjgillot`
Include Refs in Valtree Creation
This adds references to `const_to_valtree`, which isn't used in the compiler yet, but after the previous changes we made to the thir and mir representations and this change we should be able to finally introduce them in the next PR.
I wasn't able to properly test this code, except indirectly by including a call of `const_to_valtree` in the code that currently creates constants (`turn_into_const_value`).
r? `@lcnr`
cc `@oli-obk` `@RalfJung`
Parse inner attributes on inline const block
According to https://github.com/rust-lang/rust/pull/84414#issuecomment-826150936, inner attributes are intended to be supported *"in all containers for statements (or some subset of statements)"*.
This PR adds inner attribute parsing and pretty-printing for inline const blocks (https://github.com/rust-lang/rust/issues/76001), which contain statements just like an unsafe block or a loop body.
```rust
let _ = const {
#![allow(...)]
let x = ();
x
};
```
resolve: Create dummy bindings for all unresolved imports
Apparently such bindings weren't previously created for all unresolved imports, causing issues like https://github.com/rust-lang/rust/issues/95879.
In this PR I'm trying to create such dummy bindings in a more centralized way by calling `import_dummy_binding` once for all imports in `finalize_imports`.
Fixes https://github.com/rust-lang/rust/issues/95879.
Allow self-profiler to only record potentially costly arguments when argument recording is turned on
As discussed [on zulip](https://rust-lang.zulipchat.com/#narrow/stream/247081-t-compiler.2Fperformance/topic/Identifying.20proc-macro.20slowdowns/near/277304909) with `@wesleywiser,` I'd like to record proc-macro expansions in the self-profiler, with some detailed data (per-expansion spans for example, to follow #95473).
At the same time, I'd also like to avoid doing expensive things when tracking a generic activity's arguments, if they were not specifically opted into the event filter mask, to allow the self-profiler to be used in hotter contexts.
This PR tries to offer:
- a way to ensure a closure to record arguments will only be called in that situation, so that potentially costly arguments can still be recorded when needed. With the additional requirement that, if possible, it would offer a way to record non-owned data without adding many `generic_activity_with_arg_{...}`-style methods. This lead to the `generic_activity_with_arg_recorder` single entry-point, and the closure parameter would offer the new methods, able to be executed in a context where costly argument could be created without disturbing the profiled piece of code.
- some facilities/patterns allowing to record more rustc specific data in this situation, without making `rustc_data_structures` where the self-profiler is defined, depend on other rustc crates (causing circular dependencies): in particular, spans. They are quite tricky to turn into strings (if the default `Debug` impl output does not match the context one needs them for), and since I'd also like to avoid the allocation there when arg recording is turned off today, that has turned into another flexibility requirement for the API in this PR (separating the span-specific recording into an extension trait). **edit**: I've removed this from the PR so that it's easier to review, and opened https://github.com/rust-lang/rust/pull/95739.
- allow for extensibility in the future: other ways to record arguments, or additional data attached to them could be added in the future (e.g. recording the argument's name as well as its data).
Some areas where I'd love feedback:
- the API and names: the `EventArgRecorder` and its method for example. As well as the verbosity that comes from the increased flexibility.
- if I should convert the existing `generic_activity_with_arg{s}` to just forward to `generic_activity_with_arg_recorder` + `recorder.record_arg` (or remove them altogether ? Probably not): I've used the new API in the simple case I could find of allocating for an arg that may not be recorded, and the rest don't seem costly.
- [x] whether this API should panic if no arguments were recorded by the user-provided closure (like this PR currently does: it seems like an error to use an API dedicated to record arguments but not call the methods to then do so) or if this should just record a generic activity without arguments ?
- whether the `record_arg` function should be `#[inline(always)]`, like the `generic_activity_*` functions ?
As mentioned, r? `@wesleywiser` following our recent discussion.
Adding diagnostic data on generators to the crate metadata and using it to provide
a better diagnostic on failure to meet send bound on futures originated from a foreign crate
Rollup of 9 pull requests
Successful merges:
- #93969 (Only add codegen backend to dep info if -Zbinary-dep-depinfo is used)
- #94605 (Add missing links in platform support docs)
- #95372 (make unaligned_references lint deny-by-default)
- #95859 (Improve diagnostics for unterminated nested block comment)
- #95961 (implement SIMD gather/scatter via vector getelementptr)
- #96004 (Consider lifetimes when comparing types for equality in MIR validator)
- #96050 (Remove some now-dead code that was only relevant before deaggregation.)
- #96070 ([test] Add test cases for untested functions for BTreeMap)
- #96099 (MaybeUninit array cleanup)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Better method call error messages
Rebase/continuation of #71827
~Based on #92360~
~Based on #93118~
There's a decent description in #71827 that I won't copy here (for now at least)
In addition to rebasing, I've tried to restore most of the original suggestions for invalid arguments. Unfortunately, this does make some of the errors a bit verbose. To fix this will require a bit of refactoring to some of the generalized error suggestion functions, and I just don't have the time to go into it right now.
I think this is in a state that the error messages are overall better than before without a reduction in the suggestions given.
~I've tried to split out some of the easier and self-contained changes into separate commits (mostly in #92360, but also one here). There might be more than can be done here, but again just lacking time.~
r? `@estebank` as the original reviewer of #71827
This attempts to bring better error messages to invalid method calls, by applying some heuristics to identify common mistakes.
The algorithm is inspired by Levenshtein distance and longest common sub-sequence. In essence, we treat the types of the function, and the types of the arguments you provided as two "words" and compute the edits to get from one to the other.
We then modify that algorithm to detect 4 cases:
- A function input is missing
- An extra argument was provided
- The type of an argument is straight up invalid
- Two arguments have been swapped
- A subset of the arguments have been shuffled
(We detect the last two as separate cases so that we can detect two swaps, instead of 4 parameters permuted.)
It helps to understand this argument by paying special attention to terminology: "inputs" refers to the inputs being *expected* by the function, and "arguments" refers to what has been provided at the call site.
The basic sketch of the algorithm is as follows:
- Construct a boolean grid, with a row for each argument, and a column for each input. The cell [i, j] is true if the i'th argument could satisfy the j'th input.
- If we find an argument that could satisfy no inputs, provided for an input that can't be satisfied by any other argument, we consider this an "invalid type".
- Extra arguments are those that can't satisfy any input, provided for an input that *could* be satisfied by another argument.
- Missing inputs are inputs that can't be satisfied by any argument, where the provided argument could satisfy another input
- Swapped / Permuted arguments are identified with a cycle detection algorithm.
As each issue is found, we remove the relevant inputs / arguments and check for more issues. If we find no issues, we match up any "valid" arguments, and start again.
Note that there's a lot of extra complexity:
- We try to stay efficient on the happy path, only computing the diagonal until we find a problem, and then filling in the rest of the matrix.
- Closure arguments are wrapped in a tuple and need to be unwrapped
- We need to resolve closure types after the rest, to allow the most specific type constraints
- We need to handle imported C functions that might be variadic in their inputs.
I tried to document a lot of this in comments in the code and keep the naming clear.
Remove some now-dead code that was only relevant before deaggregation.
The code was broken anyway, if the deaggregator is disabled, it would have ICEd on any non-enum Adt
r? ```@RalfJung```
implement SIMD gather/scatter via vector getelementptr
Fixes https://github.com/rust-lang/portable-simd/issues/271
However, I don't *really* know what I am doing here... Cc ``@workingjubilee`` ``@calebzulawski``
I didn't do anything for cranelift -- ``@bjorn3`` not sure if it's okay for that backend to temporarily break. I'm happy to cherry-pick a patch that adds cranelift support. :)
Improve diagnostics for unterminated nested block comment
close#95283
(This is my first time try to messing around with rust compiler and might get a lot of things wrong... 🙇 )
make unaligned_references lint deny-by-default
This lint has been warn-by-default for a year now (since https://github.com/rust-lang/rust/pull/82525), so I think it is time to crank it up a bit. Code that triggers the lint causes UB (without `unsafe`) when executed, so we really don't want people to write code like this.
Only add codegen backend to dep info if -Zbinary-dep-depinfo is used
I am currently migrating the cg_clif build system from using a binary linked to the codegen backend as rustc replacement to passing `-Zcodegen-backend` instead. Without this PR this would force cargo to rebuild the sysroot on any change to the codegen backend even if I explicitly specify that I want it to be preserved, which would make development of cg_clif a lot slower. If you still want to have changes to the codegen backend invalidate the cargo build cache you can explicitly specify `-Zbinary-dep-depinfo`.
cc ``@eddyb`` as the codegen backend was initially added to the depinfo for rust-gpu.
Implement sym operands for global_asm!
Tracking issue: #93333
This PR is pretty much a complete rewrite of `sym` operand support for inline assembly so that the same implementation can be shared by `asm!` and `global_asm!`. The main changes are:
- At the AST level, `sym` is represented as a special `InlineAsmSym` AST node containing a path instead of an `Expr`.
- At the HIR level, `sym` is split into `SymStatic` and `SymFn` depending on whether the path resolves to a static during AST lowering (defaults to `SynFn` if `get_early_res` fails).
- `SymFn` is just an `AnonConst`. It runs through typeck and we just collect the resulting type at the end. An error is emitted if the type is not a `FnDef`.
- `SymStatic` directly holds a path and the `DefId` of the `static` that it is pointing to.
- The representation at the MIR level is mostly unchanged. There is a minor change to THIR where `SymFn` is a constant instead of an expression.
- At the codegen level we need to apply the target's symbol mangling to the result of `tcx.symbol_name()` depending on the target. This is done by calling the LLVM name mangler, which handles all of the details.
- On Mach-O, all symbols have a leading underscore.
- On x86 Windows, different mangling is used for cdecl, stdcall, fastcall and vectorcall.
- No mangling is needed on other platforms.
r? `@nagisa`
cc `@eddyb`
only downgrade selection Error -> Ambiguous if type error is in predicate
That is, we don't care if there's a TypeError type in the ParamEnv.
Fixes#95408
remove find_use_placement
A more robust solution to finding where to place use suggestions was added in #94584.
The algorithm uses the AST to find the span for the suggestion so we pass this span
down to the HIR during lowering and use it instead of calling `find_use_placement`
Fixes#94941
Check var scope if it exist
Fixes#92893.
Added helper function to check the scope of a variable, if it doesn't have a scope call delay_span_bug, which avoids us trying to get a block/scope that doesn't exist.
Had to increase `ROOT_ENTRY_LIMIT` was getting tidy error
Create (unstable) 2024 edition
[On Zulip](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Deprecating.20macro.20scoping.20shenanigans/near/272860652), there was a small aside regarding creating the 2024 edition now as opposed to later. There was a reasonable amount of support and no stated opposition.
This change creates the 2024 edition in the compiler and creates a prelude for the 2024 edition. There is no current difference between the 2021 and 2024 editions. Cargo and other tools will need to be updated separately, as it's not in the same repository. This change permits the vast majority of work towards the next edition to proceed _now_ instead of waiting until 2024.
For sanity purposes, I've merged the "hello" UI tests into a single file with multiple revisions. Otherwise we'd end up with a file per edition, despite them being essentially identical.
````@rustbot```` label +T-lang +S-waiting-on-review
Not sure on the relevant team, to be honest.
Stabilize `derive_default_enum`
This stabilizes `#![feature(derive_default_enum)]`, as proposed in [RFC 3107](https://github.com/rust-lang/rfcs/pull/3107) and tracked in #87517. In short, it permits you to `#[derive(Default)]` on `enum`s, indicating what the default should be by placing a `#[default]` attribute on the desired variant (which must be a unit variant in the interest of forward compatibility).
```````@rustbot``````` label +S-waiting-on-review +T-lang
`--extern-location` was an experiment to investigate the best way to
generate useful diagnostics for unused dependency warnings by enabling a
build system to identify the corresponding build config.
While I did successfully use this, I've since been convinced the
alternative `--json unused-externs` mechanism is the way to go, and
there's no point in having two mechanisms with basically the same
functionality.
This effectively reverts https://github.com/rust-lang/rust/pull/72603
when checking pointee metadata, canonicalize the `Sized` check
Use `infcx.predicate_must_hold_modulo_regions` with a `Sized` obligation instead of just calling `ty.is_sized`, because the latter does not canonicalize region and type vars (and in the test case I added in this PR, there's a region var in the `ParamEnv`).
Fixes#95311
Remove `<mbe::TokenTree as Clone>`
`mbe::TokenTree` doesn't really need to implement `Clone`, and getting rid of that impl leads to some speed-ups.
r? `@petrochenkov`
errors: lazily load fallback fluent bundle
Addresses (hopefully) https://github.com/rust-lang/rust/pull/95667#issuecomment-1094794087.
Loading the fallback bundle in compilation sessions that won't go on to emit any errors unnecessarily degrades compile time performance, so lazily create the Fluent bundle when it is first required.
r? `@ghost` (just for perf initially)
fix: wrong trait import suggestion for T:
The suggestion to bound `T` had an extra `:`.
```rust
fn foo<T:>(t: T) {
t.clone();
}
```
```
error[E0599]: no method named `clone` found for type parameter `T` in the current scope
--> src/lib.rs:2:7
|
2 | t.clone();
| ^^^^^ method not found in `T`
|
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `clone`, perhaps you need to restrict type parameter `T` with it:
|
1 | fn foo<T: Clone:>(t: T) {
| ~~~~~~~~
```
Fixes: #95898
Use mir constant in thir instead of ty::Const
This is blocked on https://github.com/rust-lang/rust/pull/94059 (does include its changes, the first two commits in this PR correspond to those changes) and https://github.com/rust-lang/rust/pull/93800 being reinstated (which had to be reverted). Mainly opening since `@lcnr` offered to give some feedback and maybe also for a perf-run (if necessary).
This currently contains a lot of duplication since some of the logic of `ty::Const` had to be copied to `mir::ConstantKind`, but with the introduction of valtrees a lot of that functionality will disappear from `ty::Const`.
Only the last commit contains changes that need to be reviewed here. Did leave some `FIXME` comments regarding future implementation decisions and some things that might be incorrectly implemented.
r? `@oli-obk`
Loading the fallback bundle in compilation sessions that won't go on to
emit any errors unnecessarily degrades compile time performance, so
lazily create the Fluent bundle when it is first required.
Signed-off-by: David Wood <david.wood@huawei.com>
prevent opaque types from appearing in impl headers
cc `@lqd`
opaque types are not distinguishable from their hidden type at the codegen stage. So we could either end up with cases where the hidden type doesn't implement the trait (which will thus ICE) or where the hidden type does implement the trait (so we'd be using its impl instead of the one written for the opaque type). This can even lead to unsound behaviour without unsafe code.
Fixes https://github.com/rust-lang/rust/issues/86411.
Fixes https://github.com/rust-lang/rust/issues/84660.
rebase of #87382 plus some diagnostic tweaks
Fix suggestions in case of `T:` bounds
This PR fixes a corner case in `suggest_constraining_type_params` that was causing incorrect suggestions.
For the following functions:
```rust
fn a<T:>(t: T) { [t, t]; }
fn b<T>(t: T) where T: { [t, t]; }
```
We previously suggested the following:
```text
...
help: consider restricting type parameter `T`
|
1 | fn a<T: Copy:>(t: T) { [t, t]; }
| ++++++
...
help: consider further restricting this bound
|
2 | fn b<T>(t: T) where T: + Copy { [t, t]; }
| ++++++
```
Note that neither `T: Copy:` not `where T: + Copy` is a correct bound.
With this commit the suggestions are correct:
```text
...
help: consider restricting type parameter `T`
|
1 | fn a<T: Copy>(t: T) { [t, t]; }
| ++++
...
help: consider further restricting this bound
|
2 | fn b<T>(t: T) where T: Copy { [t, t]; }
| ++++
```
r? `@compiler-errors`
I've tried fixing #95898 here too, but got too confused with how `suggest_traits_to_import` works and what it does 😅