Use `cfg_match!` in core
All of these uses of `cfg_if!` do not utilize that `cfg_if!` works with auto-`doc(cfg)`, so no functionality is lost from switching to use `cfg_match!` instead. We *do* lose what rustfmt special support exists for `cfg_if!`, though.
Tracking issue: #115585
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
Add bootstrap step diff to CI job analysis
This PR adds another analysis to the job analysis report in GitHub summary. It compares (diffs) bootstrap steps executed by the parent run and by the current commit. This will help us figure out if the bootstrap invocation did something different than before, and also how did the duration of individual steps and bootstrap invocations change.
Can be tested on the https://github.com/rust-lang/rust/pull/119899 PR like this:
```bash
$ curl https://ci-artifacts.rust-lang.org/rustc-builds/3d3394eb64ee2f99ad1a2b849b376220fd38263e/metrics-mingw-check.json > metrics.json
$ cargo run --manifest-path src/ci/citool/Cargo.toml postprocess-metrics metrics.json --job-name mingw-check --parent 961351c76c > out.md
```
r? `@marcoie`
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`
```
Override PartialOrd methods for bool
I noticed that `PartialOrd` implementation for `bool` does not override the individual operator methods, unlike the other primitive types like `char` and integers.
This commit extracts these `PartialOrd` overrides shared by the other primitive types into a macro and calls it on `bool` too.
CC `@scottmcm` for our recent adventures in `PartialOrd` land
rustdoc: remove useless `Symbol::is_empty` checks.
There are a number of `is_empty` checks that can never fail. This commit removes them, in support of #137978.
r? `@GuillaumeGomez`
Add target maintainer information for powerpc64-unknown-linux-musl
We intend to fix the outstanding issues on the target and eventually promote it to tier 2. We have the capacity to maintain this target in the future and already perform regular builds of rustc for this target.
Currently, all host tools except miri build fine, but I have a patch for libffi-sys to make miri also compile fine for this target that is [pending review](https://github.com/tov/libffi-rs/pull/100).
While at it, add an option for the musl root for this target.
I also added a kernel version requirement, which is rather arbitrarily chosen, but it matches our tier 2 powerpc64le-unknown-linux-musl target so I think it is a good fit.
Fix ui pattern_types test for big-endian platforms
The newly added pattern types validity tests fail on s390x and presumably other big-endian systems, due to print of raw values with padding bytes.
To fix the tests remove the raw output values in the error note by `normalize-stderr`.
Trusty: Fix build for anonymous pipes and std::sys::process
PRs #136842 (Add libstd support for Trusty targets), #137793 (Stablize anonymous pipe), and #136929 (std: move process implementations to `sys`) merged around the same time, so update Trusty to take them into account.
cc `@randomPoison`
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
I noticed that `PartialOrd` implementation for `bool` does not override the
individual operator methods, unlike the other primitive types like `char`
and integers.
This commit extracts these `PartialOrd` overrides shared by the other
primitive types into a macro and calls it on `bool` too.
Rollup of 8 pull requests
Successful merges:
- #135745 (Recognise new IPv6 non-global range from IETF RFC 9602)
- #137247 (cg_llvm: Reduce the visibility of types, modules and using declarations in `rustc_codegen_llvm`.)
- #138317 (privacy: Visit types and traits in impls in type privacy lints)
- #138581 (Abort in deadlock handler if we fail to get a query map)
- #138776 (coverage: Separate span-extraction from unexpansion)
- #138886 (Fix autofix for `self` and `self as …` in `unused_imports` lint)
- #138924 (Reduce `kw::Empty` usage, part 3)
- #138929 (Visitors track whether an assoc item is in a trait impl or an inherent impl)
r? `@ghost`
`@rustbot` modify labels: rollup
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
compiletest: Support matching on diagnostics without a span
Using `//~? ERROR my message` on any line of the test.
The new checks are exhaustive, like all other `//~` checks, and unlike the `error-pattern` directive that is sometimes used now to check for span-less diagnostics.
This will allow to eliminate most on `error-pattern` directives in compile-fail tests (except those that are intentionally imprecise due to platform-specific diagnostics).
I didn't migrate any of `error-pattern`s in this PR though, except those where the migration was necessary for the tests to pass.