Enable ScalarReplacementOfAggregates in optimized builds
Like MatchBranchSimplification, this pass is known to produce significant runtime improvements in Cranelift artifacts, and I believe based on the perf runs here that the primary effect of this pass is to empower MatchBranchSimplification. ScalarReplacementOfAggregates on its own has little effect on anything, but when this was rebased up to include https://github.com/rust-lang/rust/pull/112001 we started seeing significant and majority-positive results.
Based on the fact that we see most of the regressions in debug builds (https://github.com/rust-lang/rust/pull/112002#issuecomment-1566270144) and some rather significant ones in cycles and wall time, I'm only enabling this in optimized builds at the moment.
Preserve substs in opaques recorded in typeck results
This means that we now prepopulate MIR with opaques with the right substs.
The first commit is a hack that I think we discussed, having to do with `DefiningAnchor::Bubble` basically being equivalent to `DefiningAnchor::Error` in the new solver, so having to use `DefiningAnchor::Bind` instead, lol.
r? `@lcnr`
rustdoc: add interaction delays for tooltip popovers
Preview:
* [notable traits](http://notriddle.com/rustdoc-demo-html-3/delay-tooltip/testing/struct.Vec.html#method.iter)
* [panicking code block](http://notriddle.com/rustdoc-demo-html-3/delay-tooltip/testing/struct.Vec.html#indexing)
Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not.
To figure this out, a few different techniques are used:
* When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation.
* This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it.
* This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it.
* A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it.
* No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated.
See also:
* https://www.nngroup.com/articles/timing-exposing-content/
* https://www.nngroup.com/articles/tooltip-guidelines/
* https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
Add a distinct `OperandValue::ZeroSized` variant for ZSTs
These tend to have special handling in a bunch of places anyway, so the variant helps remember that. And I think it's easier to grok than `Aggregate`s sometimes being `Immediates` (after all, I previously got that wrong and caused #109992). As a minor bonus, it means we don't need to generate poison LLVM values for ZSTs to pass around in `OperandValue::Immediate`s.
Inspired by https://github.com/rust-lang/rust/pull/110021#discussion_r1160486991, so
r? `@compiler-errors`
rustdoc: Fix LinkReplacer link matching
It currently just uses the first link with the same href which might not necessarily be the matching one.
This fixes replacements when there are several links to the same item but with different text (e.g. `[X] and [struct@X]`). It also fixes replacements in summaries since those use a links list with empty hrefs, so currently all links would always match the first link by href but then not match its text. This could also lead to a panic in the `original_lext[1..len() - 1]` part when the first link only has a single character, which is why the new code uses `.get(..)` instead.
Replace const eval limit by a lint and add an exponential backoff warning
The lint triggers at the first power of 2 that comes after 1 million function calls or traversed back-edges (takes less than a second on usual programs). After the first emission, an unsilenceable warning is repeated at every following power of 2 terminators, causing it to get reported less and less the longer the evaluation runs.
cc `@rust-lang/wg-const-eval`
fixes#93481closes#67217
These tend to have special handling in a bunch of places anyway, so the variant helps remember that. And I think it's easier to grok than non-Scalar Aggregates sometimes being `Immediates` (like I got wrong and caused 109992). As a minor bonus, it means we don't need to generate poison LLVM values for them to pass around in `OperandValue::Immediate`s.
Uplift `clippy::cast_ref_to_mut` lint
This PR aims at uplifting the `clippy::cast_ref_to_mut` lint into rustc.
## `cast_ref_to_mut`
(deny-by-default)
The `cast_ref_to_mut` lint checks for casts of `&T` to `&mut T` without using interior mutability.
### Example
```rust,compile_fail
fn x(r: &i32) {
unsafe {
*(r as *const i32 as *mut i32) += 1;
}
}
```
### Explanation
Casting `&T` to `&mut T` without interior mutability is undefined behavior, as it's a violation of Rust reference aliasing requirements.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
`@rustbot` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::cast_ref_to_mut` into rustc
linker: Report linker flavors incompatible with the current target
The linker flavor is checked for target compatibility even if linker is never used (e.g. we are producing a rlib).
If it causes trouble, we can move the check to `link.rs` so it will run if the linker (flavor) is actually used.
And also feature gate explicitly specifying linker flavors for tier 3 targets.
The next step is supporting all the internal linker flavors in user-visible interfaces (command line and json).
Only rewrite valtree-constants to patterns and keep other constants opaque
Now that we can reliably fall back to comparing constants with `PartialEq::eq` to the match scrutinee, we can
1. eagerly try to convert constants to valtrees
2. then deeply convert the valtree to a pattern
3. if the to-valtree conversion failed, create an "opaque constant" pattern.
This PR specifically avoids any behavioral changes or major cleanups. What we can now do as follow ups is
* move the two remaining call sites to `destructure_mir_constant` off that query
* make valtree to pattern conversion infallible
* this needs to be done after careful analysis of the effects. There may be user visible changes from that.
based on https://github.com/rust-lang/rust/pull/111768
Rollup of 5 pull requests
Successful merges:
- #111772 (Fix linkage for large binaries on mips64 platforms)
- #111975 (Stop normalizing so many different prefixes)
- #111979 (Respect CARGOFLAGS in bootstrap.py)
- #112089 (Add `--warnings warn` flag to `x.py`)
- #112103 (Bootstrap update to 1.71 beta)
r? `@ghost`
`@rustbot` modify labels: rollup
Stop normalizing so many different prefixes
Previously, we would normalize *all* of
- the absolute path to the repository checkout
- the /rustc/$sha for stage1 (if `remap-debuginfo` was enabled)
- the /rustc/$sha for download-rustc
- the sysroot for download-rustc
Now, we consistently only normalize /rustc/FAKE_PREFIX. Not only is this much simpler, but it also avoids ongoing maintenance for download-rustc and makes it much less likely that tests break by accident.
- Change `tests/ui/track-diagnostics/track6.rs` to use a relative path instead of an absolute one. I am not actually sure why `track_caller` works here, but it does seem to work 🤷
- Pass `-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX` to all suites, not just UI. In particular, mir-opt tests emit /rustc/ paths in their output.
r? ```@cjgillot``` since you reviewed https://github.com/rust-lang/rust/pull/110699 - this is the test that it doesn't regress :)
Fix linkage for large binaries on mips64 platforms
This pull request fixes the linkage for large binaries on mips64 platforms by enabling the `xgot` feature in LLVM.
It is well understood that the generated binary will gain a hefty performance penalty where the external symbol jumps now cost at least three instructions each.
Also, this pull request does not address the same issue on the mips32 counterparts (due to being unable to test the changes thoroughly).
Should fix#52108
move `super_relate_consts` hack to `normalize_param_env_or_error`
`super_relate_consts` has as hack in it to work around the fact that `normalize_param_env_or_error` is broken. When relating two constants we attempt to evaluate them (aka normalize them). This is not an issue in any way specific to const generics, type aliases also have the same issue as demonstrated in [this code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=84b6d3956a2c852a04b60782476b56c9).
Since the hack in `super_relate_consts` only exists to make `normalize_param_env_or_error` emit less errors move it to `normalize_param_env_or_error`. This makes `super_relate_consts` act more like the normal plain structural equality its supposed to and should help ensure that the hack doesnt accidentally affect other situations.
r? `@compiler-errors`
Fix re-export of doc hidden item inside private item not displayed
This PR fixes this bug:
```rust
mod private_module {
#[doc(hidden)]
pub struct Public;
}
pub use crate::private_module::Public as Foo;
```
`pub use crate::private_module::Public as Foo;` should be visible in the generated doc (and not inlined!) but currently isn't. This PR fixes it.
r? `@notriddle`
offset_of: don't require type to be `Sized`
Fixes#112051
~~The RFC [explicitly forbids](https://rust-lang.github.io/rfcs/3308-offset_of.html#limitations) non-`Sized` types, but it looks like only the fields being recursed into were checked. The sized check also seemed to have been completely missing for tuples~~
change `BorrowKind::Unique` to be a mutating `PlaceContext`
fixes#112056
I believe that `BorrowKind::Unique` is a footgun in general, so I added a FIXME and opened https://github.com/rust-lang/rust/issues/112072. This is a bit too involved for this PR though.
refactor and cleanup the leak check, add it to new solver
ended up being a bit more involved than I wanted but is hopefully still easy enough to review as a single PR, can split it into separate ones otherwise.
this can be reviewed commit by commit:
a473d55cdb9284aa2b01282d1b529a2a4d26547b 31a686646534ca006d906ec757ece4e771d6f973 949039c107852a5e36361c08b62821a0613656f5 242917bf5170d9a723c6c8e23e9d9d0c2fa8dc9d ed2b25a7aa28be3184be9e3022c2796a30eaad87 are all pretty straightforward.
03dd83b4c3f4ff27558f5c8ab859bd9f83db1d04 makes it easier to refactor coherence in a later commit, see the commit description, cc `@oli-obk`
4fe311d807a77b6270f384e41689bf5d58f46aec I don't quite remember what we wanted to test here, this definitely doesn't test that the occurs check doesn't cause incorrect errors in coherence, also cc `@oli-obk` here. I may end up writing a new test for this myself later.
5c200d88a91b75bd0875b973150655bd581ef97a is the main refactor of the leak check, changing it to take the `outer_universe` instead of getting it from a snapshot. Using a snapshot requires us to be in a probe which we aren't in the new solver, it also just feels dirty as snapshots don't really have anything to do with universes.
with all of this cfc230d54188d9c7ed867a9a0d1f51be77b485f9 is now kind of trivial.
r? `@nikomatsakis`
Don't typecheck recovered method call from suggestion
Only make the use-dot-operator-to-call-method suggestion, but do not double down and use the recovered type to perform method call typechecking as it will produce confusing diagnostics relevant for the *fixed* code.
### Code Sample
```rust
struct Client;
impl Client {
fn post<T: std::ops::Add>(&self, _: T, _: T) {}
}
fn f() {
let c = Client;
post(c, ());
}
```
### Before This PR
```
error[[E0277]](https://doc.rust-lang.org/stable/error_codes/E0277.html): cannot add `()` to `()`
--> src/lib.rs:9:5
|
9 | post(c, ());
| ^^^^^^^^^^^ no implementation for `() + ()`
|
= help: the trait `Add` is not implemented for `()`
note: required by a bound in `Client::post`
--> src/lib.rs:4:16
|
4 | fn post<T: std::ops::Add>(&self, _: T, _: T) {}
| ^^^^^^^^^^^^^ required by this bound in `Client::post`
error[[E0061]](https://doc.rust-lang.org/stable/error_codes/E0061.html): this function takes 2 arguments but 1 argument was supplied
--> src/lib.rs:9:5
|
9 | post(c, ());
| ^^^^ an argument of type `()` is missing
|
note: method defined here
--> src/lib.rs:4:8
|
4 | fn post<T: std::ops::Add>(&self, _: T, _: T) {}
| ^^^^ ----- ---- ----
help: provide the argument
|
9 | post((), ())(c, ());
| ++++++++
error[[E0425]](https://doc.rust-lang.org/stable/error_codes/E0425.html): cannot find function `post` in this scope
--> src/lib.rs:9:5
|
9 | post(c, ());
| ^^^^ not found in this scope
|
help: use the `.` operator to call the method `post` on `&Client`
|
9 - post(c, ());
9 + c.post(());
|
Some errors have detailed explanations: E0061, E0277, E0425.
For more information about an error, try `rustc --explain E0061`.
```
### After This PR
```
error[E0425]: cannot find function `post` in this scope
--> tests/ui/typeck/issue-106929.rs:9:5
|
9 | post(c, ());
| ^^^^ not found in this scope
|
help: use the `.` operator to call the method `post` on `&Client`
|
9 - post(c, ());
9 + c.post(());
|
error: aborting due to previous error
For more information about this error, try `rustc --explain E0425`.
```
Fixes#106929.
fix: dedup `static_candidates` before report
Fixes https://github.com/rust-lang/rust/issues/103646
`record_static_candidate` had been executed twice, resulting in the presence of two identical `CandidateSource::Trait(Cat)` in static_candidates. This PR aims to deduplication the `static_candidates` list, allowing it to execute `suggest_associated_call_syntax` properly.
Uplift `clippy::invalid_utf8_in_unchecked` lint
This PR aims at uplifting the `clippy::invalid_utf8_in_unchecked` lint into two lints.
## `invalid_from_utf8_unchecked`
(deny-by-default)
The `invalid_from_utf8_unchecked` lint checks for calls to `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut` with an invalid UTF-8 literal.
### Example
```rust
unsafe {
std::str::from_utf8_unchecked(b"cl\x82ippy");
}
```
### Explanation
Creating such a `str` would result in undefined behavior as per documentation for `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut`.
## `invalid_from_utf8`
(warn-by-default)
The `invalid_from_utf8` lint checks for calls to `std::str::from_utf8` and `std::str::from_utf8_mut` with an invalid UTF-8 literal.
### Example
```rust
std::str::from_utf8(b"ru\x82st");
```
### Explanation
Trying to create such a `str` would always return an error as per documentation for `std::str::from_utf8` and `std::str::from_utf8_mut`.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
````@rustbot```` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::invalid_utf8_in_unchecked` into rustc
we can otherwise assign a hidden type to the opaque which
causes ICE if we don't use `take_opaque_types` during
coherence. This is annoying so I didn't bother. Added a test
showing the behavior this prevents.
Optimize scalar and scalar pair representations loaded from ByRef in llvm
in https://github.com/rust-lang/rust/pull/105653 I noticed that we were generating suboptimal LLVM IR if we had a `ConstValue::ByRef` that could be represented by a `ScalarPair`. Before https://github.com/rust-lang/rust/pull/105653 this is probably rare, but after it, every slice will go down this suboptimal code path that requires LLVM to untangle a bunch of indirections and translate static allocations that are only used once to read a scalar pair from.
Only make the use-dot-operator-to-call-method suggestion, but do not
double down and use the recovered type to perform method call
typechecking as it will produce confusing diagnostics on the "fixed"
code.
`[T; N]::zip` is "eager" but most zips are mapped.
This causes poor optimization in generated code.
This is a fundamental design issue and "zip" is
"prime real estate" in terms of function names,
so let's free it up again.
Make `TrustedStep` require `Copy`
All the implementations of the trait already are `Copy`, and this seems to be enough to simplify the implementations enough to make the MIR inliner willing to inline basics like `Range::next`.
r? `@thomcc`
All the implementations of the trait already are `Copy`, and this seems to be enough to simplify the implementations enough to make the MIR inliner willing to inline basics like `Range::next`.
Add a test for issue 110457/incremental ICE with closures with the same span
Closes#110457
It's probably possible to minimize the test case more, considering that we now know the underlying reason for the ICE, but I didn't.
r? `@cjgillot`
Make `TyKind: Debug` have less verbose output
Current `TyKind: Debug` impl is basically unusable for debugging, its too verbose even for verbose debugging 🤣 This PR replaces the debug logic for `TyKind` with a more manual debug impl instead of a hand expanded derived impl. This should help make #107084 more reasonable to land since the output of `Ty: Debug` will be better.
This isn't a fully completed change to the `Debug` impl of `TyKind` as there's still logic from the derive macro for some variants. Some of the variants are also not consisten with the `-Zverbose` printing of `Ty`, ideally `-Zverbose` printing of `Ty` would also just defer to the debug impl instead of having lots of checks in pretty printing. I plan on fixing this in follow up PRs since it seems tricky to do in this one and its already a large PR 😅
Use `Cow` in `{D,Subd}iagnosticMessage`.
Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most compelling change ever, but it might be worth merging.
This requires changing the `impl<'a> From<&'a str>` impls to `impl From<&'static str>`, which involves a bunch of knock-on changes that require/result in call sites being a little more precise about exactly what kind of string they use to create errors, and not just `&str`. This will result in fewer unnecessary allocations, though this will not have any notable perf effects given that these are error paths.
Note that I was lazy within Clippy, using `to_string` in a few places to preserve the existing string imprecision. I could have used `impl Into<{D,Subd}iagnosticMessage>` in various places as is done in the compiler, but that would have required changes to *many* call sites (mostly changing `&format("...")` to `format!("...")`) which didn't seem worthwhile.
r? `@WaffleLapkin`
Rollup of 5 pull requests
Successful merges:
- #112029 (Recover upon mistyped error on typo'd `const` in const param def)
- #112037 (Add details about `unsafe_op_in_unsafe_fn` to E0133)
- #112039 (compiler: update solaris/illumos to enable tsan support.)
- #112042 (Migrate GUI colors test to original CSS color format)
- #112045 (Followup to #111973)
r? `@ghost`
`@rustbot` modify labels: rollup
Recover upon mistyped error on typo'd `const` in const param def
And add machine-applicable fix for the typo'd `const` keyword.
### Before
```
error: expected one of `,`, `:`, `=`, or `>`, found `N`
--> src/lib.rs:1:18
|
1 | pub fn bar<Const N: u8>() {}
| ^ expected one of `,`, `:`, `=`, or `>`
```
### After This PR
```
error: `const` keyword was mistyped as `Const`
--> test.rs:1:8
|
1 | fn bar<Const N: u8>() {}
| ^^^^^
|
help: use the `const` keyword
|
1 | fn bar<const N: u8>() {}
| ~~~~~
```
Fixes#111941.
Inline derived `hash`
Because most of the other derived functions are inlined: `clone`, `default`, `eq`, `partial_cmp`, `cmp`. The exception is `fmt`, but it tends to not be on hot paths as much.
r? `@ghost`
Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most
compelling change ever, but it might be worth merging.
This requires changing the `impl<'a> From<&'a str>` impls to `impl
From<&'static str>`, which involves a bunch of knock-on changes that
require/result in call sites being a little more precise about exactly
what kind of string they use to create errors, and not just `&str`. This
will result in fewer unnecessary allocations, though this will not have
any notable perf effects given that these are error paths.
Note that I was lazy within Clippy, using `to_string` in a few places to
preserve the existing string imprecision. I could have used `impl
Into<{D,Subd}iagnosticMessage>` in various places as is done in the
compiler, but that would have required changes to *many* call sites
(mostly changing `&format("...")` to `format!("...")`) which didn't seem
worthwhile.
MIR: opt-in normalization of `BasicBlock` and `Local` numbering
This doesn't matter at all for actual codegen, but after spending some time reading pre-codegen MIR, I was wishing I didn't have to jump around so much in reading post-inlining code.
So this add two passes that are off by default for every mir level, but can be enabled (`-Zmir-enable-passes=+ReorderBasicBlocks,+ReorderLocals`) for humans.
Don't check for misaligned raw pointer derefs inside Rvalue::AddressOf
From https://github.com/rust-lang/rust/pull/112026#issuecomment-1565686697:
rustc 1.70 (stable next week) added a Mir pass to add pointer alignment checks in debug mode. Adding these checks caused some crates to break, but that was expected, since they contain broken code (https://github.com/rust-lang/rust/issues/111487) for tracking that.
However, the checks added are slightly more aggressive than they should have been. Specifically, they also check the place in an `addr_of!` expression. Whether lack of alignment there is or isn't UB is unclear. This PR modifies the pass to not affect those cases.
I spot checked the crater regressions and the ones I saw were not the case that this PR is modifying. It still seems good to not land anything overaggressive though
Enable MatchBranchSimplification
This pass is one of the small number of benefits from `-Zmir-opt-level=3` that has motivated rustc_codegen_cranelift to use it:
19ed0aade6/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs (L244-L246)
Cranelift's motivation for this is _runtime_ performance improvements in debug builds. Lifting this pass all the way to `-Zmir-opt-level=1` seems to come without significant perf overhead, so that's what I'm suggesting here.
Add support for LLVM SafeStack
Adds support for LLVM [SafeStack] which provides backward edge control
flow protection by separating the stack into two parts: data which is
only accessed in provable safe ways is allocated on the normal stack
(the "safe stack") and all other data is placed in a separate allocation
(the "unsafe stack").
SafeStack support is enabled by passing `-Zsanitizer=safestack`.
[SafeStack]: https://clang.llvm.org/docs/SafeStack.html
cc `@rcvalle` #39699
Add warn-by-default lint when local binding shadows exported glob re-export item
This PR introduces a warn-by-default rustc lint for when a local binding (a use statement, or a type declaration) produces a name which shadows an exported glob re-export item, causing the name from the exported glob re-export to be hidden (see #111336).
### Unresolved Questions
- [x] ~~Is this approach correct? While it passes the UI tests, I'm not entirely convinced it is correct.~~ Seems to be ok now.
- [x] ~~What should the lint be called / how should it be worded? I don't like calling `use x::*;` or `struct Foo;` a "local binding" but they are `NameBinding`s internally if I'm not mistaken.~~ ~~The lint is called `local_binding_shadows_glob_reexport` for now, unless a better name is suggested.~~ `hidden_glob_reexports`.
Fixes#111336.
Rework handling of recursive panics
This PR makes 2 changes to how recursive panics works (a panic while handling a panic).
1. The panic count is no longer used to determine whether to force an immediate abort. This allows code like the following to work without aborting the process immediately:
```rust
struct Double;
impl Drop for Double {
fn drop(&mut self) {
// 2 panics are active at once, but this is fine since it is caught.
std::panic::catch_unwind(|| panic!("twice"));
}
}
let _d = Double;
panic!("once");
```
Rustc already generates appropriate code so that any exceptions escaping out of a `Drop` called in the unwind path will immediately abort the process.
2. Any panics while the panic hook is executing will force an immediate abort. This is necessary to avoid potential deadlocks like #110771 where a panic happens while holding the backtrace lock. We don't even try to print the panic message in this case since the panic may have been caused by `Display` impls.
Fixes#110771
Fix re-export of doc hidden macro not showing up
It's part of the follow-up of https://github.com/rust-lang/rust/pull/109697.
Re-exports of doc hidden macros should be visible. It was the only kind of re-export of doc hidden item that didn't show up.
r? `@notriddle`
fix for `Self` not respecting tuple Ctor privacy
This PR fixes#111220 by checking the privacy of tuple constructors using `Self`, so the following code now errors
```rust
mod my {
pub struct Foo(&'static str);
}
impl AsRef<str> for my::Foo {
fn as_ref(&self) -> &str {
let Self(s) = self; // previously compiled, now errors correctly
s
}
}
```
Change ty and const error's pretty printing to be in braces
`[const error]` and `[type error]` are slightly confusing since they look like either a slice with an error type for the element ty or a slice with a const argument as the type ???. This PR changes them to display as `{const error}` and `{type error}` similar to `{integer}`.
This does not update the `Debug` impls for them which is done in #111988.
I updated some error logic to avoid printing the substs of trait refs when unable to resolve an assoc item for them, this avoids emitting errors with `{type error}` in them. The substs are not relevant for these errors since we don't take into account the substs when resolving the assoc item.
r? ``@compiler-errors``
improve error message for calling a method on a raw pointer with an unknown pointee
The old error message had very confusing wording.
Also added some more test cases besides the single edition test.
r? `@compiler-errors`
Adds support for LLVM [SafeStack] which provides backward edge control
flow protection by separating the stack into two parts: data which is
only accessed in provable safe ways is allocated on the normal stack
(the "safe stack") and all other data is placed in a separate allocation
(the "unsafe stack").
SafeStack support is enabled by passing `-Zsanitizer=safestack`.
[SafeStack]: https://clang.llvm.org/docs/SafeStack.html
Previously, we would normalize *all* of
- the absolute path to the repository checkout
- the /rustc/$sha for stage1 (if `remap-debuginfo` was enabled)
- the /rustc/$sha for download-rustc
- the sysroot for download-rustc
Now, we consistently only normalize /rustc/FAKE_PREFIX. Not only is this
much simpler, but it also avoids ongoing maintenance for download-rustc
and makes it much less likely that tests break by accident.
- Change `tests/ui/track-diagnostics/track6.rs` to use a relative path
instead of an absolute one. I am not actually sure why `track_caller`
works here, but it does seem to work 🤷
- Pass `-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX` to all
suites, not just UI. In particular, mir-opt tests emit /rustc/ paths
in their output.
This fixes#111220 by checking the privacy of tuple constructors using `Self`, so the following code now errors
```rust
mod my {
pub struct Foo(&'static str);
}
impl AsRef<str> for my::Foo {
fn as_ref(&self) -> &str {
let Self(s) = self; // previously compiled, now errors correctly
s
}
}
```
Don't print newlines in APITs
This is kind of a hack, but it gets the job done because the only "special" formatting that (afaict) `rustc_ast_pretty` does is break with newlines sometimes.
Fixesrust-lang/measureme#207
Always capture slice when pattern requires checking the length
Fixes#111751
cc ``@zirconium-n,`` I see you were assigned to this but I've fixed some similar issues in the past and had an idea on how to investigate this.
Consider lint check attributes on match arms
Currently, lint check attributes on match arms have no effect for some lints. This PR makes some lint passes to take those attributes into account.
- `LateContextAndPass` for late lint doesn't update `last_node_with_lint_attrs` when it visits match arms. This leads to lint check attributes on match arms taking no effects on late lints that operate on the arms' pattern:
```rust
match value {
#[deny(non_snake_case)]
PAT => {} // `non_snake_case` only warned due to default lint level
}
```
To be honest, I'm not sure whether this is intentional or just an oversight. I've dug the implementation history and searched up issues/PRs but couldn't find any discussion on this.
- `MatchVisitor` doesn't update its lint level when it visits match arms. This leads to check lint attributes on match arms taking no effect on some lints handled by this visitor, namely: `bindings_with_variant_name` and `irrefutable_let_patterns`.
This seems to be a fallout from #108504. Before 05082f57af, when the visitor operated on HIR rather than THIR, check lint attributes for the said lints were effective. [This playground][play] compiles successfully on current stable (1.69) but fails on current beta and nightly.
I wasn't sure where best to place the test for this. Let me know if there's a better place.
[play]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=38432b79e535cb175f8f7d6d236d29c3
[play-match]: https://play.rust-lang.org/?version=beta&mode=debug&edition=2021&gist=629aa71b7c84b269beadeba664e2221d
Because most of the other derived functions are inlined: `clone`,
`default`, `eq`, `partial_cmp`, `cmp`. The exception is `fmt`, but it
tends to not be on hot paths as much.
Support #[global_allocator] without the allocator shim
This makes it possible to use liballoc/libstd in combination with `--emit obj` if you use `#[global_allocator]`. This is what rust-for-linux uses right now and systemd may use in the future. Currently they have to depend on the exact implementation of the allocator shim to create one themself as `--emit obj` doesn't create an allocator shim.
Note that currently the allocator shim also defines the oom error handler, which is normally required too. Once `#![feature(default_alloc_error_handler)]` becomes the only option, this can be avoided. In addition when using only fallible allocator methods and either `--cfg no_global_oom_handling` for liballoc (like rust-for-linux) or `--gc-sections` no references to the oom error handler will exist.
To avoid this feature being insta-stable, you will have to define `__rust_no_alloc_shim_is_unstable` to avoid linker errors.
(Labeling this with both T-compiler and T-lang as it originally involved both an implementation detail and had an insta-stable user facing change. As noted above, the `__rust_no_alloc_shim_is_unstable` symbol requirement should prevent unintended dependence on this unstable feature.)
Handle opaques in the new solver (take 2?)
Implement a new strategy for handling opaques in the new solver.
First, queries now carry both their defining anchor and the opaques that were defined in the inference context at the time of canonicalization. These are both used to pre-populate the inference context used by the canonical query.
Second, use the normalizes-to goal to handle opaque types in the new solver. This means that opaques are handled like projection aliases, but with their own rules:
* Can only define opaques if they're "defining uses" (i.e. have unique params in all their substs).
* Can only define opaques that are from the anchor.
* Opaque type definitions are modulo regions. So that means `Opaque<'?0r> = HiddenTy1` and `Opaque<?'1r> = HiddenTy2` equate `HiddenTy1` and `HiddenTy2` instead of defining them as different opaque type keys.
Rollup of 5 pull requests
Successful merges:
- #111741 (Use `ObligationCtxt` in custom type ops)
- #111840 (Expose more information in `get_body_with_borrowck_facts`)
- #111876 (Roll compiler_builtins to 0.1.92)
- #111912 (Use `Option::is_some_and` and `Result::is_ok_and` in the compiler )
- #111915 (libtest: Improve error when missing `-Zunstable-options`)
r? `@ghost`
`@rustbot` modify labels: rollup
Expose more information in `get_body_with_borrowck_facts`
Verification tools for Rust such as, for example, Creusot or Prusti would benefit from having access to more information computed by the borrow checker.
As a first step in that direction, #86977 added the `get_body_with_borrowck_facts` API, allowing compiler consumers to obtain a `mir::Body` with accompanying borrow checker information.
At RustVerify 2023, multiple people working on verification tools expressed their need for a more comprehensive API.
While eventually borrow information could be part of Stable MIR, in the meantime, this PR proposes a more limited approach, extending the existing `get_body_with_borrowck_facts` API.
In summary, we propose the following changes:
- Permit obtaining the borrow-checked body without necessarily running Polonius
- Return the `BorrowSet` and the `RegionInferenceContext` in `BodyWithBorrowckFacts`
- Provide a way to compute the `borrows_out_of_scope_at_location` map
- Make some helper methods public
This is similar to #108328 but smaller in scope.
`@smoelius` Do you think these changes would also be sufficient for your needs?
r? `@oli-obk`
cc `@JonasAlaif`
Always require closure parameters to be `Sized`
The `rust-call` ABI isn't compatible with `#![feature(unsized_fn_params)]`, so trying to use that feature with closures leads to an ICE (#67981). This turns that ICE into a type-check error.
`@rustbot` label A-closures F-unsized_fn_params
Designing a good hover microinteraction is a matter of guessing
user intent from what are, literally, vague gestures. In this case,
guessing if hovering in our out of the tooltip base is intentional
or not.
To figure this out, a few different techniques are used:
* When the mouse pointer enters a tooltip anchor point, its hitbox
is grown on the bottom, where the popover is/will appear. This was
already there before this commit: search "hover tunnel" in
rustdoc.css for the implementation.
* This commit adds a delay when the mouse pointer enters the base
anchor, in case the mouse pointer was just passing through and the
user didn't want to open it.
* This commit also adds a delay when the mouse pointer exits the
tooltip's base anchor or its popover, before hiding it.
* A fade-out animation is layered onto the pointer exit delay to
immediately inform the user that they successfully dismissed the
popover, while still providing a way for them to cancel it if
it was a mistake and they still wanted to interact with it.
* No animation is used for revealing it, because we don't want
people to try to interact with an element while it's in the
middle of fading in: either they're allowed to interact with
it while it's fading in, meaning it can't serve as mistake-
proofing for opening the popover, or they can't, but they
might try and be frustrated.
See also:
* https://www.nngroup.com/articles/timing-exposing-content/
* https://www.nngroup.com/articles/tooltip-guidelines/
* https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
CFI: Fix encode_region: unexpected ReEarlyBound(0, 'a)
Fixes#111515 and complements #106547 by adding support for encoding early bound regions and also excluding projections when transforming trait objects' traits into their identities before emitting type checks.
fix(resolve): not defined `extern crate shadow_name`
Fixes https://github.com/rust-lang/rust/issues/109148
## Why does #109148 panic?
When resolving `use std::xx` it enters `visit_scopes` from `early_resolve_ident_in_lexical_scope`, and iters twice during the loop:
|iter| `scope` | `break_result` | result |
|-|-|-|-|
| 0 | `Module` pointed to root | binding pointed to `Undetermined`, so result is `None` | scope changed to `ExternPrelude` |
| 1 | `ExternPrelude` | binding pointed to `std` | - |
Then, the result of `maybe_resolve_path` is `Module(std)`, so `import.imported_module.set` is executed.
Finally, during the `finalize_import` of `use std::xx`, `resolve_path` returns `NonModule` because `Binding(Ident(std), Module(root)`'s binding points to `extern crate blah as std`, which causes the assertion to fail at `assert!(import.imported_module.get().is_none());`.
## Investigation
The question is why `#[a] extern crate blah as std` is not defined as a binding of `std::xxx`, which causes the iteration twice during `visit_scopes` when resolving `std::xxx`. Ideally, the value of `break_result.is_some()` should have been valid in the first iteration.
After debugging, I found that because `#[a] extern crate blah as std` had been dummied by `placeholder` during `collect_invocations`, so it had lost its attrs, span, etc..., so it will not be defined. However, `expand_invoc` added them back, then the next `build_reduced_graph`, `#[a] extern crate blah as std` would have been defined, so it makes the result of `resolved_path` unexpected, and the program panics.
## Try to solve
I think there has two-way to solve this issue:
- Expand invocations before the first `resolve_imports` during `fully_expand_fragment`. However, I do not think this is a good idea because it would mess up the current design.
- As my PR described: do not define to `extern crate blah as std` during the second `build_reduced_graph`, which is very easy and more reasonable.
r? `@petrochenkov`
The `rust-call` ABI isn't compatible with
`#![feature(unsized_fn_params)]`, so trying to use that feature with
closures leads to an ICE (#67981). This turns that ICE into a
type-check error.
Fixes#111515 and complements #106547 by adding support for encoding
early bound regions and also excluding projections when transforming
trait objects' traits into their identities before emitting type checks.
Fix some issues with folded AArch64 features
In #91608 the `fp` feature was removed for AArch64 and folded into the `neon` feature, however disabling the `neon` feature doesn't actually disable the `fp` feature. If my understanding on that thread is correct it should do.
While doing this, I also noticed that disabling some features would disable features that it shouldn't. For instance enabling `sve` will enable `neon`, however, when disabling `sve` it would then also disable `neon`, I wouldn't expect disabling `sve` to also disable `neon`.
cc `@workingjubilee`
When compiling with panic=abort (or using a target that doesn't have
unwinding support), the compiler adds the "nounwind" attribute to
functions. This results in a different LLVM IR, which results in a #NNN
added after the function name:
tail call void @bar() #13, !dbg !467
attributes #13 = { nounwind }
...instead of:
tail call void @bar(), !dbg !467
This commit changes the matchers to swallow the #NNN, as it's not needed
for these specific tests.
Rollup of 6 pull requests
Successful merges:
- #111461 (Fix symbol conflict diagnostic mistakenly being shown instead of missing crate diagnostic)
- #111579 (Also assume wrap-around discriminants in `as` MIR building)
- #111704 (Remove return type sized check hack from hir typeck)
- #111853 (Check opaques for mismatch during writeback)
- #111854 (rustdoc: clean up `settings.css`)
- #111860 (Don't ICE if method receiver fails to unify with `arbitrary_self_types`)
r? `@ghost`
`@rustbot` modify labels: rollup
Don't ICE if method receiver fails to unify with `arbitrary_self_types`
Consider:
```rust
struct Foo(u32);
impl Foo {
fn get<R: Deref<Target=Self>>(self: R) -> u32 {
self.0
}
}
fn main() {
let mut foo = Foo(1);
foo.get::<&Foo>();
}
```
The problem here is that with `arbitrary_self_types`, we're allowed to have a method receiver that mentions generics from the method itself (`fn get<R: Deref<Target=Self>>(self: R)`). Since we don't actually take into account the user-written turbofish generics when doing method lookup (nor do we check that method predicates hold), method probing will happily infer `R = Foo` during the probe. When we later confirm the method, we do use the turbofish'd subst and instead now have that `R = &Foo`. This doesn't unify with the self type we chose during the probe, causing an ICE.
Getting this to work correctly will be difficult. Specifically, we'll need to actually pass in the turbofish generics for the method being probed for and check that the self type unifies considering those generics. This seems like a lot of work, and I'm not actually familiar with the restrictions originally called out for `#![feature(arbitrary_self_types)]`, but I think we should probably instead just deny having receivers that mention (type/const) generics that come from the method itself.
But I mostly just want to turn this ICE into an error, so I'll leave that up for later PRs.
Fixes#111838
Check opaques for mismatch during writeback
Revive #111705.
I realized that we don't need to put any substs in the writeback results since all of the hidden types have already been remapped. See the comment in `compiler/rustc_middle/src/ty/typeck_results.rs`, which should make that clear for other explorers of the codebase.
Additionally, we need to do some diagnostic stashing because the diagnostics we produce during HIR typeck is very poor and we should prefer the diagnostic that comes from MIR, if we have one.
r? `@oli-obk`
Remove return type sized check hack from hir typeck
Remove a bunch of special-cased suggestions when someone returns `-> dyn Trait` that checks for type equality, etc.
This was a pretty complex piece of code that also relied on a hack in hir typeck (see changes to `compiler/rustc_hir_typeck/src/check.rs`), and I'm not convinced that it's necessary to maintain, when all we really need to tell the user is that they should return `-> impl Trait` or `-> Box<dyn Trait>`, depending on their specific use-case.
This is necessary because we may need to move the "return type is sized" check from hir typeck to wfcheck, which does not have access to typeck results. This is a prerequisite for that, and I'm fairly confident that the diagnostics "regressions" here are not a big deal.
[rustc_ty_utils] Treat `drop_in_place`'s *mut argument like &mut when adding LLVM attributes
This resurrects PR #103614, which has sat idle for a while.
This could probably use a new perf run, since we're on a new LLVM version now.
r? `@oli-obk`
cc `@RalfJung`
---
LLVM can make use of the `noalias` parameter attribute on the parameter to `drop_in_place` in areas like argument promotion. Because the Rust compiler fully controls the code for `drop_in_place`, it can soundly deduce parameter attributes on it.
In #103957, Miri was changed to retag `drop_in_place`'s argument as if it was `&mut`, matching this change.
Deal with unnormalized projections when structurally resolving types with new solver
1. Normalize types in `structurally_resolved_type` when the new solver is enabled
2. Normalize built-in autoderef targets in `Autoderef` when the new solver is enabled
3. Normalize-erasing-regions in `resolve_type` in writeback
This is motivated by the UI test provided, which currently fails with:
```
error[E0609]: no field `x` on type `<usize as SliceIndex<[Foo]>>::Output`
--> <source>:9:11
|
9 | xs[0].x = 1;
| ^
```
I'm pretty happy with the approach in (1.) and (2.) and think we'll inevitably need something like this in the long-term, but (3.) seems like a hack to me. It's a *lot* of work to add tons of new calls to every user of these typeck results though (mir build, late lints, etc). Happy to discuss further.
r? `@lcnr`
This was added to control percentage sizes, in
79956b96e8
Now, the only percentage size is [`border-radius`], which is
based on the size of the box itself, not its containing block.
This leaves the property unused.
[`border-radius`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius
Give better error when collecting into `&[T]`
The detection of slice reference of `{integral}` in `rustc_on_unimplemented` is hacky, but a proper solution requires changing `FmtPrinter` to add a parameter to print integers as `{integral}` and I didn't want to change it just for `rustc_on_unimplemented`. I can do that if requested, though.
I'm open to better wording; this is the best I could come up with.
fix recursion depth handling after confirmation
fixes#111729
I think having to use `Obligation::with_depth` correctly everywhere is very hard because e.g. the nested obligations from `eq` currently do not have the correct obligation depth.
The new solver [completely removes `recursion_depth` from obligations](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/traits/solve/struct.Goal.html) and instead tracks the depth in the solver itself which is far easier to get right. Moving the old solver towards this shouldn't be that hard but is probably somewhat annoying.
r? `@matthewjasper`
Fix duplicate `arcinner_layout_for_value_layout` calls when using the uninit `Arc` constructors
What this fixes is the duplicate calls to `arcinner_layout_for_value_layout` seen here: https://godbolt.org/z/jr5Gxozhj
The issue was discovered alongside #111603 but is otherwise unrelated to the duplicate `alloca`s, which remain unsolved. Everything I tried to solve said main issue has failed.
As for the duplicate layout calculations, I also tried slapping `#[inline]` and `#[inline(always)]` on everything in sight but the only thing that worked in the end is to dedup the calls by hand.
Rather than returning an array of features from to_llvm_features, return a structure that contains
the dependencies. This also contains metadata on how the features depend on each other to allow for
the correct enabling and disabling.
Some features that are tied together only make sense to be folded
together when enabling the feature. For example on AArch64 sve and
neon are tied together, however it doesn't make sense to disable neon
when disabling sve.
rustdoc: include strikethrough in item summary
Fixes https://github.com/rust-lang/rust/issues/111822. Since **bold** and *italic* are included, I don't see why ~~strikethrough~~ shouldn't be.
Since this only affects `PreCodegen MIR, and it would be nice for that to be resilient to permutations of things that don't affect the actual semantic behaviours.
Rollup of 5 pull requests
Successful merges:
- #111745 (Fix overflow in error emitter)
- #111770 (Read beta version from the version file if building from a source tarball)
- #111797 (Migrate GUI colors test to original CSS color format)
- #111809 (Unset MIRI_BLESS for mir-opt-level 4 miri tests)
- #111817 (Migrate GUI colors test to original CSS color format)
r? `@ghost`
`@rustbot` modify labels: rollup
Fix overflow in error emitter
Fix#109854Close#94171 (was already fixed before but missing test)
This bug happens when a multipart suggestion spans more than one line.
The fix is to update the `acc` variable, which didn't handle the case when the text to remove spans multiple lines but the text to add spans only one line.
Also, use `usize::try_from` instead of `as usize` to detect overflows earlier in the future, and point to the source of the overflow (the original issue points to a different place where this value is used, not where the overflow had happened).
And finally add an `if start != end` check to avoid doing any extra work in case of empty ranges.
Long explanation:
Given this test case:
```rust
fn generate_setter() {
String::with_capacity(
//~^ ERROR this function takes 1 argument but 3 arguments were supplied
generate_setter,
r#"
pub(crate) struct Person<T: Clone> {}
"#,
r#""#,
);
}
```
The compiler will try to convert that code into the following:
```rust
fn generate_setter() {
String::with_capacity(
//~^ ERROR this function takes 1 argument but 3 arguments were supplied
/* usize */,
);
}
```
So it creates a suggestion with 3 separate parts:
```
// Replace "generate_setter" with "/* usize */"
SubstitutionPart { span: fuzz_input.rs:4:5: 4:20 (#0), snippet: "/* usize */" }
// Remove second arg (multiline string)
SubstitutionPart { span: fuzz_input.rs:4:20: 7:3 (#0), snippet: "" }
// Remove third arg (r#""#)
SubstitutionPart { span: fuzz_input.rs:7:3: 8:11 (#0), snippet: "" }
```
Each of this parts gets a separate `SubstitutionHighlight` (this marks the relevant text green in a terminal, the values are 0-indexed so `start: 4` means column 5):
```
SubstitutionHighlight { start: 4, end: 15 }
SubstitutionHighlight { start: 15, end: 15 }
SubstitutionHighlight { start: 18446744073709551614, end: 18446744073709551614 }
```
The 2nd and 3rd suggestion are empty (start = end) because they only remove text, so there are no additions to highlight. But the 3rd span has overflowed because the compiler assumes that the 3rd suggestion is on the same line as the first suggestion. The 2nd span starts at column 20 and the highlight starts at column 16 (15+1), so that suggestion is good. But since the 3rd span starts at column 3, the result is `3 - 4`, or column -1, which turns into -2 with 0-indexed, and that's equivalent to `18446744073709551614 as isize`.
With this fix, the resulting `SubstitutionHighlight` are:
```
SubstitutionHighlight { start: 4, end: 15 }
SubstitutionHighlight { start: 15, end: 15 }
SubstitutionHighlight { start: 15, end: 15 }
```
As expected. I guess ideally we shouldn't emit empty highlights when removing text, but I am too scared to change that.
Don't inline functions with unsized args
Fixes#111355 .
I have some ideas for how we can get this back in the future, out of scope for this PR though.
r? `@cjgillot`
CFI: Fix encode_ty: unexpected Param(B/#1)
Fixes#111510 and complements #106547 by adding support for encoding type parameters and also by transforming trait objects' traits into their identities before emitting type checks.
don't skip inference for type in `offset_of!`
Fixes https://github.com/rust-lang/rust/issues/111678 by no longer skipping inference on the type in `offset_of!`. Simply erasing the regions the during writeback isn't enough and can cause ICEs. A test case for this is included.
This reverts https://github.com/rust-lang/rust/pull/111661, because it becomes redundant, since inference already erases the regions.
Fix local libs not included when printing native static libs
This PR fixes https://github.com/rust-lang/rust/issues/111643 by adding the local used libs to the printed `--print=native-static-libs` output.
It seems that `--print=native-static-libs` doesn't have any test, so I added one. It's very simple and doesn't even tries to compile the result to a binary as I don't know how to handle external library linking in CI. (Note that https://github.com/rust-lang/rust/blob/master/tests/run-make/staticlib-dylib-linkage/Makefile does compile to a binary)
r? `@bjorn3`
The CHECK, -NOT, -SAME pattern ensures that the `CHECK-NOT: noalias`
is limited to only one line, and won't match unrelated lines further
down in the file.
Explicit drop call added to preserve the `foo` argument name, since
names of unused arguments are not preserved.
We've done measurements with Miri and have determined that `noalias` shouldn't
break code. The requirements that allow us to add dereferenceable and align
have been long documented in the standard library documentation.
LLVM can make use of the `noalias` parameter attribute on the parameter to
`drop_in_place` in areas like argument promotion. Because the Rust compiler
fully controls the code for `drop_in_place`, it can soundly deduce parameter
attributes on it. In the case of a value that has a programmer-defined Drop
implementation, we know that the first thing `drop_in_place` will do is pass a
pointer to the object to `Drop::drop`. `Drop::drop` takes `&mut`, so it must be
guaranteed that there are no pointers to the object upon entering that
function. Therefore, it should be safe to mark `noalias` there.
With this patch, we mark `noalias` only when the type is a value with a
programmer-defined Drop implementation. This is possibly overly conservative,
but I thought that proceeding cautiously was best in this instance.
Add more tests for the offset_of macro
Implements what I [suggested in the tracking issue](https://github.com/rust-lang/rust/issues/106655#issuecomment-1535007205), plus some further improvements:
* ensuring that offset_of!(Self, ...) works iff inside an impl block
* ensuring that the output type is usize and doesn't coerce. this can be changed in the future, but if it is done, it should be a conscious decision
* improving the privacy checking test
* ensuring that generics don't let you escape the unsized check
r? `````@WaffleLapkin`````
Dont check `must_use` on nested `impl Future` from fn
Fixes (but does not close, per beta policy) #111484
Also fixes a `FIXME` left in the code about (presumably) false-positives on non-async `#[must_use] fn() -> impl Future` cases, though if that's not desirable to include in the beta backport then I can certainly revert it.
Beta nominating as it fixes a beta ICE.
Fix dependency tracking for debugger visualizers
This PR fixes dependency tracking for debugger visualizer files by changing the `debugger_visualizers` query to an `eval_always` query that scans the AST while it is still available. This way the set of visualizer files is already available when dep-info is emitted. Since the query is turned into an `eval_always` query, dependency tracking will now reliably detect changes to the visualizer script files themselves.
TODO:
- [x] perf.rlo
- [x] Needs a bit more documentation in some places
- [x] Needs regression test for the incr. comp. case
Fixes https://github.com/rust-lang/rust/issues/111226
Fixes https://github.com/rust-lang/rust/issues/111227
Fixes https://github.com/rust-lang/rust/issues/111295
r? `@wesleywiser`
cc `@gibbyfree`