Remove `prev_index_to_index` field from `CurrentDepGraph`
The dep graph currently has 2 ways to map a previous index into a current index. The `prev_index_to_index` map stores the current index equivalent of a previous index. For indices which are marked green, we also store the same information in the `DepNodeColorMap`. We actually only need to known the mapping for green nodes however, so this PR removes `prev_index_to_index` and instead makes use of the `DepNodeColorMap`.
To avoid racing when promoting a node from the previous session, the encoder lock is now used to ensure only one thread encodes the promoted node. This was previously done by the lock in `prev_index_to_index`.
This also changes `nodes_newly_allocated_in_current_session` used to detect duplicate dep nodes to contain both new and previous nodes, which is simpler and can better catch duplicates.
The dep node index encoding used in `DepNodeColorMap` is tweak to avoid subtraction / addition to optimize accessing the current equivalent of a previous index.
r? `@oli-obk`
hygiene: Ensure uniqueness of `SyntaxContextData`s
`SyntaxContextData`s are basically interned with `SyntaxContext`s working as indices, so they are supposed to be unique.
However, currently duplicate `SyntaxContextData`s can be created during decoding from metadata or incremental cache.
This PR fixes that.
cc https://github.com/rust-lang/rust/pull/129827#discussion_r1759074553
Rollup of 7 pull requests
Successful merges:
- #138483 (Target modifiers fix for bool flags without value)
- #138818 (Don't produce debug information for compiler-introduced-vars when desugaring assignments.)
- #138898 (Mostly parser: Eliminate code that's been dead / semi-dead since the removal of type ascription syntax)
- #138930 (Add bootstrap step diff to CI job analysis)
- #138954 (Ensure `define_opaque` attrs are accounted for in HIR hash)
- #138959 (Revert "Make MatchPairTree::place non-optional")
- #138967 (Fix typo in error message)
r? `@ghost`
`@rustbot` modify labels: rollup
Mostly parser: Eliminate code that's been dead / semi-dead since the removal of type ascription syntax
**Disclaimer**: This PR is intended to mostly clean up code as opposed to bringing about behavioral changes. Therefore it doesn't aim to address any of the 'FIXME: remove after a month [dated: 2023-05-02]: "type ascription syntax has been removed, see issue [#]101728"'.
---
By commit:
1. Removes truly dead code:
* Since 1.71 (#109128) `let _ = { f: x };` is a syntax error as opposed to a semantic error which allows the parse-time diagnostic (suggestion) "*struct literal body without path // you might have forgotten […]*" to kick in.
* The analysis-time diagnostic (suggestion) from <=1.70 "*cannot find value \`f\` in this scope // you might have forgotten […]*" is therefore no longer reachable.
2. Updates `is_certainly_not_a_block` to be in line with the current grammar:
* The seq. `{ ident:` is definitely not the start of a block. Before the removal of ty ascr, `{ ident: ty_start` would begin a block expr.
* This shouldn't make more code compile IINM, it should *ultimately* only affect diagnostics.
* For example, `if T { f: () } {}` will now be interpreted as an `if` with struct lit `T { f: () }` as its *condition* (which is banned in the parser anyway) as opposed to just `T` (with the *consequent* being `f : ()` which is also invalid (since 1.71)). The diagnostics are almost the same because we have two separate parse recovery procedures + diagnostics: `StructLiteralNeedingParens` (*invalid struct lit*) before and `StructLiteralNotAllowedHere` (*struct lits aren't allowed here*) now, as you can see from the diff.
* (As an aside, even before this PR, fn `maybe_suggest_struct_literal` should've just used the much older & clearer `StructLiteralNotAllowedHere`)
* NB: This does sadly regress the compiler output for `tests/ui/parser/type-ascription-in-pattern.rs` but that can be fixed in follow-up PRs. It's not super important IMO and a natural consequence.
3. Removes code that's become dead due to the prior commit.
* Basically reverts #106620 + #112475 (without regressing rustc's output!).
* Now the older & more robust parse recovery procedure (cc `StructLiteralNotAllowedHere`) takes care of the cases the removed code used to handle.
* This automatically fixes the suggestions for \[[playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=7e2030163b11ee96d17adc3325b01780)\]:
* `if Ty::<i32> { f: K }.m() {}`: `if Ty::<i32> { SomeStruct { f: K } }.m() {}` (broken) → ` if (Ty::<i32> { f: K }).m() {}`
* `if <T as Trait>::Out { f: K::<> }.m() {}`: `if <T as Trait>(::Out { f: K::<> }).m() {}` (broken) → `if (<T as Trait>::Out { f: K::<> }).m() {}`
4. Merge and simplify UI tests pertaining to this issue, so it's easier to add more regression tests like for the two cases mentioned above.
5. Merge UI tests and add the two regression tests.
Best reviewed commit by commit (on request I'll partially squash after approval).
Don't produce debug information for compiler-introduced-vars when desugaring assignments.
An assignment such as
(a, b) = (b, c);
desugars to the HIR
{ let (lhs, lhs) = (b, c); a = lhs; b = lhs; };
The repeated `lhs` leads to multiple Locals assigned to the same DILocalVariable. Rather than attempting to fix that, get rid of the debug info for these bindings that don't even exist in the program to begin with.
Fixes#138198
r? `@jieyouxu`
Target modifiers fix for bool flags without value
Fixed support of boolean flags without values: `-Zbool-flag` is now consistent with `-Zbool-flag=true` in another crate.
When flag is explicitly set to default value, target modifier will not be set in crate metainfo (`-Zflag=false` when `false` is a default value for the flag).
Improved error notification when target modifier flag is absent in a crate ("-Zflag unset").
Example:
```
note: `-Zreg-struct-return=true` in this crate is incompatible with unset `-Zreg-struct-return` in dependency `default_reg_struct_return`
```
Batch mark waiters as unblocked when resuming in the deadlock handler
This fixes a race when resuming multiple threads to resolve query cycles. This now marks all threads as unblocked before resuming any of them. Previously if one was resumed and marked as unblocked at a time. The first thread resumed could fall asleep then Rayon would detect a second false deadlock. Later the initial deadlock handler thread would resume further threads.
This also reverts the workaround added in https://github.com/rust-lang/rust/pull/137731.
cc `@SparrowLii` `@lqd`
Stabilize `#![feature(precise_capturing_in_traits)]`
# Precise capturing (`+ use<>` bounds) in traits - Stabilization Report
Fixes https://github.com/rust-lang/rust/issues/130044.
## Stabilization summary
This report proposes the stabilization of `use<>` precise capturing bounds in return-position impl traits in traits (RPITITs). This completes a missing part of [RFC 3617 "Precise capturing"].
Precise capturing in traits was not ready for stabilization when the first subset was proposed for stabilization (namely, RPITs on free and inherent functions - https://github.com/rust-lang/rust/pull/127672) since this feature has a slightly different implementation, and it hadn't yet been implemented or tested at the time. It is now complete, and the type system implications of this stabilization are detailed below.
## Motivation
Currently, RPITITs capture all in-scope lifetimes, according to the decision made in the ["lifetime capture rules 2024" RFC](https://rust-lang.github.io/rfcs/3498-lifetime-capture-rules-2024.html#return-position-impl-trait-in-trait-rpitit). However, traits can be designed such that some lifetimes in arguments may not want to be captured. There is currently no way to express this.
## Major design decisions since the RFC
No major decisions were made. This is simply an extension to the RFC that was understood as a follow-up from the original stabilization.
## What is stabilized?
Users may write `+ use<'a, T>` bounds on their RPITITs. This conceptually modifies the desugaring of the RPITIT to omit the lifetimes that we would copy over from the method. For example,
```rust
trait Foo {
fn method<'a>(&'a self) -> impl Sized;
// ... desugars to something like:
type RPITIT_1<'a>: Sized;
fn method_desugared<'a>(&'a self) -> Self::RPITIT_1<'a>;
// ... whereas with precise capturing ...
fn precise<'a>(&'a self) -> impl Sized + use<Self>;
// ... desugars to something like:
type RPITIT_2: Sized;
fn precise_desugared<'a>(&'a self) -> Self::RPITIT_2;
}
```
And thus the GAT doesn't name `'a`. In the compiler internals, it's not implemented exactly like this, but not in a way that users should expect to be able to observe.
#### Limitations on what generics must be captured
Currently, we require that all generics from the trait (including the `Self`) type are captured. This is because the generics from the trait are required to be *invariant* in order to do associated type normalization.
And like regular precise capturing bounds, all type and const generics in scope must be captured.
Thus, only the in-scope method lifetimes may be relaxed with this syntax today.
## What isn't stabilized? (a.k.a. potential future work)
See section above. Relaxing the requirement to capture all type and const generics in scope may be relaxed when https://github.com/rust-lang/rust/issues/130043 is implemented, however it currently interacts with some underexplored corners of the type system (e.g. unconstrained type bivariance) so I don't expect it to come soon after.
## Implementation summary
This functionality is implemented analogously to the way that *opaque type* precise capturing works.
Namely, we currently use *variance* to model the capturedness of lifetimes. However, since RPITITs are anonymous GATs instead of opaque types, we instead modify the type relation of GATs to consider variances for RPITITs (along with opaque types which it has done since https://github.com/rust-lang/rust/pull/103491).
30f168ef81/compiler/rustc_middle/src/ty/util.rs (L954-L976)30f168ef81/compiler/rustc_type_ir/src/relate.rs (L240-L244)
Using variance to model capturedness is an implementation detail, and in the future it would be desirable if opaques and RPITITs simply did not include the uncaptured lifetimes in their generics. This can be changed in a forwards-compatible way, and almost certainly would not be observable by users (at least not negatively, since it may indeed fix some bugs along the way).
## Tests
* Test that the lifetime isn't actually captured: `tests/ui/impl-trait/precise-capturing/rpitit.rs` and `tests/ui/impl-trait/precise-capturing/rpitit-outlives.rs` and `tests/ui/impl-trait/precise-capturing/rpitit-outlives-2.rs`.
* Technical test for variance computation: `tests/ui/impl-trait/in-trait/variance.rs`.
* Test that you must capture all trait generics: `tests/ui/impl-trait/precise-capturing/forgot-to-capture-type.rs`.
* Test that you cannot capture more than what the trait specifies: `tests/ui/impl-trait/precise-capturing/rpitit-captures-more-method-lifetimes.rs` and `tests/ui/impl-trait/precise-capturing/rpitit-impl-captures-too-much.rs`.
* Undercapturing (refinement) lint: `tests/ui/impl-trait/in-trait/refine-captures.rs`.
### What other unstable features may be exposed by this feature?
I don't believe that this exposes any new unstable features indirectly.
## Remaining bugs and open issues
Not aware of any open issues or bugs.
## Tooling support
Rustfmt: ✅ Supports formatting `+ use<>` everywhere.
Clippy: ✅ No support needed, unless specific clippy lints are impl'd to care for precise capturing itself.
Rustdoc: ✅ Rendering `+ use<>` precise capturing bounds is supported.
Rust-analyzer: ✅ Parser support, and then lifetime support isn't needed https://github.com/rust-lang/rust/pull/138128#issuecomment-2705292494 (previous: ~~❓ There is parser support, but I am unsure of rust-analyzer's level of support for RPITITs in general.~~)
## History
Tracking issue: https://github.com/rust-lang/rust/issues/130044
* https://github.com/rust-lang/rust/pull/131033
* https://github.com/rust-lang/rust/pull/132795
* https://github.com/rust-lang/rust/pull/136554
add FCW to warn about wasm ABI transition
See https://github.com/rust-lang/rust/issues/122532 for context: the "C" ABI on wasm32-unk-unk will change. The goal of this lint is to warn about any function definition and calls whose behavior will be affected by the change. My understanding is the following:
- scalar arguments are fine
- including 128 bit types, they get passed as two `i64` arguments in both ABIs
- `repr(C)` structs (recursively) wrapping a single scalar argument are fine (unless they have extra padding due to over-alignment attributes)
- all return values are fine
`@bjorn3` `@alexcrichton` `@Manishearth` is that correct?
I am making this a "show up in future compat reports" lint to maximize the chances people become aware of this. OTOH this likely means warnings for most users of Diplomat so maybe we shouldn't do this?
IIUC, wasm-bindgen should be unaffected by this lint as they only pass scalar types as arguments.
Tracking issue: https://github.com/rust-lang/rust/issues/138762
Transition plan blog post: https://github.com/rust-lang/blog.rust-lang.org/pull/1531
try-job: dist-various-2
Visitors track whether an assoc item is in a trait impl or an inherent impl
`AssocCtxt::Impl` now contains an `of_trait` field. This allows ast lowering and nameres to not have to track whether we're in a trait impl or an inherent impl.
Fix autofix for `self` and `self as …` in `unused_imports` lint
This fixes two problems with the autofixes for the `unused_imports` lint:
- `use std::collections::{HashMap, self as coll};` would suggest, when `HashMap` is unused, the incorrect `use std::collections::self as coll;` which does not compile.
- `use std::borrow::{self, Cow};` would suggest, when `self` is unused, `use std::borrow::{Cow};`, which contains unnecessary brackets.
The first problem was reported in rust-lang/rust-clippy#14450, the second found while fixing the first one.
Fix#133750
(thanks to `@richardsamuels` for spotting the duplicate)
coverage: Separate span-extraction from unexpansion
Historically, coverage instrumentation has relied on eagerly “unexpanding” MIR spans back to ancestor spans that have the same context as the function body, and lie within that body. Doing so makes several subsequent operations more straightforward.
In order to support expansion regions, we need to stop doing that, and handle layers of macro-expansion more explicitly. This PR takes a step in that direction, by deferring some of the unexpansion steps, and concentrating them in one place (`spans::extract_refined_covspans`).
Unexpansion still takes place as before, but these changes will make it easier to experiment with expansion-aware coverage instrumentation.
Abort in deadlock handler if we fail to get a query map
Resolving query cycles requires the complete active query map, or it may miss query cycles. We did not check that the map is completely constructed before. If there is some error collecting the map, something has gone wrong already. This adds a check to abort/panic if we fail to construct the complete map.
This can help differentiate errors from the `deadlock detected` case if constructing query map has errors in practice.
An `Option` is not used for `collect_active_jobs` as the panic handler can still make use of a partial map.
cg_llvm: Reduce the visibility of types, modules and using declarations in `rustc_codegen_llvm`.
Final part of #135502
Reduces the visibility of types, modules and using declarations in the `rustc_codegen_llvm` to private or `pub(crate)` where possible, and marks unused fields and enum entries with `#[expect(dead_code)]`.
r? Zalathar
StructLiteralNeedingParens is no longer reachable always giving
precedence to StructLiteralNotAllowedHere.
As an aside: The former error struct shouldn't've existed in the
first place. We should've just used the latter in this branch.
Remove InstanceKind::generates_cgu_internal_copy
This PR should not contain any behavior changes. Before this PR, the logic for selecting instantiation mode is spread across all of
* `instantiation_mode`
* `cross_crate_inlinable`
* `generates_cgu_internal_copy`
* `requires_inline`
The last two of those functions are not well-designed. The function that actually decides if we generate a CGU-internal copy is `instantiation_mode`, _not_ `generates_cgu_internal_copy`. The function `requires_inline` documents that it is about the LLVM `inline` attribute and that it is a hint. The LLVM attribute is called `inlinehint`, this function is also used by other codegen backends, and since it is part of instantiation mode selection it is *not* a hint.
The goal of this PR is to start cleaning up the logic into a sequence of checks that have a more logical flow and are easier to customize in the future (to do things like improve incrementality or improve optimizations without causing obscure linker errors because you forgot to update another part of the compiler).
Add a helper for building an owner id in ast lowering
Just some deduplication of owner-id creations. Will also help me later split up ast lowering into per-owner queries, as it won't be possible anymore to go from a NodeId to a DefId of an owner without doing extra work to check whether we have an owner id. So I'd just do that in the new `owner_id` function and keep the `local_def_id` function free of that logic
Fix/tweak some tests in new solver
Bunch of miscellaneous new solver tweaks that I found from the failing tests. Can split these out, but they all seemed small enough to not warrant separate PRs.
r? lcnr
The existing code produces `Some(kw::Empty)` for these invalid forms:
- a non-name-value, e.g. `#[rustc_allowed_through_unstable_modules]`
- a non-string arg, e.g. `#[rustc_allowed_through_unstable_modules = 3]`
The new code avoids the `kw::Empty` and is a little shorter. It will
produce `None` in those cases, which means E0789 won't be produced if
the `stable` attribute is missing for these invalid forms. This doesn't
matter, because these invalid forms will trigger an "malformed
`rustc_allowed_through_unstable_modules` attribute" anyway.
This way, `None` represents "crate root without a name" instead of
`kw::Empty`. This changes makes it impossible to forget to handle the
exceptional case.