std: sys: process: uefi: Add program searching
- Follow UEFI Shell search flow to search for programs while launching.
- Tested using OVMF on QEMU.
@rustbot label +O-UEFI
Avoid Vec allocation in TyCtxt::mk_place_elem
`mk_place_elem` appends a single `PlaceElem` to an existing (interned) projection. The current implementation copies the projection into a fresh `Vec`, pushes the new element, and re-interns the slice, which allocates on every call.
Feed the elements through `mk_place_elems_from_iter` so that `CollectAndApply`'s hand-unrolled stack fast path (up to 9 elements, in `rustc_type_ir::interner`) kicks in for the common case of short projections and the `Vec` allocation is skipped entirely. The behavior is identical for longer projections (the fast path falls back to a `Vec` internally).
Fix heap overflow in slice::join caused by misbehaving Borrow
This code allocates a buffer using lengths calculated by calling `.borrow()` on some slices, and then copies them over after again calling `.borrow()`. There is no safety-reliable guarantee that these will return the same slices.
While this code calls `.borrow()` three times, only one of them is problematic: the others already use checked indexing.
I made the test a normal library test, but let me know if it should go elsewhere.
Bug discovered by Rust Foundation Security using AI. I'm just helping with the patch as a member of wg-security-response. We do not believe this bug needs embargo, it is a soundness fix for hard-to-trigger unsoundness.
Implement more traits for FRTs
From https://github.com/rust-lang/rust/pull/154927#discussion_r3068460955.
FRTs now implement the following traits: `Sized + Freeze + RefUnwindSafe + Send + Sync + Unpin + UnsafeUnpin + UnwindSafe + Copy + Debug + Default + Eq + Hash + Ord`.
Let me know if there is any trait missing.
I also removed the explicit `Send` and `Sync` impls, since commit cb37ee2c87 ("make field representing types invariant over the base type") made the auto-trait impl work even if `T: !Send` or `T: !Sync`. Very happy to see unsafe impls get dropped :)
Note that I used the reflection feature (cc @oli-obk) to print the actual field names in the debug implementation. I think this is a cool way to use it, but if it isn't ready for that, I'm happy to change it to the alternative implementation I gave in the note comment (it's essentially Mark's suggestion but printing `T`'s name instead of `Self`'s).
Since this is a library change, I'll give this to Mark; feel free to also take a look/leave comments, Oli :)
r? @Mark-Simulacrum
Make Rcs and Arcs use pointer comparison for unsized types
`Rc` and `Arc`s have an `Eq` implementation that first attempt to compare the pointers as an optimization. This, however, was not extended to DSTs, which is what this PR fixes.
Fixesrust-lang/rust#154998.
`std::io::Take`: Clarify & optimize `BorrowedBuf::set_init` usage.
Don't initialize `buf` if it was already initialized. Clarify safety comments.
Move the `buf.advance()` call to make the initialization more like
calling `buf.ensure_init()`, then clarify how the code here is an
optimized variant of `ensure_init`.
Fix requires_lto targets needing lto set in cargo
Targets that set `requires_lto = true` were not actually using lto when compiling with cargo by default. They needed an extra `lto = true` in `Cargo.toml` to work.
Fix this by letting lto take precedence over the `embed_bitcode` flag when lto is required by a target.
If both these flags would be supplied by the user, an error is generated. However, this did not happen when lto was requested by the target instead of the user.
Fixesrust-lang/rust#148514
Tracking issue: rust-lang/rust#135024
Avoid improper spans when `...` or `..=` is recovered from non-ASCII
- Fixes https://github.com/rust-lang/rust/issues/155799
Adjusting span endpoints by `BytePos(1)` is almost always bad news.
In this case, the code assumed that it was skipping over a single ASCII character. But in the presence of parser recovery from other non-ASCII characters this resulted in an ICE due to bad string indexing when emitting suggestions.
Cleanups to `AttributeExt`
r? @mejrs
- Makes some functions take `ast::Attribute` instead of `impl AttributeExt`
- Remove `deprecation_note` from `AttributeExt`, since the two implementations are basically seperate
Fix minor panic-unsoundness in CString::clone_into
`CString` must always contain a null byte, calling `mem::take` on its inner allocation puts it in an invalid state (causing UB if e.g. it hits `CString::drop`) that can be observed if the allocator panics.
Unfortunately, this solution allocates an intermediate 1-element `Box`. I'm not sure of a clean way to avoid that additional allocation; we could directly `realloc` if we want but it's tricky. Might be something we can do with `ManuallyDrop`.
I do have a gnarly miri test for this that uses a panicky allocator, but I'm not sure where it would go. Happy to push it up if someone has a suggestion.
Bug discovered by Rust Foundation Security using AI. I'm just helping with the patch as a member of wg-security-response. We do not believe this bug needs embargo, it is a soundness fix for hard-to-trigger unsoundness.
Suggest enclosing format string with `""` under special cases
This commit adds suggestions on enclosing format string with `""` when it falls into the following 3 cases: `{}`, `{:?}`, `{:#?}` as mentioned in rust-lang/rust#155508.
Currently, this commit only recognizes the above 3 cases. I wonder if we should generalize this to more cases, for example, appying this suggestion to `Block`s with only 0 or 1 `Stmt`, such as `{:#x}`, `{:^10}`, `{abc}`.
macro_metavar_expr_concat: explain why idents are invalid
Recently I've been playing around with `macro_metavar_expr_concat` and in the process wasted more time than I'd have liked on debugging my dodgy idents. This should make that experience much nicer going forward.
Prefer `-1` for `None`
Currently we pick "weird" numbers like `1114112` for `None::<char>`. While that's not *wrong*, it's kinda *unnatural* -- a human wouldn't make that choice.
This PR instead picks `-1` for thinge like `None::<char>` -- like [clang's `WEOF`](63ae74b78a/libc/include/llvm-libc-macros/wchar-macros.h (L15)) -- and `None::<bool>` and such.
Any enums with more than one niched value (so not `Result` nor `Option`) remain as they were before. Also we continue to use `0` when that's possible -- `-1` is only preferred when zero *isn't* possible.
---
Inspired when someone in discord posted an example like this <https://rust.godbolt.org/z/W94s9qdYW> and I thought it was odd that we're currently picking `-9223372036854775808` to be the value to store to mark an `Option<Vec<_>>` as `None`. (Especially since that needs an 8-byte immediate on x64, and writing `-1` is only a 4-byte immediate.)
Move `std::io::RawOsError` to `core::io`
ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: https://github.com/rust-lang/rust/issues/154046
Related: https://github.com/rust-lang/rust/pull/154654
## Description
As a part of moving components of `std::io` into `alloc::io` and `core::io`, there will need to be a new home for the type `RawOsError`. In this PR, I propose moving it to `core::io`, and removing it from `std::sys`. I suspect this will be quite controversial as it is a platform dependent type, but this is not the only instance of a type being conditioned on `target_os` in `core` (e.g., `core::os` and `core::ffi`).
Since `RawOsError` is currently unstable, I think it's reasonable to make this move now, and worry about making it platform independent if/when it is stabilized (e.g., replacing it with a wrapper around `isize` on all platforms).
---
## Notes
* No AI tooling of any kind was used during the creation of this PR.
Windows: Cache the pipe filesystem handle
Updates the anonymous pipe handling based on feedback from @lhecker (see https://github.com/rust-lang/rust/pull/142517#discussion_r3065864262). This does two things:
1. Cache the handle to the pipe filesystem so we don't have to reopen it each time.
2. Use the `\Device\NamedPipe\` directly instead of the symlink to it.
* Suggest enclosing format string under special cases
This commit add suggestions about enclosing format string when it falls
into the following cases: `{}`, `{:?}`, `{:#?}`.
* Add HELP annotations in the UI test
std: maintain `CStringArray` null-termination even if `Vec::push` panics
Fixesrust-lang/rust#155748 by performing the `push` of the new null terminator before overwriting the previous one.
This commit expands the initialism UCRT on first use in the rusct book
chapter on the *-windows-gnullvm platform support, making the chapter
easier to understand. Microsoft, the originator of this technology in
Windows, expands it to Universal C Runtime[1]. The same expansion is
added to the chapter.
[1] https://learn.microsoft.com/en-us/cpp/porting/upgrade-your-code-to-the-universal-crt
Currently we pick "weird" numbers like `1114112` for `None::<char>`. While that's not *wrong*, it's kinda *unnatural* -- a human wouldn't make that choice.
This PR instead picks `-1` for thinge like `None::<char>` -- like clang's `WEOF` -- and `None::<bool>` and such.
Any enums with more than one niched value (so not `Result` nor `Option`) remain as they were before.
Rollup of 9 pull requests
Successful merges:
- rust-lang/rust#146181 (Add intrinsic for launch-sized workgroup memory on GPUs)
- rust-lang/rust#154803 (Fix ICE from cfg_attr_trace )
- rust-lang/rust#155065 (Error on invalid macho section specifier)
- rust-lang/rust#155485 (Add an edge-case test for `--remap-path-prefix` for `rustc` & `rustdoc`)
- rust-lang/rust#155659 (cleanup, restructure and merge `tests/ui/deriving` into `tests/ui/derives`)
- rust-lang/rust#155676 ( Reject implementing const Drop for types that are not const `Destruct` already)
- rust-lang/rust#155696 (Add a higher-level API for parsing attributes)
- rust-lang/rust#155769 (triagebot.toml: Ping Enselic when tests/debuginfo/basic-stepping.rs changes)
- rust-lang/rust#155783 (Do not suggest internal cfg trace attributes)
Reject implementing const Drop for types that are not const `Destruct` already
fixesrust-lang/rust#155618
While there is no soundness or otherwise issue currently, this PR ensures that people get what they expect. It seems wrong to allow implementing `const Drop`, but then the type still can't be dropped at compile-time.
r? @fee1-dead
cleanup, restructure and merge `tests/ui/deriving` into `tests/ui/derives`
As a followup to https://github.com/rust-lang/rust/pull/155615, this PR deletes some outdated tests from these directories, splits up `ui/derives` into smaller directories to roughly group tests by the derive macros they use and moves over all tests from `ui/deriving` into `ui/derives`.
r? @Kivooeo
Error on invalid macho section specifier
The macho section specifier used by `#[link_section = "..."]` is more strict than e.g. the one for elf. LLVM will error when you get it wrong, which is easy to do if you're used to elf. So, provide some guidance for the simplest mistakes, based on the LLVM validation.
Currently compilation fails with an LLVM error, see https://godbolt.org/z/WoE8EdK1K.
The LLVM validation logic is at
a0f0d6342e/llvm/lib/MC/MCSectionMachO.cpp (L199-L203)
LLVM validates the other components of the section specifier too, but it feels a bit fragile to duplicate those checks. If you get that far, hopefully the LLVM errors will be sufficient to get unstuck.
---
sidequest from https://github.com/rust-lang/rust/pull/147811
r? JonathanBrouwer
specifically, is this the right place for this sort of validation? `rustc_attr_parsing` also does some validation.
Add intrinsic for launch-sized workgroup memory on GPUs
Workgroup memory is a memory region that is shared between all
threads in a workgroup on GPUs. Workgroup memory can be allocated
statically or after compilation, when launching a gpu-kernel.
The intrinsic added here returns the pointer to the memory that is
allocated at launch-time.
# Interface
With this change, workgroup memory can be accessed in Rust by
calling the new `gpu_launch_sized_workgroup_mem<T>() -> *mut T`
intrinsic.
It returns the pointer to workgroup memory guaranteeing that it is
aligned to at least the alignment of `T`.
The pointer is dereferencable for the size specified when launching the
current gpu-kernel (which may be the size of `T` but can also be larger
or smaller or zero).
All calls to this intrinsic return a pointer to the same address.
See the intrinsic documentation for more details.
## Alternative Interfaces
It was also considered to expose dynamic workgroup memory as extern
static variables in Rust, like they are represented in LLVM IR.
However, due to the pointer not being guaranteed to be dereferencable
(that depends on the allocated size at runtime), such a global must be
zero-sized, which makes global variables a bad fit.
# Implementation Details
Workgroup memory in amdgpu and nvptx lives in address space 3.
Workgroup memory from a launch is implemented by creating an
external global variable in address space 3. The global is declared with
size 0, as the actual size is only known at runtime. It is defined
behavior in LLVM to access an external global outside the defined size.
There is no similar way to get the allocated size of launch-sized
workgroup memory on amdgpu an nvptx, so users have to pass this
out-of-band or rely on target specific ways for now.
Tracking issue: rust-lang/rust#135516
privacy: Assert that compared visibilities are (usually) ordered
And make "greater than" (`>`) the new primary operation for comparing visibilities instead of "is at least" (`>=`).
`mk_place_elem` appends a single `PlaceElem` to an existing (interned)
projection. The current implementation copies the projection into a
fresh `Vec`, pushes the new element, and re-interns the slice, which
allocates on the heap on every call.
Feed the elements through `mk_place_elems_from_iter` so that
`CollectAndApply`'s hand-unrolled stack fast path (up to 9 elements,
in `rustc_type_ir::interner`) kicks in for the common case of short
projections and the `Vec` allocation is skipped entirely. The behavior
is identical for longer projections (the fast path falls back to a
`Vec` internally).
Do not modify resolver outputs during lowering
Split from https://github.com/rust-lang/rust/pull/142830
I believe this achieves the same thing as https://github.com/rust-lang/rust/pull/153656 but in a much simpler way.
This PR forces AST->HIR lowering to stop mutating resolver outputs. Instead, it manages a few override maps that only live during lowering and are dropped afterwards.
r? @petrochenkov
cc @aerooneqq
The test `tests/debuginfo/basic-stepping.rs` has a history of regressing
for subtle reasons, and has non-obvious expectations. So I'd like to
keep an extra eye on it.
Pass fields to `is_tuple_fields` instead of `SBValue` object
straightforward fix for a logic error. `is_tuple_fields` expects a `list`, so we pass that in instead of the value object.
Coincidentally, this also fixes one of the 3 DI tests that fails on `x86_64-pc-windows-gnu` (`tests/debuginfo/union-smoke.rs`)
Account for `GetSyntheticValue` failures
`GetSyntheticValue` returns an invalid `SBValue` if no synthetic is present. That wasn't a problem before when we were attaching synthetics to every type, but it won't be the case once github.com/rust-lang/rust/pull/155336 or similar lands. Additionally, codelldb subverts `lldb_commands` to apply similar behavior that doesn't attach synthetics to every type, so this fixes a regression there too.
Additionally, I removed 1 useless instance of `GetSyntheticValue`, since pointers should always be `IndirectionSyntheticProvider`, not `DefaultSyntheticProvider`.
bootstrap: Don't clone submodules unconditionally in dry-run
This made it very annoying to debug bootstrap itself, because every `--dry-run` invocation would start out by cloning LLVM, which is almost never necessary. Instead change a few Steps to properly support dry_run when no submodule is checked out.
I tested this by running all of `check`, `build`, `doc`, `dist`, `install`, `vendor`, `clippy`, `fix`, and `miri` with `--dry-run`.
Handle index projections in call destinations in DSE
Since call destinations are evaluated after call arguments, we can't turn copy arguments into moves if the same local is later used as an index projection in the call destination.
DSE call arg optimization: rust-lang/rust#113758
r? @cjgillot
cc @RalfJung
Avoid redundant clone suggestions in borrowck diagnostics
Fixesrust-lang/rust#153886
Removed redundant `.clone()` suggestions.
I found that there are two patterns to handle this issue while I was implementing:
- Should suggest only UFCS
- Should suggest only simple `.clone()`
For the target issue, we can just remove the UFCS (`<Option<String> as Clone>::clone(&selection.1)`) side.
However, for the `BorrowedContentSource::OverloadedDeref` pattern like `Rc<Vec<i32>>`, for instance the `borrowck-move-out-of-overloaded-auto-deref.rs` test case, I think we need to employ the UFCS way. The actual test case is:
```rust
//@ run-rustfix
use std::rc::Rc;
pub fn main() {
let _x = Rc::new(vec![1, 2]).into_iter();
//~^ ERROR [E0507]
}
```
And another error will be shown if we simply use the simple `.clone()` pattern. Like:
```rust
use std::rc::Rc;
pub fn main() {
let _x = Rc::new(vec![1, 2]).clone().into_iter();
}
```
then we will get
```
error[E0507]: cannot move out of an `Rc`
--> src/main.rs:5:14
|
5 | let _x = Rc::new(vec![1, 2]).clone().into_iter();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ----------- value moved due to this method call
| |
| move occurs because value has type `Vec<i32>`, which does not implement the `Copy` trait
|
note: `into_iter` takes ownership of the receiver `self`, which moves value
--> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:310:18
|
310 | fn into_iter(self) -> Self::IntoIter;
| ^^^^
help: you can `clone` the value and consume it, but this might not be your desired behavior
|
5 - let _x = Rc::new(vec![1, 2]).clone().into_iter();
5 + let _x = <Vec<i32> as Clone>::clone(&Rc::new(vec![1, 2])).into_iter();
|
For more information about this error, try `rustc --explain E0507`.
```
[Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=7e767bed3f1c573c03642f20f454ed03)
In this case, `Rc::clone` only increments the reference count and returns a new `Rc<Vec<i32>>`; it does not grant ownership of the inner `Vec<i32>`. As a result, calling into_iter() attempts to move the `Vec<i32>`, leading to the same E0507 error again.
On the other hand, in UFCS form:
```
<Vec<i32> as Clone>::clone(&Rc::new(vec![1, 2])).into_iter()
```
This explicitly calls `<Vec<i32> as Clone>::clone`, and the argument `&Rc<Vec<i32>>` is treated as `&Vec<i32>` via Rc’s `Deref` implementation. As a result, the `Vec<i32>` itself is cloned, yielding an owned `Vec<i32>`, which allows `into_iter()` to succeed, if my understanding is correct.
I addressed the issue as far as I could find the edge cases but please advice me if I'm overlooking something.
Rollup of 3 pull requests
Successful merges:
- rust-lang/rust#155754 (make the `core::ffi::va_list` module private)
- rust-lang/rust#155522 (cmse: test returning `MaybeUninit<T>`)
- rust-lang/rust#155741 (std: Refactor BufWriter::flush to use the `?` operator)
cmse: test returning `MaybeUninit<T>`
tracking issue: https://github.com/rust-lang/rust/issues/81391
tracking issue: https://github.com/rust-lang/rust/issues/75835
Some tests from https://github.com/rust-lang/rust/pull/147697 that already work and are useful. Extracting them shrinks that (currently blocked) PR.
The code in `tests/ui/cmse-nonsecure/cmse-nonsecure-call/return-via-stack.rs` checks that `MaybeUninit<T>` is considered abi-compatible with `T`. The code in `tests/ui/cmse-nonsecure/cmse-nonsecure-entry/params-via-stack.rs` really only tests that no errors/warnings are emitted.
r? davidtwco
Permit `{This}` in diagnostic attribute format literals
My motivation was that yesterday I wanted to write something like this and reference `$name` in the string literal.
```rust
pub mod sym {
// stuff here
}
macro_rules! my_macro {
($name:ident $(,)?) => {{
#[diagnostic::on_unknown(
message = "this is not present in symbol table",
note = "you must add it to rustc_span::symbol::symbol!"
)]
use sym::$name as name;
// ...
}}
}
```
That is (as far as I can tell) impossible or at least very unergonomic. This adds the ability to just reference the name of the item the attribute is on. I imagine that's useful for use inside macros generally, so it's also added for some other attributes.
The affected attributes are all unstable, it is not implemented for diagnostic::on_unimplemented (will do in its own PR).
Note that `{This}` is already usable in `#[rustc_on_unimplemented]`, so this does not implement it but just enables some more.
This PR also migrates one lint away from AttributeLintKind, and improves the messages for that lint.
Rollup of 12 pull requests
Successful merges:
- rust-lang/rust#149452 (Refactor out common code into a `IndexItem::new` constructor)
- rust-lang/rust#155621 (Document #[diagnostic::on_move] in the unstable book.)
- rust-lang/rust#155635 (delegation: rename `Self` generic param to `This` in recursive delegations)
- rust-lang/rust#155730 (Some cleanups around per parent disambiguators)
- rust-lang/rust#153537 (rustc_codegen_ssa: Define ELF flag value for sparc-unknown-linux-gnu)
- rust-lang/rust#155219 (Do not suggest borrowing enclosing calls for nested where-clause obligations)
- rust-lang/rust#155408 (rustdoc: Fix Managarm C Library name in cfg pretty printer)
- rust-lang/rust#155571 (Enable AddressSanitizer on arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf)
- rust-lang/rust#155713 (test: Add a regression test for Apple platforms aborting on `free`)
- rust-lang/rust#155723 (Fix tier level for 5 thumb bare-metal ARM targets)
- rust-lang/rust#155735 (Fix typo by removing extra 'to')
- rust-lang/rust#155736 (Remove `AllVariants` workaround for rust-analyzer)
Remove `AllVariants` workaround for rust-analyzer
Part of https://github.com/rust-lang/rust/issues/155677
Removes the `ALL_VARIANTS` alias added to work around rust-analyzer not supporting `#![feature(macro_derive)]`, which has since been fixed (rust-lang/rust-analyzer/issues/21043).
Fix typo by removing extra 'to'
Fixesrust-lang/rust#155695
Fix a typo in the `std::convert` module documentation by removing an extra "to" in the module-level docs.
Fix tier level for 5 thumb bare-metal ARM targets
The spec files for 5 Thumb-mode bare-metal ARM targets incorrectly set tier: Some(2), while the documentation correctly lists them as Tier 3. This mismatch was introduced in PR #150556 — the intent was Tier 2 eventually, but these targets should sit at Tier 3 until a proper Tier 3 → Tier 2 promotion MCP is submitted and approved.
This PR changes tier: Some(2) → Some(3) in the following spec files, making them consistent with the docs:
thumbv7a-none-eabi
thumbv7a-none-eabihf
thumbv7r-none-eabi
thumbv7r-none-eabihf
thumbv8r-none-eabihf
PS: No doc changes needed — they already correctly state Tier 3.
r?
test: Add a regression test for Apple platforms aborting on `free`
Add a regression test for https://github.com/rust-lang/rust/issues/150898 to make users aware that if this test failures, they may encounter unusual behavior elsewhere.
Enable AddressSanitizer on arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf
Add SanitizerSet::ADDRESS to the supported_sanitizers for the arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf targets.
The AddressSanitizer is already enabled on the armv7-linux-androideabi platform, which shares the same ARM architecture. There is no reason these Linux GNU targets should not also support it, as the underlying LLVM support for ASan on 32-bit ARM is already in place.
rustdoc: Fix Managarm C Library name in cfg pretty printer
Like rust-lang/rust#155293, this was introduced in https://github.com/rust-lang/rust/pull/154328.
Unlike that PR, I don't think there's any need to backport, because this cfg is not used anywhere in the standard library.
(I searched for `"mlibc"`, the only place it's used in rust-lang/rust is the HTML doc test.)
#### Other Minor Fixes
Remove a FIXME comment in the pretty printer, `os = "none"` is always bare metal:
d227e48c56/compiler/rustc_target/src/spec/mod.rs (L3179)
Fix a comment typo, ignore another typo in vendored sources.
Do not suggest borrowing enclosing calls for nested where-clause obligations
In rust-lang/rust#155088, the compiler was blaming the whole call expr instead of the value that actually failed the trait bound, so for foo(&[String::from("a")]) it was suggesting stuff like &foo(...). I changed the suggestion logic so it only emits borrow help if the expr it found actually matches the failed self type, and used the same check for the “similar impl exists” help too. So now the compiler should give the normal error + required bound note.
Fixrust-lang/rust#155088
Some cleanups around per parent disambiguators
r? @petrochenkov
follow-up to rust-lang/rust#155547
The two remaining uses are
* resolve_bound_vars, where it is a reasonable way to do it instead of having another field in the visitor that needs to get scoped (set & reset) every time we visit an opaque type. May still change that at some point, but it's not really an issue
* `create_def` in the resolver: will get removed together with my other refactorings for `node_id_to_def_id` (making that per-owner)
delegation: rename `Self` generic param to `This` in recursive delegations
This PR supports renaming of `Self` generic parameter to `This` in recursive delegations scenario, this allows propagation of `This` as we rely on `Self` naming to check whether it is implicit Self of a trait. Comment with a bit deeper explanation is in `uplift_delegation_generic_params`. Part of rust-lang/rust#118212.
r? @petrochenkov
This made it very annoying to debug bootstrap itself, because every
`--dry-run` invocation would start out by cloning LLVM, which is almost
never necessary. Instead change a few Steps to properly support dry_run
when no submodule is checked out.
Add a regression test for RUST-150898 to make users aware that if this
test fails, they may encounter unusual behavior elsewhere.
Original repro authored by dianqk.
Workgroup memory is a memory region that is shared between all
threads in a workgroup on GPUs. Workgroup memory can be allocated
statically or after compilation, when launching a gpu-kernel.
The intrinsic added here returns the pointer to the memory that is
allocated at launch-time.
# Interface
With this change, workgroup memory can be accessed in Rust by
calling the new `gpu_launch_sized_workgroup_mem<T>() -> *mut T`
intrinsic.
It returns the pointer to workgroup memory guaranteeing that it is
aligned to at least the alignment of `T`.
The pointer is dereferencable for the size specified when launching the
current gpu-kernel (which may be the size of `T` but can also be larger
or smaller or zero).
All calls to this intrinsic return a pointer to the same address.
See the intrinsic documentation for more details.
## Alternative Interfaces
It was also considered to expose dynamic workgroup memory as extern
static variables in Rust, like they are represented in LLVM IR.
However, due to the pointer not being guaranteed to be dereferencable
(that depends on the allocated size at runtime), such a global must be
zero-sized, which makes global variables a bad fit.
# Implementation Details
Workgroup memory in amdgpu and nvptx lives in address space 3.
Workgroup memory from a launch is implemented by creating an
external global variable in address space 3. The global is declared with
size 0, as the actual size is only known at runtime. It is defined
behavior in LLVM to access an external global outside the defined size.
There is no similar way to get the allocated size of launch-sized
workgroup memory on amdgpu an nvptx, so users have to pass this
out-of-band or rely on target specific ways for now.
Forbid `*-pass` and `*-fail` directives in tests/crashes
Crash tests are always expected to crash during compilation, so there is no sensible meaning for specifying a pass expectation or a run-fail expectation in a crash test.
It could conceivably be useful to use failure expectations to specify whether a crash test requires codegen in order to crash, but currently none of the crash tests try to do that. If that functionality is desired in the future, we can always look into re-adding it after the internals of pass/fail expectations have been cleaned up a bit.
---
After this change, pass/fail directives are only allowed in UI tests, which should make it easier to overhaul and simplify their implementation.
r? jieyouxu
Remove `AttributeLintKind` variants - part 7
Part of https://github.com/rust-lang/rust/issues/153099.
It's the last easy one. Next one will require to get the crate name and to pass `Session` to the remaining lints. Fun times ahead. :)
r? @JonathanBrouwer
Remove myself as a maintainer of `wasm32-wasip1-threads`
Over time the landscape for myself has changed, and I no longer would like to be officially listed as a maintainer of this target in Rust, so I'm going to step down. There are still a number of others listed on this target, however, so I'm sure they can address issues should they come up.
Syntactically reject tuple index shorthands in struct patterns to fix a correctness regression
Split out of PR rust-lang/rust#154492. This fixes a correctness regression introduced in PR rust-lang/rust#81235 from 2021. Crater was run in my other PR and didn't report any real regressions (https://github.com/rust-lang/rust/pull/154492#issuecomment-4187544786); a rerun has been issued for a few spurious builds (https://github.com/rust-lang/rust/pull/154492#issuecomment-4237077272) but I'm certain it won't find anything either.
This is a theoretical breaking change that doesn't need any T-lang input IMHO since it's such a minute, niche and crystal clear bug that's not worth bothering them with (such a decision is not unprecedented). I'm adding it to the compatibility section of the release notes as is customary.
The Reference doesn't need updating since it didn't adopt this bug and thus accurately describes this part of the grammar as it used to be before 2021-02-23 and as it's meant to be.
The majority of the diff is doc comment additions & necessary UI test restructurings.
Eliminate `CrateMetadataRef`.
There are a number of things I dislike about `CrateMetadataRef`.
- It contains two fields `cstore` and `cdata`. The latter points to data within the former. It's like having an `Elem` type that has a reference to a vec element and also a reference to the vec itself. Weird.
- The `cdata` field gets a lot of use, and the `Deref` impl just derefs that field. The `cstore` field is rarely used.
- `CrateMetadataRef` is not a good name.
- Variables named `cdata` sometimes refer to values of this type and sometimes to values of type `CrateMetadata`, which is confusing.
The good news is that `CrateMetadataRef` is not necessary and can be replaced with `&CrateMetadata`. Why? Everywhere that `CrateMetadataRef` is used, a `TyCtxt` is also present, and the `CStore` is accessible from the `TyCtxt` with `CStore::from_tcx`.
So this commit removes `CrateMetadataRef` and replaces all its uses with `&CrateMetadata`. Notes:
- This requires adding only two uses of `CStore::from_tcx`, which shows how rarely the `cstore` field was used.
- `get_crate_data` now matches `get_crate_data_mut` more closely.
- A few variables are renamed for consistency, e.g. `data`/`cmeta` -> `cdata`.
- An unnecessary local variable (`local_cdata`) in `decode_expn_id` is removed.
- All the `CrateMetadataRef` methods become `CrateMetadata` methods, and their receiver changes from `self` to `&self`.
- `RawDefId::decode_from_cdata` is inlined and removed, because it has a single call site.
r? @mejrs
Move and clean up some ui test
`ui/reserved` -> `ui/keyword`
`ui/deref-patterns` -> `ui/pattern/deref-patterns`
`ui/unknown-unstable-lints` -> `ui/lint/unknown-lints`
Tests related to unknown_lints that were located above lint have also been moved to a subdirectory, and duplicate tests have been deleted.
And delete unnecessary `//@ check-fail`
r? Kivooeo
Generalize IO Traits for `Arc<T>` where `&T: IoTrait`
ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: https://github.com/rust-lang/rust/issues/154046
Related: rust-lang/rust#94744
## Description
After experimenting with rust-lang/rust#155625, I noticed `Seek` and `SeekFrom` can almost be moved to `core::io`. Unfortunately, the implementation of `Seek` for `Arc<File>` is a blocker for such a move, since `Arc` is not a fundamental type. This PR attempts to resolve this potential blocker by replacing the implementation with a more general alternative. An internal trait `IoHandle` has been added which types can implement to opt-in to `Read`/`Write`/`Seek` implementations for `Arc<Self>` as long as `&Self` implements said trait. Note that `BufRead` is excluded as the signature for `fill_buf` would require returning from a temporary.
Since this "blanket" implementation only applies to a single type which already implements the same traits, I believe this should have no user-facing impact.
If this PR was merged, rust-lang/rust#134190 could be replaced with a 2 line PR:
```rust
impl IoHandle for TcpStream {}
impl IoHandle for UnixStream {}
```
Likewise for any other types, a table of which can be found [here](https://github.com/rust-lang/libs-team/issues/504#issuecomment-2539569736). This is out of scope for this PR to avoid the need for an ACP.
---
## Notes
* See [this comment](https://github.com/rust-lang/rust/issues/154046#issuecomment-4303975612) for further details.
* No AI tooling of any kind was used during the creation of this PR.
Added a marker trait `IoHandle` which can be used by the standard library to opt-in types to a blanket implementation of the various IO traits on `Arc<T>` where `&T: IoTrait` for some `IoTrait`.
The marker is required to avoid types like `Arc<[u8]>` being included, since they don't have interior mutability and would not give expected results.
Fix classify_union to return Union for regular unions
Commit 623c7d7c4b accidentally changed the return value from REGULAR_UNION to RegularEnum when converting string literals to enum values. Commit b17670d3de then renamed RegularUnion to Union, but the buggy return statement remained unchanged. This caused unions to be misclassified as enums, preventing LLDB from displaying union field contents.
Fix array template arg lookup behavior
Minor logic error. `get_template_args` expects a matching `<`/`>` pair. We were passing in an array type with the beginning `<` removed, so the template arg behavior would fail.
Add docs about SDKs and C compilation on armv7a-vex-v5
This PR expands the documentation for armv7a-vex-v5 to fix broken links, add more information about SDKs, and create a new section about C compilation.
I'm not super familiar with how Rust chooses what linker configuration to use / how the `cc` crate chooses what compiler to use - is this configuration to make C compilation work usually something that would be included in the compiler itself? Either way, it requires a lot of extra work which is kind of unfortunate (downloading a separate compiler, adding it to path, setting up a bunch of environment variables, and making a cargo config for linking).
c-variadic: fix for sparc64
tracking issue: https://github.com/rust-lang/rust/issues/44930
Turns out it's a big-endian target that right-adjusts values in the stack slots.
Apparently these tests do get run occasionally, though i don't think test failures are usually turned into issues on this repo. I guess we could add an assembly test here too, though really you just have to run these tests. I've tried this locally with qemu, and it passes all c-variadic tests.
cc @thejpster @glaubitz
r? tgross35
Emscripten and OpenBSD exit out of the build script early. Since
02014b06c1a3 ("c-b: Turn `mem-unaligned` from a feature to a cfg"), this
meant that the exit happened before all `rustc-check-cfg`s had been
emitted.
Rework the logic so these only skip the C build rather than the rest of
configuration.
There are a number of things I dislike about `CrateMetadataRef`.
- It contains two fields `cstore` and `cdata`. The latter points to data
within the former. It's like having an `Elem` type that has a
reference to a vec element and also a reference to the vec itself.
Weird.
- The `cdata` field gets a lot of use, and the `Deref` impl just derefs
that field. The `cstore` field is rarely used.
- `CrateMetadataRef` is not a good name.
- Variables named `cdata` sometimes refer to values of this type and
sometimes to values of type `CrateMetadata`, which is confusing.
The good news is that `CrateMetadataRef` is not necessary and can be
replaced with `&CrateMetadata`. Why? Everywhere that `CrateMetadataRef`
is used, a `TyCtxt` is also present, and the `CStore` is accessible from
the `TyCtxt` with `CStore::from_tcx`.
So this commit removes `CrateMetadataRef` and replaces all its uses with
`&CrateMetadata`. Notes:
- This requires adding only two uses of `CStore::from_tcx`, which shows
how rarely the `cstore` field was used.
- `get_crate_data` now matches `get_crate_data_mut` more closely.
- A few variables are renamed for consistency, e.g. `data`/`cmeta` ->
`cdata`.
- An unnecessary local variable (`local_cdata`) in `decode_expn_id` is
removed.
- All the `CrateMetadataRef` methods become `CrateMetadata` methods, and
their receiver changes from `self` to `&self`.
- `RawDefId::decode_from_cdata` is inlined and removed, because it has a
single call site.
Simplify `Config::track_state`.
This is a callback used to track otherwise untracked state. It was added in rust-lang/rust#116731 for Clippy. (It was originally named `hash_untracked_state`, and examples in the rustc-dev-guide still use that name.) The `StableHasher` argument is unused, and probably has never been used. There is a FIXME comment pointing this out, which was added more than a year ago.
This commit removes the `StableHasher` callback argument. This also removes the need for `Options::untracked_state_hash`.
r? @bjorn3
Over time the landscape for myself has changed, and I no longer would
like to be officially listed as a maintainer of this target in Rust, so
I'm going to step down. There are still a number of others listed on
this target, however, so I'm sure they can address issues should they
come up.
Some architectures, such as RISC-V and LoongArch, lack support for
native byte-sized atomic operations, so weak operations fallback to
non-weak operations and are actually emulated by LL/SC loop, which never
fail.
Rollup of 7 pull requests
Successful merges:
- rust-lang/rust#155469 (Account for titlecase in casing lints)
- rust-lang/rust#155644 (delegation: support self ty propagation for functions in free to trait reuse)
- rust-lang/rust#154957 (Fix ICE when const closure appears inside a non-const trait method)
- rust-lang/rust#155442 (Change keyword order for `impl` restrictions)
- rust-lang/rust#155561 (Use singular wording for single _ placeholders in type suggestions)
- rust-lang/rust#155637 (Fix E0191 suggestion for empty dyn trait args)
- rust-lang/rust#155661 (Remove `AttributeLintKind` variants - part 6)
Change keyword order for `impl` restrictions
Based on rust-lang/rust#155222, this PR reorders keywords in trait definitions to group restrictions with visibility. It changes the order from `pub(...) const unsafe auto impl(...) trait Foo {...}` to `pub(...) impl(...) const unsafe auto trait Foo {...}`.
Tracking issue for restrictions: rust-lang/rust#105077
r? @Urgau
cc @jhpratt
Fix ICE when const closure appears inside a non-const trait method
Fixesrust-lang/rust#153891
`hir_body_const_context()` unconditionally delegated to the parent's const context for const closures, returning `None` when the parent had no const context. This caused `mir_const_qualif()` to hit a `span_bug!`, since `mir_promoted()` had already decided to call it based on the closure's own syntactic constness. Fall back to `ConstContext::ConstFn` when the parent's const context is `None`, so that the const closure body is still properly const-checked rather than triggering an ICE.
Examining [another attempt](https://github.com/rust-lang/rust/pull/153900/changes) at this issue (which has already been closed), I thought that its approach represents a workaround fix to avoid inconsistencies in the caller of `mir_promoted()`, whereas I think the correct behavior is for `hir_body_const_context()` itself to return the proper value.
delegation: support self ty propagation for functions in free to trait reuse
This PR adds support for self types specified in free to trait reuse. Up to this point we always generated `Self` despite the fact whether self type was specified or not. Now we use it in signature inheritance. Moreover we no more generate `Self` for static methods. Part of rust-lang/rust#118212.
```rust
trait Trait<T> {
fn foo<const B: bool>(&self) {}
fn bar() {}
}
impl<T> Trait<T> for usize {}
reuse <usize as Trait>::foo;
// Desugaring (no `Self` as usize is specified)
fn foo<T, const B: bool>(self: &usize) {
<usize as Trait::<T>>::foo::<B>(self)
}
reuse Trait::bar;
// Desugaring (no `Self` as static method)
fn bar<T>() {
Trait::<T>::bar(); //~ERROR: type annotations needed
}
```
r? @petrochenkov
Streamline `CrateMetadataRef` construction in `provide_one!`.
`cstore.get_crate_data()` creates a `CrateMetadataRef`, which is exactly what we need. The current code is very confused and does several unnecessary things: mapping the `FreezeReadGuard` and calling `CStore::from_tcx` a second time to construct a second `CrateMetadataRef`.
This is a small perf win.
r? @mu001999
Commit 623c7d7c4b accidentally changed the return value from
REGULAR_UNION to RegularEnum when converting string literals
to enum values. Commit b17670d3de then renamed RegularUnion
to Union, but the buggy return statement remained unchanged.
This caused unions to be misclassified as enums, preventing
LLDB from displaying union field contents.
Since call destinations are evaluated after call arguments, we can't
turn copy arguments into moves if the same local is later used as an
index projection in the call destination.
rustc_llvm: update opt-level handling for LLVM 23
LLVM 23 removed Os and Oz optimization pipelines and the PR says to use O2 with optsize or minsize instead as appropriate.
See https://github.com/llvm/llvm-project/pull/191363 for more details.
Expand `Path::is_empty` docs
Give some reasons why you might want to check if a path is empty. The `Path::join` behaviour can be surprising if you're not aware it might happen.
Remove non-working code for "running" mir-opt tests
Tests in `tests/mir-opt` always use `--emit=mir`, so the compiler doesn't even produce an executable.
Attempting to "run" these tests (e.g. with `./x test mir-opt --pass=run`) therefore fails when the OS notices that a MIR text file is not executable.
---
The second commit performs some semi-related cleanup.
r? jieyouxu
Make `//@ skip-filecheck` a normal compiletest directive
The `skip-filecheck` directive is currently used by mir-opt tests, to suppress the default behaviour of running LLVM's `FileCheck` tool to check MIR output against FileCheck rules in the test file.
The `skip-filecheck` directive was not included in the big migration to `//@` directive syntax (https://github.com/rust-lang/rust/pull/121370), perhaps because it was parsed and processed in the *miropt-test-tools* helper crate, not in compiletest itself.
Recently I noticed that a small number of *codegen-llvm* tests were using the `//@ build-pass` directive, which has the non-obvious effect of skipping FileCheck in codegen tests. That's quite confusing, so I decided to have the mir-opt tests migrate over to a proper `//@ skip-filecheck` directive, which could then be used by codegen tests as well.
(I also added skip-filecheck support to assembly tests, which are very similar to codegen tests, though there are currently no assembly tests that actually use `//@ skip-filecheck`.)
---
Support for using `//@ build-pass` in codegen tests to skip FileCheck was introduced in https://github.com/rust-lang/rust/pull/113603. With hindsight, I think doing things that way was pretty clearly a mistake, and we'll be better off with `//@ skip-filecheck`.
r? jieyouxu
Mark a function only used in nightly as nightly only
If you run `./x.py test rustc_next_trait_solver` you'll currently see a failure:
```
warning: method `merge` is never used
--> compiler/rustc_abi/src/callconv.rs:38:8
|
25 | impl HomogeneousAggregate {
| ------------------------- method in this implementation
...
38 | fn merge(self, other: HomogeneousAggregate) -> Result<HomogeneousAggregate, Heterogeneous> {
| ^^^^^
|
= note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default
warning: `rustc_abi` (lib) generated 1 warning
```
This is because the usages are behind a nightly feature flag:
fda6d37bb8/compiler/rustc_abi/src/callconv.rs (L52)fda6d37bb8/compiler/rustc_abi/src/callconv.rs (L131)fda6d37bb8/compiler/rustc_abi/src/callconv.rs (L167)
This does the flag off.
Test on `main` and this branch:
```
./x.py test rustc_next_trait_solver
```
Improved assumptions relating to isqrt
Improved various assumptions relating to values yielded by `isqrt`.
Does not solve but does improve rust-lang/rust#132763.
Re-openeing of rust-lang/rust#154115
Added assumptions are:
* if `x` is nonzero then `x.isqrt()` is nonzero
* `x.isqrt() <= x`
* `x.isqrt() * x.isqrt() <= x`
rustc_thread_pool: Make `CoreLatch::set` use `SeqCst` instead of `AcqRel`
Every other modification of this variable uses `SeqCst`, which is justified in the sleep README. This particular choice of `AcqRel` was not discussed during its addition in rayon-rs/rayon#746, nor rayon-rs/rfcs#5, so I suspect was simply an oversight from earlier development. We probably do want this to participate in the same sequential consistency.
The only other ordering difference is `CoreLatch::probe`'s load with `Acquire`, which should be fine because this doesn't need consistency with the sleep counters.
See also rayon-rs/rayon#1297. As I commented there, I think in practice this would be quite rare to cause any problems, but it *could* be a source of non-deterministic bugs on targets with weak memory ordering.
This is a callback used to track otherwise untracked state. It was added
in #116731 for Clippy. (It was originally named `hash_untracked_state`,
and examples in the rustc-dev-guide still use that name.) The
`StableHasher` argument is unused, and probably has never been used.
There is a FIXME comment pointing this out, which was added more than a
year ago.
This commit removes the `StableHasher` callback argument. This also
removes the need for `Options::untracked_state_hash`.
Update to wasi-sdk-32 in CI/releases
Similar to prior updates such as rust-lang/rust#149037. This notably pulls in some bug fixes for wasi-libc around nonblocking I/O and networking.
Replace `ShardedHashMap` method `insert` with debug-checked `insert_unique`
Currently every use of `ShardedHashMap::insert` checks that it won't evict an old value due to unique key. I haven't found any issue related to that faulty condition, so I thought of replacing it with `ShardedHashMap::insert_unique` which doesn't check for this condition unless `debug_assertions` are enabled. This might improve the performance.
r? @petrochenkov
BinOpAssign always returns unit
I don't know why we treated assign ops as returning their binop type sometimes, but it's usually ignored later anyway and mostly affects infer vars.
Also updated a comment from 11 years ago when SIMD types apparently had builtin `==` logic.
Immediately feed visibility on DefId creation
This system was originally introduced in rust-lang/rust#121089
This PR was enabled by refactorings in rust-lang/rust#154945, because after that, the visibility feeding happens directly after the `DefId` creation, so we don't need to go through the intermediate hash table anymore
Should unblock rust-lang/rust#138995
Remove `nodes_in_current_session` field and related assertions
This removes the `nodes_in_current_session` field and related assertions. These are enabled if `-Z incremental-verify-ich` is passed or `debug_assertions` is on. Historically these have been useful to catch query keys with improper `HashStable` impls which lead to collisions.
We currently also check for duplicate nodes when loading the dep graph. This check is more complete as it covers the entire dep graph and is enabled by default. It doesn't provide a query key for a collision however. This check is also delayed to the next incremental session.
We also have the `verify_query_key_hashes` which is also enabled if `-Z incremental-verify-ich` is passed or `debug_assertions` is on. This checks for dep node conflicts in each query cache and provides 2 conflicting keys if present.
I think these remaining checks are sufficient and so we can remove `nodes_in_current_session`.
Document precision considerations of `Duration`-float methods
A `Duration` is essentially a 94-bit value (64-bit sec and ~30-bit ns),
so there's some inherent loss when converting to floating-point for
`mul_f64` and `div_f64`. We could go to greater lengths to compute these
with more accuracy, like rust-lang/rust#150933 or rust-lang/rust#154107,
but it's not clear that it's worth the effort. The least we can do is
document that some rounding is to be expected, which this commit does
with simple examples that only multiply or divide by `1.0`.
This also changes the `f32` methods to just forward to `f64`, so we keep
more of that duration precision, as the range is otherwise much more
limited there.
codegen: Copy to an alloca when the argument is neither by-val nor by-move for indirect pointer.
Fixes https://github.com/rust-lang/rust/issues/155241.
When a value is passed via an indirect pointer, the value needs to be copied to a new alloca. For x86_64-unknown-linux-gnu, `Thing` is the case:
```rust
#[derive(Clone, Copy)]
struct Thing(usize, usize, usize);
pub fn foo() {
let thing = Thing(0, 0, 0);
bar(thing);
assert_eq!(thing.0, 0);
}
#[inline(never)]
#[unsafe(no_mangle)]
pub fn bar(mut thing: Thing) {
thing.0 = 1;
}
```
Before passing the thing to the bar function, the thing needs to be copied to an alloca that is passed to bar.
```llvm
%0 = alloca [24 x i8], align 8
call void @llvm.memcpy.p0.p0.i64(ptr align 8 %0, ptr align 8 %thing, i64 24, i1 false)
call void @bar(ptr %0)
```
This patch applies the rule to the untupled arguments as well.
```rust
#![feature(fn_traits)]
#[derive(Clone, Copy)]
struct Thing(usize, usize, usize);
#[inline(never)]
#[unsafe(no_mangle)]
pub fn foo() {
let thing = (Thing(0, 0, 0),);
(|mut thing: Thing| {
thing.0 = 1;
}).call(thing);
assert_eq!(thing.0.0, 0);
}
```
For this case, this patch changes from
```llvm
; call example::foo::{closure#0}
call void @_RNCNvCs15qdZVLwHPA_7example3foo0B3_(ptr ..., ptr %thing)
```
to
```llvm
%0 = alloca [24 x i8], align 8
call void @llvm.memcpy.p0.p0.i64(ptr align 8 %0, ptr align 8 %thing, i64 24, i1 false)
; call example::foo::{closure#0}
call void @_RNCNvCs15qdZVLwHPA_7example3foo0B3_(ptr ..., ptr %0)
```
However, the same rule cannot be applied to tail calls that would be unsound, because the caller's stack frame is overwritten by the callee's stack frame. Fortunately, https://github.com/rust-lang/rust/pull/151143 has already handled the special case. We must not copy again.
No copy is needed for by-move arguments, because the argument is passed to the called "in-place".
No copy is also needed for by-val arguments, because the attribute implies that a hidden copy of the pointee is made between the caller and the callee.
NOTE: The patch has a trick for tail calls that we pass by-move. We can choose to copy an alloca even for by-move arguments, but tail calls require MUST-by-move.
This argument is only used to inhibit `#![allow(unused)]` for `//@ run-pass` UI
tests.
No callers actually need to override this value, even when doing unusual
things, so we can just look it up inside the method body instead.
Tests in `tests/mir-opt` always use `--emit=mir`, so the compiler doesn't even
produce an executable.
Attempting to "run" these tests (e.g. with `./x test mir-opt --pass=run`)
therefore fails when the OS notices that a MIR text file is not executable.
Skipping FileCheck in codegen/assembly tests is normally not very useful, but a
small number of existing tests were using `//@ build-pass` to do so anyway, so
it's clearer for them to explicitly use `//@ skip-filecheck` instead.
we were saying that the type is i32, but would often provide an i64.
That never failed so far, but starts failing (like, crashing LLVM) when
working with 128-bit values that are 16-byte aligned. So, we may as well
use the more robust approach now.
Rollup of 7 pull requests
Successful merges:
- rust-lang/rust#155589 (Forbid `check-pass`/`build-pass`/`run-pass` directives in incremental tests)
- rust-lang/rust#155610 (Add missing `dyn` keyword to `trait_alias` page of the Unstable Book)
- rust-lang/rust#155615 (test cleanups for `ui/derives` and `ui/deriving`)
- rust-lang/rust#154874 (Fix ICE for inherited const conditions on const closures)
- rust-lang/rust#155605 (std: Update support for `wasm32-wasip3`)
- rust-lang/rust#155613 (c-variadic: tweak `std` docs)
- rust-lang/rust#155619 (Remove a bunch of unnecessary explicit lifetimes from the ast validator)
Remove a bunch of unnecessary explicit lifetimes from the ast validator
Noticed while fiddling with error reporting. None of the lifetimes were ever used for anything
std: Update support for `wasm32-wasip3`
This commit performs some minor update within the standard library for the `wasm32-wasip3` target. This target is a tier 3 target currently due to the WASIp3 specification not being officially released. This commit adds a dependency from the standard library on the `wasip3` crate in the same manner as the `wasip1` and `wasip2` crates that it already depends on. The use-sites, for randomness and environment variables, are then updated to handle the wasip2/wasip3 multiplexing.
Fix ICE for inherited const conditions on const closures
Synchronize `evaluate_host_effect_for_fn_goal` with the behavior of `extract_fn_def_from_const_callable` in new solver.
Closesrust-lang/rust#153861 .
test cleanups for `ui/derives` and `ui/deriving`
The eventual goal is for `ui/deriving` to be merged into `ui/derives` entirely. This PR focuses on the `issue-*.rs` tests in `deriving` and a few other no-longer-useful tests.
r? @Kivooeo
Add missing `dyn` keyword to `trait_alias` page of the Unstable Book
There seemed to be a small typo in the Rust Unstable Book page for the `trait_alias` feature, where a variable is declared as `&Bar` for a trait `Bar`, rather than `&dyn Bar`.
Forbid `check-pass`/`build-pass`/`run-pass` directives in incremental tests
- Follow-up to https://github.com/rust-lang/rust/pull/155474
---
This PR forbids the use of `//@ check-pass`, `//@ build-pass`, and `//@ run-pass` directives in incremental tests. Tests that would have used those directives should use a revision name beginning with `cpass`/`bpass`/`rpass` instead.
(The `*-fail` directives are already forbidden in incremental tests.)
Existing incremental tests that used the `check-pass` and `build-pass` directives have been migrated. To allow migration of the check-pass tests, this PR also adds support for revision names beginning with `cpass`. No incremental tests were using `run-pass`.
---
Several of the migrated `build-pass` tests have a FIXME indicating that they could potentially be migrated to `check-pass` instead. This PR does not perform that migration.
In the future, I intend to do more cleanup of how compiletest handles pass/fail expectations, but I didn't want to cram too much into one PR.
r? jieyouxu
It's currently an impl for `(CrateMetadataRef, TyCtxt)`, but (a) the
`TyCtxt` is not used, and (b) the `CrateMetadataRef` can be simplified
to a `CrateMetadata` because `CStore` access isn't required. This
require changing `blob` to take `&self`, which is no big deal, and it
simplifies many `get` calls.
`Metadata` has two methods, `blob` and `decoder`, which are not used
together. Splitting the trait in two will allow some cleanups in
subsequent commits.
Incremental tests that would have used the `check-pass`, `build-pass`, or
`run-pass` directives should instead use a revision name starting with
`cpass`/`bpass`/`rpass` as appropriate.
This is the subset of incremental tests that have a FIXME to consider migrating
to check-pass instead.
That migration is beyond the scope of this PR, but might be attempted later.
This is the subset of incremental tests that should continue to use `bpass`
even after `cpass` is supported, because they (presumably) involve codegen.
`cstore.get_crate_data()` creates a `CrateMetadataRef`, which is exactly
what we need. The current code is very confused and does several
unnecessary things: mapping the `FreezeReadGuard` and calling
`CStore::from_tcx` a second time to construct a second
`CrateMetadataRef`.
This is a small perf win.
Use per-parent disambiguators everywhere
This PR addressing the following concerns about per-parent disambiguators (rust-lang/rust#153955):
- DisambiguatorState is removed, PerParentDisambiguatorState is now used everywhere,
- Steals were removed from every per-parent disambiguator in resolver,
- It adds `parent` field in `PerParentDisambiguatorState` in `#[cfg(debug_assertions)]` for asserting that per-parent disambiguator corresponds to the same `LocalDefId` which is passed into `create_def`,
- ~Removes `Disambiguator` trait replacing it with `Disambiguator` enum, with this change we no longer expose `next` method (as trait should be public otherwise the warning will be emitted). It may affect perf in a negative way though.~
~Those changes should not fix perf issues that were [reported](https://github.com/rust-lang/rust/pull/153955#issuecomment-4269223191), perf run that was attempted [before](https://github.com/rust-lang/rust/pull/153955#issuecomment-4214516698) showed much better results. Performance can be probably fixed by removing per-parent disambiguators replacing them with a single one as it was before, then it will be passed to AST -> HIR lowering and modified. For delayed owners we can store ~followup disambiguators as it was in the beginning of the rust-lang/rust#153955~ per-parent disambiguators. This solution should save achievements from rust-lang/rust#153955 (removed `DefPathData` variants).
However, I would prefer to keep per-parent disambiguators as it seems a better architectural solution for me.~
r? @petrochenkov
cc @oli-obk
Remove duplicated `Flags` methods.
The `Flags` trait has two methods: `flags` and `outer_exclusive_binder`. Multiple types impl this trait and then also have duplicate inherent methods with the same names; these are all marked with "Think about removing this" comments. This is left over from things being moved into `rustc_type_ir`.
This commit removes those inherent methods. This requires adding `use Flags` to a number of files.
r? @lcnr
Fix incorrect `let` to `const` suggestion for pattern bindings
When a variable from a pattern binding was referenced inside a `const {}` block, the compiler incorrectly suggested replacing `let` with `const`. This was reported in rust-lang/rust#152831 for `if let`, but also applies to `while let` and `let ... else`.
Improve E0308 error message for `impl Trait` return mismatches
When a function returns `impl Trait`, all branches must return the same concrete type. Previously, the compiler showed:
expected `First` because of return type
This was misleading, as it suggested the return type was `First`, rather than any single type implementing the trait.
Update the diagnostic to:
expected a single type implementing `Value` because of return type
Also highlight the first return expression to make it clearer why subsequent returns do not match.
Every other modification of this variable uses `SeqCst`, which is
justified in the sleep README. This particular choice of `AcqRel` was
not discussed during its addition in rayon-rs/rayon#746, nor
rayon-rs/rfcs#5, so I suspect was simply an oversight from earlier
development. We probably do want this to participate in the same
sequential consistency.
The only other ordering difference is `CoreLatch::probe`'s load with
`Acquire`, which should be fine because this doesn't need consistency
with the sleep counters.
See also rayon-rs/rayon#1297. As I commented there, I think in practice
this would be quite rare to cause any problems, but it *could* be a
source of non-deterministic bugs on targets with weak memory ordering.
Rollup of 4 pull requests
Successful merges:
- rust-lang/rust#152611 (Modify error message of importing inherent associated items when `#[feature(import_trait_associated_functions)]` is enabled)
- rust-lang/rust#155359 (Improperctypes refactor2.2)
- rust-lang/rust#155036 (Store a PathBuf rather than SerializedModule for cached modules)
- rust-lang/rust#155554 (add warning message when using x fix)
This commit performs some minor update within the standard library for
the `wasm32-wasip3` target. This target is a tier 3 target currently due
to the WASIp3 specification not being officially released. This commit
adds a dependency from the standard library on the `wasip3` crate in the
same manner as the `wasip1` and `wasip2` crates that it already depends
on. The use-sites, for randomness and environment variables, are then
updated to handle the wasip2/wasip3 multiplexing.
Store a PathBuf rather than SerializedModule for cached modules
In cg_gcc `ModuleBuffer` already only contains a path anyway. And for moving LTO into `-Zlink-only` we will need to serialize `MaybeLtoModules`. By storing a path cached modules we avoid writing them to the disk a second time during serialization of `MaybeLtoModules`.
Some further improvements will require changes to cg_gcc that I would prefer landing in the cg_gcc repo to actually test the LTO changes in CI.
Part of https://github.com/rust-lang/compiler-team/issues/908
Improperctypes refactor2.2
This is "part 2/3 of 2/3 of 1/2" of the original pull request https://github.com/rust-lang/rust/pull/134697 (refactor plus overhaul of the ImproperCTypes family of lints)
(all pulls of this series of pulls are supersets of the previous pulls.)
previous pull: https://github.com/rust-lang/rust/pull/155358
next pull: https://github.com/rust-lang/rust/pull/146273
This commit splits the lint's `visit_type` function into multiple functions that focus on specific things:
- visit_indirection (references, boxes, raw pointers)
- visit_variant_fields (the list of fields of a struct, enum variant, or union)
- visit_enum
- visit_struct_or_union
- visit_type (most "easy" decisions such as labeling `char` unsafe are here)
since, during these visits, we often move from an "outer type" to an "inner type" (structs, arrays, pointers, etc...),
two structs have been added to track the current state of a visit:
- VisitorState tracks the state related to the "original type" being checked (function argument/return, static variable)
- OuterTyData tracks the data related to the type "immediately outer to the current visited type"
r? petrochenkov (because you asked me to)
Modify error message of importing inherent associated items when `#[feature(import_trait_associated_functions)]` is enabled
Fixesrust-lang/rust#148009
This PR improves the diagnostic for importing inherent associated items from a struct or union when
`#[feature(import_trait_associated_functions)]` (rust-lang/rust#134691) is enabled.
Previously, this would result in a "not a module" error. This change provides a more specific error message clarifying that only trait associated items can be imported, while inherent associated items remain ineligible for import.
Enums are currently excluded from this change because their variants are valid import targets and require distinct handling.
Add SanitizerSet::ADDRESS to the supported_sanitizers for the
arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf targets.
The AddressSanitizer is already enabled on the armv7-linux-androideabi
platform, which shares the same ARM architecture. There is no reason
these Linux GNU targets should not also support it, as the underlying
LLVM support for ASan on 32-bit ARM is already in place.
Another interal change that shouldn't impact rustc users.
Code called outside of `visit_type` (and callees) is moved inside, by
adding new types to properly track the state of a type visitation.
- OuterTyKind tracks the knowledge of the type "directly outside of" the
one being visited (if we are visiting a struct's field, an array's
element, etc)
- RootUseFlags tracks the knowledge of how the "original type being
visited" is used: static variable, function argument/return, etc.
Ensure we don't feed owners from ast lowering if we ever make that query tracked
follow-up to rust-lang/rust#153489
I don't expect this to ever really be an issue, but better safe than sorry 😆
Move diagnostic attribute target checks from check_attr
Move diagnostic attribute target checks into their targets. Part of https://github.com/rust-lang/rust/issues/131229#issuecomment-3959910413
This is much easier with `emit_dyn_lint` :) (thanks @GuillaumeGomez !)
I think there might be some opportunity to simplify all these `check_diagnostic_*` methods in `check_attr`. However there are some diagnostic attribute prs in flight and I'd like to wait for those to land first and then think about it. So that PR is not for today.
r? @JonathanBrouwer (or @GuillaumeGomez if you want)
Fix `#[expect(dead_code)]` liveness propagation
Fixes https://github.com/rust-lang/rust/issues/154324
Fixes https://github.com/rust-lang/rust/issues/152370 (cc @eggyal)
Previously, when traversing from a `ComesFromAllowExpect::Yes` item (i.e., with `#[allow(dead_code)]` or `#[expect(dead_code)]`), other `ComesFromAllowExpect::Yes` items reached during propagation would be updated to `ComesFromAllowExpect::No` and inserted into `live_symbols`. That caused `dead_code` lint couldn't be emitted correctly.
After this PR, `ComesFromAllowExpect::Yes` items no longer incorrectly update other `ComesFromAllowExpect::Yes` items during propagation or mark them live by mistake, then `dead_code` lint could behave as expected.
Rewrite `FlatMapInPlace`.
Replace the hacky macro with a generic function and a new `FlatMapInPlaceVec` trait. More verbose but more readable and typical.
LLM disclosure: I asked Claude Code to critique this file and it suggested the generic function + trait idea. I implemented the idea entirely by hand.
r? @chenyukang
tests: add whitespace tests for vertical tab behavior
This PR adds two small tests to highlight how vertical tab (\x0B)
is handled differently across Rust's whitespace definitions.
The Rust lexer treats vertical tab as whitespace (Unicode
Pattern_White_Space), while `split_ascii_whitespace` follows the
WhatWG Infra Standard and does not include vertical tab.
These tests make that difference visible and easier to understand.
See: https://github.com/rustfoundation/interop-initiative/issues/53
* tests: add whitespace tests for vertical tab behavior
Add two small tests to highlight how vertical tab is handled differently.
- vertical_tab_lexer.rs checks that the lexer treats vertical tab as whitespace
- ascii_whitespace_excludes_vertical_tab.rs shows that split_ascii_whitespace does not split on it
This helps document the difference between the Rust parser (which accepts vertical tab)
and the standard library’s ASCII whitespace handling.
See: rust-lang/rust-project-goals#53
* tests: add ignore-tidy-tab directive to whitespace tests
* tests: expand vertical tab lexer test to cover all Pattern_White_Space chars
* tests: add whitespace/ README entry explaining lexer vs stdlib mismatch
* Update ascii_whitespace_excludes_vertical_tab.rs
* Update ascii_whitespace_excludes_vertical_tab.rs
make sure tabs and spaces are well checked
* Update ascii_whitespace_excludes_vertical_tab.rs
* fix tidy: add whitespace README entry
* Update README.md with missing full stop
* Update ascii_whitespace_excludes_vertical_tab.rs
* fix tidy: use full path format for whitespace README entry
* fix tidy: README order, trailing newlines in whitespace tests
* fix: add run-pass directive and restore embedded whitespace bytes
* fix tidy: remove duplicate whitespace README entry
*
Add failing UI test for invalid whitespace (zero width space)
This adds a //@ check-fail test to ensure that disallowed whitespace
characters like ZERO WIDTH SPACE are rejected by the Rust lexer.
* git add tests/ui/whitespace/invalid_whitespace.rs
git commit -m "Fix tidy: add trailing newline"
git push
* Fix tidy: add trailing newline
* Update invalid_whitespace.rs
* Update invalid_whitespace.rs
* Clean up whitespace in invalid_whitespace.rs
Remove unnecessary blank lines in invalid_whitespace.rs
* Update invalid_whitespace.rs
* Clarify ZERO WIDTH SPACE usage in test
Update comment to clarify usage of ZERO WIDTH SPACE.
* Improve error messages for invalid whitespace
Updated error messages to clarify the issue with invisible characters.
* Modify invalid_whitespace test for clarity
Update test to check for invalid whitespace characters.
* Resolve unknown token error in invalid_whitespace.rs
Fix whitespace issue causing unknown token error.
* Remove invisible character from variable assignment
Fix invisible character issue in variable assignment.
* Improve error message for invalid whitespace
Updated error message to clarify invisible characters.
* Improve error handling for invisible characters
Updated error message for invisible characters in code.
* Document error for unknown token due to whitespace
Add error message for invalid whitespace in code
* Update error message for invalid whitespace handling
* Modify invalid_whitespace.rs for whitespace checks
Updated the test to check for invalid whitespace handling.
* Correct whitespace in variable declaration
Fix formatting issue by adding space around '=' in variable declaration.
* Update error message for invalid whitespace
* Update invalid_whitespace.stderr
* Refine error handling for invalid whitespace test
Update the error messages for invalid whitespace in the test.
* Update invalid_whitespace.rs
* Fix whitespace issues in invalid_whitespace.rs
* Update invalid_whitespace.stderr file
* Clean up whitespace in invalid_whitespace.rs
Removed unnecessary blank lines from the test file.
* Update invalid_whitespace.stderr
Using the reflection experiment, we can print the actual names of the
field that an FRT is referring to. In case this breaks, there is an
alternative implementation in the note comment.
Commit cb37ee2c87 ("make field representing types invariant over the
base type") made the auto-trait impl work even if `T: !Send` or `T:
!Sync` thus we can remove these explicit unsafe impls while FRTs still
implement `Send` and `Sync`.
Fix redundant boolean comparison in `Mutex::try_lock`
Simplify boolean return in `Mutex::try_lock`.
Replace `expr == false` with `!expr` for cleaner code.
Replace the hacky macro with a generic function and a new
`FlatMapInPlaceVec` trait. More verbose but more readable and typical.
LLM disclosure: I asked Claude Code to critique this file and it
suggested the generic function + trait idea. I implemented the idea
entirely by hand.
Fix performance regression introduced in #142531 by excluding `Storage{Live,Dead}` from CGU size estimation
Fix performance regression introduced in rust-lang/rust#142531 ([rust-timer comment](https://github.com/rust-lang/rust/pull/142531#issuecomment-4273712294)) by excluding `Storage{Live,Dead}` from CGU size estimation.
Also, avoid unneeded work for storage removal in non-opt builds in CopyProp and GVN
by allocating local sets for the storage accounting only when `tcx.sess.emit_lifetime_markers()`.
r? saethlin
Update books
## rust-embedded/book
2 commits in 2463edeb8003c5743918b3739a9f6870b86396f5..0789b0f29e73ecb91213cac10ad0eec1b9333770
2026-04-11 08:46:22 UTC to 2026-04-10 14:01:38 UTC
- remove IO chapter, is covered in next chapter (rust-embedded/book#411)
- add embassy chapter (rust-embedded/book#412)
## rust-lang/reference
10 commits in d2715c07e9dd9839c0c7675ecfa18bec539a6ee9..8c88f9d0bdd75ffdc0691676d83212ae22a18cee
2026-04-20 15:20:24 UTC to 2026-04-07 16:25:09 UTC
- typo in example code (rust-lang/reference#2232)
- oxford comma (rust-lang/reference#2233)
- improve readability (rust-lang/reference#2234)
- typo (rust-lang/reference#2230)
- Clarify items.fn.generics.param-bounds (rust-lang/reference#2229)
- follow formatting style guideline (rust-lang/reference#2228)
- Update `derive` export locations (rust-lang/reference#2223)
- Clarify that `{self}` imports require a module parent (rust-lang/reference#2221)
- stabilize s390x vector registers (rust-lang/reference#2215)
- Fix misuse of *usage* throughout the Reference (rust-lang/reference#2222)
## rust-lang/rust-by-example
2 commits in b31e3b8da01eeba0460f86a52a55af82709fadf5..898f0ac1479223d332309e0fce88d44b39927d28
2026-04-19 11:40:28 UTC to 2026-04-19 11:38:45 UTC
- remove debug printing for the u32 and bool in variable_bindings.md (rust-lang/rust-by-example#1999)
- Update for.md (rust-lang/rust-by-example#2008)
Fix LLVM offload install docs to use semicolon-separated CMake lists
Update so the LLVM CMake example uses and , which is the correct list separator syntax for LLVM CMake options.[Docs] Remove shortcode from models page heading
Suggest removing `&` when awaiting a reference to a future
Fixesrust-lang/rust#87211
When `.await`ing `&impl Future`, suggest removing the `&` instead of removing `.await`.
Make E0284 generic argument suggestions more explicit
Closesrust-lang/rust#147313
Previously, when type annotations were missing for a function call, rust suggested: "consider specifying the generic argument". This PR improves the diagnostics:
- If only one generic type is missing:
"consider specifying a concrete type for the generic type `<T>`" with the turbofish being "::\<SomeConcreteType>"
- If only one const generic is missing:
"consider specifying a const for the const generic `<CONST>`" with the turbofish being "::<SOME_CONST>"
Multiple missing generics still produce the original more general suggestion
Merge BuildReducedGraphVisitor into DefPathVisitor
These two visitors run right after each other on the same immutable AST. There's also a hash map for transferring the TyCtxtFeed created in the def collector to the BRG when it visits the same items. There are possibly more avenues for sharing logic, but I want to keep this PR simple.
only opening for perf runs for now. I'm still investigating how to ensure that future changes don't introduce subtle bugs by forgetting that def collection and reduced graph building are one pass now
Best reviewed commit-by-commit. I took a lot of care for making the individual changes reviewable, but all the `Merge *` commits aren't able to compile libcore until the last one.
Another interal change that shouldn't impact rustc users.
This time, regroup into `visit_indirections` the code dealing with the
FFI safety of Boxes, Refs and RawPtrs.
Another interal change that shouldn't impact rustc users.
the list of simpler type-based decisions made by `visit_type` are
reordered and are given better documentation.
Another interal change that shouldn't impact rustc users.
The goal (of this commit and a few afterwards) is to break apart the gigantic
visit_type function into more managable and easily-editable bits that focus
on specific parts of FFI safety.
For now, we break the code specific to enums one side, and
structs/unions on the other, into separate visit_? methods
Simplify macros for target-modifier and mitigation flags
- Rebased and revised version of https://github.com/rust-lang/rust/pull/154501.
---
The macros used for handling command-line flags that are “target modifiers” or “mitigations” are quite complicated, and can be significantly simplified by tweaking their syntax and by making use of `${ignore(..)}` metavars.
It's possible that more code could be moved out of macros (e.g. declaring some of the enums by hand), but that can be investigated in a potential follow-up.
There should be no change to compiler behaviour.
Suggest returning a reference for unsized place from a closure
Fixesrust-lang/rust#152064
There are 3 similar note:
`the size for values of type str cannot be known at compilation time`
for different spans, maybe need more work to remove some of them.
This PR only adds a suggestion for using a reference.
Rollup of 11 pull requests
Successful merges:
- rust-lang/rust#154654 (Move `std::io::ErrorKind` to `core::io`)
- rust-lang/rust#145270 (Fix an ICE observed with an explicit tail-call in a default trait method)
- rust-lang/rust#154895 (borrowck: Apply `user_arg_index` nomenclature more broadly)
- rust-lang/rust#155213 (resolve: Make sure visibilities of import declarations make sense)
- rust-lang/rust#155346 (`single_use_lifetimes`: respect `anonymous_lifetime_in_impl_trait`)
- rust-lang/rust#155517 (Add a test for Mach-O `#[link_section]` API inherited from LLVM)
- rust-lang/rust#155549 (Remove some unnecessary lifetimes.)
- rust-lang/rust#154248 (resolve : mark repr_simd as internal)
- rust-lang/rust#154772 (slightly optimize the `non-camel-case-types` lint)
- rust-lang/rust#155541 (Add `#[rust_analyzer::prefer_underscore_import]` to the traits in `rustc_type_ir::inherent`)
- rust-lang/rust#155544 (bootstrap: Make "detected modifications" for download-rustc less verbose)
Remove `HashStable` impl for `[hir::Attribute]`.
This impl skips:
- All doc comments
- A handful of other attributes, mostly `rustc_*` ones related to incremental compilation testing.
This skipping originated in rust-lang/rust#36025 and was extended a couple of times, e.g. in rust-lang/rust#36370. Those PRs don't have any explanation of why the skipping exists. Perhaps the reasoning was that doc comments should only affect rustdoc and rustdoc doesn't use incremental compilation? But doc comments end up in metadata, and there is a query `attrs_for_def` that returns a `&'tcx [hir::Attribute]`. So skipping some attributes just seems plainly wrong.
This commit removes the impl, which means `[hir::Attribute]` hashing falls back to the default impl for `[T]`. This has no noticeable effect on the test suite. It does slightly hurt performance, because of the doc comments. This perf regression seems worth it for the correctness benefits.
Add `#[rust_analyzer::prefer_underscore_import]` to the traits in `rustc_type_ir::inherent`
This is a new attribute (https://github.com/rust-lang/rust-analyzer/pull/21740) that instructs rust-analyzer to prefer importing the trait `as _`. It is useful for these traits since their names often clashes with the type.
resolve : mark repr_simd as internal
I changed ```repr_simd``` to ```internal``` and changed the position to ```feature-group-start: internal feature gates```.
closerust-lang/rust#154034
Remove some unnecessary lifetimes.
We have a number of structs with more lifetimes than necessary. This commit removes them.
LLM disclosure: I asked Claude Code to check for unnecessary lifetimes in all types with three or more lifetimes, and it produced a list of candidates (half of which were invalid). I did the modifications for the valid cases myself, and found a couple more cases along the way.
r? @JohnTitor
Add a test for Mach-O `#[link_section]` API inherited from LLVM
The format of the `#[link_section]` attribute is under-documented, but on Mach-O, I think it's roughly the following BNF:
```
LinkSection -> Segment `,` Section (`,` (SectionType (`,` (SectionAttributes)?)?)?)?
Segment -> <0 to 16 bytes>
Section -> <0 to 16 bytes>
SectionType -> `regular` | `zerofill` | `cstring_literals` | `4byte_literals` | `8byte_literals` | `literal_pointers` | `non_lazy_symbol_pointers` | `lazy_symbol_pointers` | `symbol_stubs` | `mod_init_funcs` | `mod_term_funcs` | `coalesced` | `interposing` | `16byte_literals` | `thread_local_regular` | `thread_local_zerofill` | `thread_local_variables` | `thread_local_variable_pointers` | `thread_local_init_function_pointers`
SectionAttributes -> SectionAttribute (`+` SectionAttribute)*
SectionAttribute -> `pure_instructions` | `no_toc` | `strip_static_syms` | `no_dead_strip` | `live_support`, `self_modifying_code` | `debug`
```
This PR adds a small test for a little part of this.
Once https://github.com/rust-lang/rust/issues/154429 is resolved, this should make it possible to test https://github.com/rust-lang/rustc_codegen_cranelift/pull/1648 end-to-end.
r? bjorn3
resolve: Make sure visibilities of import declarations make sense
That they are all ordered inside the module and not more private than the module itself.
The `import_decl_vis` logic is also reused when reporting `ambiguous_import_visibilities` lint.
Some asserts are hardened.
Some relevant tests are added.
Extracted from https://github.com/rust-lang/rust/pull/154149.
Fix an ICE observed with an explicit tail-call in a default trait method
Right now, explicit tail-calls cannot be used in functions that hold the `#[track_caller]` attribute. This check is performed on a resolved concrete instance of a function, which would be absent for a tail-call performed from the body of a default trait method. This PR fixes the issue by checking for the relevant attribute in default trait methods separately, without expecting a specific resolved instance.
Closes https://github.com/rust-lang/rust/issues/144985.
Move `std::io::ErrorKind` to `core::io`
ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: https://github.com/rust-lang/rust/issues/154046
Related: https://github.com/rust-lang/rust/pull/152918
## Description
I consider rust-lang/rust#154046 to be really important for `no_std`, but I'm concerned rust-lang/rust#152918 might be too controversial. As an alternative, I'd like to propose starting small with `ErrorKind`, since it can be moved somewhat trivially. It has no dependencies on functionality in `std`, no platform specific behaviour, and could provide an excellent bridging point for `no_std` IO libraries.
Since `std::io::Error` implements `From<ErrorKind>`, libraries could write functions which return `Result<T, core::io::ErrorKind>`, and therefore be usable in `std`-using libraries with the `?` operator. For that reason, I'd consider this to be a worthwhile change even if the rest of `std::io` couldn't be moved to `core`/`alloc`, and entirely compatible with any efforts to make such a change in the future.
## Notes
* This is my first PR against Rust, please let me know if there's anything I should be doing that I have not done. I tried reading through the library contributors guide but I'm sure I've missed _something_.
* No AI tooling of any kind was used in the creation of this PR.
* I believe it's appropriate that this be a part of the linked tracking issue, but please let me know if that's not the case!
That they are all ordered inside the module and not more private than the module itself
The `import_decl_vis` logic is reused when reporting `ambiguous_import_visibilities` lint
Some asserts are hardened
Some relevant tests are added
The logic determining whether the relevant function is marked as `#[track_caller]`
only worked with functions that could be resolved to a concrete instance, which default
trait methods cannot. We need to check the codegen attribute on the default method itself.
Co-authored-by: Folkert de Vries <folkert@folkertdev.nl>
We have a number of structs with more lifetimes than necessary. This
commit removes them.
LLM disclosure: I asked Claude Code to check for unnecessary lifetimes
in all types with three or more lifetimes, and it produced a list of
candidates (half of which were invalid). I did the modifications for the
valid cases myself, and found a couple more cases along the way.
Move `std::io::ErrorKind` to `core::io`
* Update `rustdoc-html` tests for the new path
* Add `core_io` feature to control stability. This replaces the use of `core_io_borrowed_buf` on the `core::io` module itself.
* Re-export `core::io::ErrorKind` in `std::io::error`
When a function returns `impl Trait`, all branches must return the same
concrete type. Previously, the compiler showed:
expected `First` because of return type
This was misleading, as it suggested the return type was `First`, rather
than any single type implementing the trait.
Update the diagnostic to:
expected a single type implementing `Value` because of return type
Also highlight the first return expression to make it clearer why
subsequent returns do not match.
Signed-off-by: Usman Akinyemi <usmanakinyemi202@gmail.com>
Tweak `is_ascii_punctuation()` docs wording
These methods return `true` for characters with Unicode general category of punctuation (P), but also for those with general category of symbol (S).
@rustbot label A-docs
docs(num): fix stale link to `mem::Alignment`
This pull request updates a stale link to `mem::Alignment` in `num::IntErrorKind`.
In rust-lang/rust#153178, I added a link to `Alignment` in `IntErrorKind`, but I overlooked that `Alignment` had been moved from `core::ptr` to `core::mem`. Although it is still re-exported in `core::ptr`, this pull request points the link to its canonical location.
@rustbot label +A-docs
Rename incremental `cfail`/`cpass` revisions to `bfail`/`bpass`
Long ago, UI tests were divided into *compile* and *run* tests. Later, the compile tests were further subdivided into *check* and *build* tests, to speed up tests that don't need a full build.
The same split was never applied to incremental test revisions, so the only way to perform a check build in incremental tests is (confusingly) to use a `cfail` revision and then specify `//@ check-fail` or `//@ check-pass`.
This PR makes room for dedicated check-fail and check-pass revisions by renaming the existing `cfail` and `cpass` revisions to `bfail` and `bpass`, since they currently perform a full build.
---
The test updates were done with a regex whole-word find-and-replace for `c(fail|pass)(\d*)`, and I also took the opportunity to manually add a space after `revisions:` on affected lines.
r? jieyouxu
compiletest: add a new diff for compare-out-by-lines tests.
Previously, when comparing output by lines, only the actual diff was shown. This is unhelpful since we expect lines to be shuffled around.
With this new print, we can see the exact lines that are missing or have appeared without the noise of the moved around lines.
Example, in this case a note has moved slightly so there is one more separator line "|":
```
+ |
+ = help: maybe it is overwritten before being read?
Compare output by lines enabled, diff by lines:
Expected contains these lines that are not in actual:
(no lines found)
Actual contains these lines that are not in expected:
|
The actual stderr differed from the expected stderr
To update references, rerun the tests and pass the `--bless` flag
To only update this specific test, also pass `--test-args liveness/liveness-consts.rs`
```
r? @jieyouxu
cc @zetanumbers @ywxt
Add autocast support for `x86amx`
Builds on rust-lang/rust#140763 by further adding autocasts for `x86amx` from/to vectors of size 8192 bits.
This also disables SIMD vector abi checks for the `"unadjusted"` abi because
- This is primarily used to link with LLVM intrinsics, which don't actually lower to function calls with vector arguments. Even with other cg backends, this is true.
- This ABI is internal and perma-unstable (and also super specific), so it is very unlikely that this will cause breakages.
- (The primary reason) Without doing this we can't actually use 8192 bit long vectors to represent `x86amx`
> Why do we need a bypass for `x86amx`? Can't we use a `#[lang_item]` or something?
If `x86amx` was a normal LLVM type, this approach would've worked and I would also prefer it. But LLVM specifies that
> No instruction is allowed for this type. There are no arguments, arrays, pointers, vectors or constants of this type.
So we can't treat it like a normal type at all -- even if we add it like a lang-item, we would still have to special-case everywhere to check if we are passing to the correct LLVM intrinsic, and only then use the `x86amx` type. IMO this is needlessly complex, and way worse than this solution, which just adds it to the autocast list in cg_llvm
r? codegen
This is a new attribute that instructs rust-analyzer to prefer importing the trait `as _`. It is useful for these traits
since their names often clashes with the type.
Previously, when comparing output by lines, only the actual
diff was shown. This is unhelpful since we expect lines to be
shuffled around.
With this new print, we can see the exact lines that are missing
or have appeared without the noise of the moved around lines.
This should help speed.
Instead, we do it only when an `Interner` is constructed, since an interner cannot be held across revisions.
There is a problem, though: an interner *can* be held across different databases. To solve that, we also reinit the cache when attaching databases, and take the assumption that everything significant (i.e. that can access the cache) will need to attach the db. This is somewhat risky, but we'll take it for the speed.
Theoretically we could *only* reinit on db attach, but it's less risky this way, and with-crate interner construction is rare.
The `_punctuation` methods return `true` for characters with
Unicode general category of punctuation (P),
but also for those with general category
of symbol (S).
The `Flags` trait has two methods: `flags` and `outer_exclusive_binder`.
Multiple types impl this trait and then also have duplicate inherent
methods with the same names; these are all marked with "Think about
removing this" comments. This is left over from things being moved into
`rustc_type_ir`.
This commit removes those inherent methods. This requires adding `use
Flags` to a number of files.
* Checking exhaustion will no longer be possible for `repr_bitpacked`. Moving `kind_from_prim` into an associated function, and setting it up to be moved into `core::io` as well.
* `ErrorKind::as_str` is private, but it's only usage is trivially replaced with `Display::fmt`
* The features io_error_inprogress, io_error_more, and io_error_uncategorized will all need to be enabled
Introduce `Unnormalized` wrapper
This is the first step of the [eager normalization](https://rust-lang.zulipchat.com/#narrow/channel/364551-t-types.2Ftrait-system-refactor/topic/Eager.20normalization.2C.20ahoy.21/with/582996293) series.
This PR introduce an `Unnormalized` wrapper and make most normalization routines consume it. The purpose is to make normalization explicit.
This PR contains no behavior change.
API changes are in the first two commit.
There're some normalization routines left untouched:
- `normalize` in the type checker of borrowck: better do it together with `field.ty()` returning `Unnormalized`.
- `normalize_with_depth`: only used inside the old solver. Can be done later.
- `query_normalize`: rarely used.
- misc local normalization helpers.
The compiler errors are mostly fixed via `ast-grep`, with exceptions handled manually.
Update so the LLVM
CMake example uses and , which is the
correct list separator syntax for LLVM CMake options.[Docs] Remove shortcode from models page heading
libtest: use binary search for --exact test filtering
When `--exact` is passed in, use binary search for O(f log n) lookups instead of an O(n) linear scan, under the assumption that f << n (which is true for the most relevant cases).
This is important for Miri, where the interpreted execution makes the linear scan very expensive.
I measured this against a repo with 1000 empty tests, running `cargo +stage1 miri nextest run test_00` (100 tests) under hyperfine:
* Before (linear scan): 49.7s ± 0.6s
* After (binary search): 41.9s ± 0.2s (-15.7%)
I also tried a few other variations (particularly swapping matching tests to the front of the list + truncating the list), but the index + swap_remove approach proved to be the fastest.
Questions:
- [ ] To be conservative, I've assumed that test_main can potentially receive an unsorted list of tests. Is this assumption correct?
deprecate `std::char` constants and functions
similar to how constants in those modules for numeric types have been deprecated. The `std::char` module contains:
Three stable constants that this PR deprecates. These already link to their associated constant equivalents.
- `MAX`
- `REPLACEMENT_CHARACTER`
- `UNICODE_VERSION`
two unstable constants that this PR removes. The constants are already stablized as associated constants on `char`.
- `MAX_LEN_UTF8`
- `MAX_LEN_UTF16`
Four stable functions that this PR deprecates. These already link to their method equivalents.
- `fn decode_utf16`
- `fn from_digit`
- `fn from_u32`
- `fn from_u32_unchecked⚠`
discussion at [#t-libs > should `std::char::{MIN, MAX}` be deprecated?](https://rust-lang.zulipchat.com/#narrow/channel/219381-t-libs/topic/should.20.60std.3A.3Achar.3A.3A.7BMIN.2C.20MAX.7D.60.20be.20deprecated.3F/with/579444750).
r? libs-api
triagebot.toml: Sync `assign.owners` with `autolabel."T-compiler"`
In `autolabel."T-compiler"`, several `./tests/*` dirs are listed.
But many of them are missing from `assign.owners`. Add them all to `assign.owners` so reviewers are picked from the compiler group, and not from the small `assign.adhoc_groups.fallback` group.
Discovered in https://github.com/rust-lang/rust/pull/153941#issuecomment-4065145752.
CC fallback group @Mark-Simulacrum @jieyouxu who can maybe confirm that the old setup was not intentional? (Edit: I hope it was not intentional, because in that case I should have reached out to you personally beforehand.)
Add test for coalescing of diagnostic attribute duplicates
There is an existing [test](github.com/rust-lang/rust/blob/main/tests/ui/diagnostic_namespace/on_unimplemented/report_warning_on_duplicated_options.rs) that warnings for duplicates are emitted, but not for the messages themselves.
Replace the spdx-rs dependency with a minimal in-tree SPDX tag-value parser
The spdx-rs crate [is no longer maintained](https://github.com/doubleopen-project/spdx-rs/pulls) and is behind on its own dependency updates. It is currently used in [the collect-license-metadata tool](https://github.com/rust-lang/rust/tree/main/src/tools/collect-license-metadata), employing a single function therefrom: `spdx_rs::parsers::spdx_from_tag_value`, which parses the output of the `reuse` tool to extract file names, licences and copyright text.
This PR replaces the use of said function with a small minimal parser that handles just the subset of the SPDX tag-value format that is needed: `Tag: Value` line pairs and multi-line `<text>...</text>` blocks.
Coincidentally, this gets rid of the last transitive dependency on syn v1.
Add regression test for dead code elimination with drop + panic
Add a codegen test for rust-lang/rust#114532.
The bug was that dead code elimination failed when a `Drop` impl contained a `panic!` and a potentially-panicking external function was called after the value was created. This was fixed since 1.82 but no regression test was added.
The test verifies that `foo()` compiles to just a call to `unknown()` + `ret void`, with no panic or panicking call in the function body.
Closesrust-lang/rust#114532
In commit "test: Consolidate `Hexf`, `Hexi`, and the `Hex` trait" we
unintentionally lost the difference between float hex and bitwise hex
formatting; instead, the float hex was getting printed twice. Resolve
this by printing the integer hex whenever the `-` format modifier is
specified. This also makes things simpler because we no longer need to
keep track of whether an `impl DisplayHex` is a float with `.to_bits()`
available or an integer without it, we can always just try to print both
forms.
As a result, we can use a common error message for all validation
checks.
Refactor FnDecl and FnSig non-type fields into a new wrapper type
#### Why this Refactor?
This PR is part of an initial cleanup for the [arg splat experiment](https://github.com/rust-lang/rust/issues/153629), but it's a useful refactor by itself.
It refactors the non-type fields of `FnDecl`, `FnSig`, and `FnHeader` into a new packed wrapper types, based on this comment in the `splat` experiment PR:
https://github.com/rust-lang/rust/pull/153697#discussion_r3004637413
It also refactors some common `FnSig` creation settings into their own methods. I did this instead of creating a struct with defaults.
#### Relationship to `splat` Experiment
I don't think we can use functional struct updates (`..default()`) to create `FnDecl` and `FnSig`, because we need the bit-packing for the `splat` experiment.
Bit-packing will avoid breaking "type is small" assertions for commonly used types when `splat` is added.
This PR packs these types:
- ExternAbi: enum + `unwind` variants (38) -> 6 bits
- ImplicitSelfKind: enum variants (5) -> 3 bits
- lifetime_elision_allowed, safety, c_variadic: bool -> 1 bit
#### Minor Changes
Fixes some typos, and applies rustfmt to clippy files that got skipped somehow.
When the contents correspond to the default, just output
`MiniCore("<default>")` instead of the whole thing.
Helps reduce the length of the debug output in the common case.
std: Update dependency on `wasi` crate
This commit updates the crate dependency that the standard library has on the `wasi` crate. This is now updated to depending explicitly on the `wasip1` crate and the `wasip2` crate published on crates.io. These crates are managed in the [same location][repo] as the `wasi` crate and represent a different versioning scheme which doesn't require multi-version WASI support to require depending on the same crate at multiple versions. The code in libstd is updated to reference `wasip1` and `wasip2` directly as well.
[repo]: https://github.com/bytecodealliance/wasi-rs
Document why `layout.align() + layout.size()` doesn't overflow
This addition looks suspicious and is safety critical, but is saved by the weird `Layout` invariants.
std: fix HashMap RNG docs wording
Fixes a wording typo in the top-level HashMap docs.
Changed "random number coroutine" to "random number generator" in the seed entropy paragraph.
This section is security-relevant, and "generator" is the correct term in RNG context.
Testing:
- Not run locally (docs-only text change).
fix: add aliasing rules for Box
This is a new revised version for the PR [139857](https://github.com/rust-lang/rust/pull/139857), sorry for the delayed reply. I've rewritten the sentence to closely mirror the wording from `Vec::from_raw_parts`, which clearly states the transfer of ownership and its consequences. This should make the aliasing requirements much clearer.
I opted not to include a note about `mem::forget` by default to keep the documentation focused on the primary contract, similar to `Vec`.
net::tcp/udp: fix docs about how set_nonblocking is implemented
`fcntl` `FIONBIO` doesn't even make sense, it should be `fcntl` `F_SETFL`. However, for some reason we are using `ioctl` by default -- except on Solaris where this doesn't seem to work very well.
Honestly what I would have expected is that we just always use `FileDesc::set_nonblocking` also for network sockets, but for some reason we don't and there are no comments explaining this choice. Cc @nikarh (for "vita") @joboet
Rollup of 5 pull requests
Successful merges:
- rust-lang/rust#155308 (Make `OnDuplicate::Error` the default for attributes)
- rust-lang/rust#154432 (Set up API to make it possible to pass closures instead of `AttributeLint`)
- rust-lang/rust#154843 ( Fix conflicting deref move suggestion for LazyLock patterns)
- rust-lang/rust#155262 (bootstrap.py: fix duplicated "the")
- rust-lang/rust#155478 (Fixed broken documentation link for method lookup in rustc_hir_typeck…)
Fix conflicting deref move suggestion for LazyLock patterns
fixesrust-lang/rust#154826.
Rust was suggesting *V -> V for let (v,) = *V, which then triggered a follow-up error suggesting the opposite. This patch makes that case suggest borrowing (&*V) instead. Also handles destructuring assignment separately so we don’t emit a misleading &*... fix-it there.
Set up API to make it possible to pass closures instead of `AttributeLint`
Part of https://github.com/rust-lang/rust/issues/153099.
This PR sets up the base implementations needed to remove `AttributeLintKind` entirely and migrate two variants as examples.
r? @JonathanBrouwer
Make `OnDuplicate::Error` the default for attributes
This makes two changes, in separate commits for reviewability:
- Changes all unstable attributes that are currently `OnDuplicate::Warn` to error.
- Makes `OnDuplicate::Error` the default and removes the explicit `ON_DUPLICATE` for ones that currently already error
r? @jdonszelmann
Remove fewer Storage calls in CopyProp and GVN
Modify the CopyProp and GVN MIR optimization passes to remove fewer `Storage{Live,Dead}` calls, allowing for better optimizations by LLVM - see rust-lang/rust#141649.
### Details
The idea is to use a new `MaybeUninitializedLocals` analysis and remove only the storage calls of locals that are maybe-uninit when accessed in a new location.
Long ago, UI tests were divided into "compile" and "run" tests. Later, the
compile tests were further subdivided into "check" and "build" tests, to speed
up tests that don't need a full build.
The same split was never applied to incremental test revisions, so the only way
to perform a check build in incremental tests is (confusingly) to use a `cfail`
revision and then specify `//@ check-fail` or `//@ check-pass`.
This PR makes room for dedicated check-fail and check-pass revisions by
renaming the existing `cfail` and `cpass` revisions to `bfail` and `bpass`,
since they currently perform a full build.
Rollup of 12 pull requests
Successful merges:
- rust-lang/rust#147811 (naked functions: respect `function-sections`)
- rust-lang/rust#154935 (Add Sized supertrait for CoerceUnsized and DispatchFromDyn)
- rust-lang/rust#139690 (`impl Default for RepeatN`)
- rust-lang/rust#153511 (`std::any::TypeId`: remove misplaced "and" in `Unique<T>` example)
- rust-lang/rust#154943 (Move recursion out of `MatchPairTree::for_pattern` helpers )
- rust-lang/rust#155295 (Fix misleading "borrowed data escapes outside of function" diagnostic)
- rust-lang/rust#155427 (ptr: update text in intro text to one in with_addr doc)
- rust-lang/rust#155428 (Fix ICE in borrowck mutability suggestion with multi-byte ref sigil)
- rust-lang/rust#155435 (rustdoc: Fix `redundant_explicit_links` incorrectly firing (or not firing) under certain scenarios)
- rust-lang/rust#155450 (Remove unnecessary safety conditions related to unchecked uint arithmetic)
- rust-lang/rust#155454 (docs: Fix typo in std/src/thready/scoped.rs)
- rust-lang/rust#155467 (`std::error::Request`: clean up documentation)
docs: Fix typo in std/src/thready/scoped.rs
# Fix typo in std/src/thread/scoped.rs
## Why this pr
This PR fixes the typo mentioned in rust-lang/rust#155275.
I know this was originally fixed in rust-lang/rust#155325 and then in rust-lang/rust#155328.
But since the first issue was closed due to some ai slop and the second one was closed because the first one was already opened, it seems to me that this PR is still needed.
## What this pr does
This PR "just" fixes a typo inside the `std/src/thread/scoped.rs` file
Changing the comment from this:
```
/// borrow non-`'static` data from the outside the scope. See [`scope`] for
/// details.
```
to this:
```
/// borrow non-`'static` data from outside the scope. See [`scope`] for
/// details.
```
rustdoc: Fix `redundant_explicit_links` incorrectly firing (or not firing) under certain scenarios
Hi! I found some issues with the `rustdoc::redundant_explicit_links` lint while working on a personal project.
- After skipping a link that contains inline markups, the lint would incorrectly skip all the remaining links.
For example, with the following snippet, the lint is fired for `[Option][Option]`, but not `[Result][Result]`:
```rs
//! [Option][Option]
//! [**u8**][u8] (skipped)
//! [Result][Result]
```
Happening because of a `?` causing a loop to bail early:
a4a37ed163/src/librustdoc/passes/lint/redundant_explicit_links.rs (L107)
- The lint is fired for links that specify titles (like `[link](link "title")`), except that wouldn't be applicable because it's not possible to specify a title without there also being an explicit target. For example:
```
error: redundant explicit link target
--> <anon>:5:12
|
5 | /// [drop](drop "This function is not magic")
| ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ explicit target is redundant
| |
| because label contains path that resolves to same destination
|
= note: when a link's destination is not specified,
the label is used to resolve intra-doc links
help: remove explicit link target
|
5 - /// [drop](drop "This function is not magic")
5 + /// [drop]
|
```
These are found as of:
```
rustdoc 1.97.0-nightly (1b8f2e46e 2026-04-17)
binary: rustdoc
commit-hash: 1b8f2e46e1
commit-date: 2026-04-17
host: aarch64-apple-darwin
release: 1.97.0-nightly
LLVM version: 22.1.2
```
(Note: I ran `./x test tests/rustdoc-ui` locally, but not `./x tidy` due to my slow internet. There was an unrelated failed test at `tests/rustdoc-ui/ice-bug-report-url.rs` which I'm not sure about)
Fix ICE in borrowck mutability suggestion with multi-byte ref sigil
Fixesrust-lang/rust#139089
Similarly to rust-lang/rust#155068, this is another instance where span arithmetic did not account for multi-byte characters. (Note that the ampersand in the test is full-width)
This change also results in correcting some inappropriate suggestions.
Fix misleading "borrowed data escapes outside of function" diagnostic
Fixesrust-lang/rust#154350
Fall back to `report_general_error()` when `fr_name_and_span` is `None` in function items, since the "escaping data" framing is only appropriate for closures capturing outside variables.
Move recursion out of `MatchPairTree::for_pattern` helpers
The helper functions now just iterate over the relevant subpatterns, while leaving recursion up to the main function.
This avoids passing parameters that were only used for recursive plumbing, and consolidates all recursive calls into `for_pattern` itself, which should make it easier to experiment with changes to the recursive structure.
There should be no change to compiler behaviour.
`impl Default for RepeatN`
This creates an empty iterator, like `repeat_n(value, 0)` but without
needing any such value at hand. There's precedent in many other
iterators that the `Default` is empty, like `slice::Iter`.
I found myself wanting this for rayon's `RepeatN` as it lowers to a
sequential iterator [here][1]. Since rayon is also optimizing to avoid
extra clones, it may end up with parallel splits that have count 0 and
no item value. Calling `std::iter::repeat_n(x, 0)` just drops that
value, but there's no way to construct the same result without a value
yet. This would be straightforward with an empty `Default`.
[1]: ae07384e3e/src/iter/repeat.rs (L201-L202)
r? libs-api (insta-stable)
Add Sized supertrait for CoerceUnsized and DispatchFromDyn
This is part of rust-lang/rust#149094. I did not include `Receiver` because I think it is correct to allow non-sized receivers.
Rollup of 5 pull requests
Successful merges:
- rust-lang/rust#154781 (Fix attribute order implementation)
- rust-lang/rust#155242 (resolve: Introduce `(Local,Extern)Module` newtypes for local and external modules respectively)
- rust-lang/rust#149614 (Use `MaybeDangling` in `std`)
- rust-lang/rust#153178 (Add `TryFromIntError::kind` method and `IntErrorKind::NotAPowerOfTwo` variant)
- rust-lang/rust#155049 (Documenting the case of `Weak::upgrade` returning `None` when the value behind the reference is missing)
Failed merges:
- rust-lang/rust#155308 (Make `OnDuplicate::Error` the default for attributes)
`if (return) {}` caused a panic in `replace_if_let_with_match`:
`let_and_guard` recursed through the `ParenExpr`, producing a bare
`return` as the scrutinee. `make::expr_match` formatted `match return
{ ... }`, which the parser reinterpreted as `match (return { ... })`,
consuming the arm list as the return value. The resulting match expr
had no `MatchArmList`, so the `unwrap()` in `SyntaxFactory::expr_match`
panicked.
Mirror the fix pattern from rust-lang/rust-analyzer#22067: build a fake
`match () { }` and ask whether the scrutinee needs parens in that
position via `needs_parens_in_place_of`. Wrap when required.
fixesrust-lang/rust-analyzer#22072
Example
---
**Before this PR**
```rust
struct Type;
type $0Type = (u8, u8, u8);
struct S { field: Type }
```
**After this PR**
```rust
struct Type;
type $0Type1 = (u8, u8, u8);
struct S { field: Type1 }
```
Documenting the case of `Weak::upgrade` returning `None` when the value behind the reference is missing
Adds a clause to the documentation of `Weak` for `Arc` which was discussed in rust-lang/rust#154936.
Adds the same clause to the documentation of `Weak` for `Rc`, because the behavior is the same.
Add `TryFromIntError::kind` method and `IntErrorKind::NotAPowerOfTwo` variant
- ACP: rust-lang/libs-team#746
- Tracking issue: rust-lang/rust#153978
This pull request adds `kind` method to [`TryFromIntError`](https://doc.rust-lang.org/core/num/struct.TryFromIntError.html), which outputs the detailed cause of converting an integer failing.
This is primarily intended for use in cases where there are multiple causes for failure, such as converting from a large signed integer type to a small signed integer type.
At the moment, this method returns [`&IntErrorKind`](https://doc.rust-lang.org/core/num/enum.IntErrorKind.html). This type implements the `Copy` trait and could return `IntErrorKind`, but returns a reference to align with the behavior of [`ParseIntError::kind`](https://doc.rust-lang.org/core/num/struct.ParseIntError.html#method.kind). If it is not necessary to align the behavior of `TryFromIntError::kind` with `ParseIntError::kind`, I'll change this method to return `IntErrorKind`.
Before this pull request, `IntErrorKind` was only used by [`ParseIntError`](https://doc.rust-lang.org/core/num/struct.ParseIntError.html), but I changed it to be used by `TryFromIntError` as well, so I updated `IntErrorKind`'s documentation.
[`impl TryFrom<usize> for Alignment`](https://doc.rust-lang.org/std/ptr/struct.Alignment.html#impl-TryFrom%3Cusize%3E-for-Alignment) returns `TryFromIntError` as an error if the given value is not a power of two. However, `IntErrorKind` does not have a variant that represents this. So I added the variant `NotAPowerOfTwo` to represent this. For this variant to stabilize, both `try_from_int_error_kind` and `ptr_alignment_type` features must be stabilized.
resolve: Introduce `(Local,Extern)Module` newtypes for local and external modules respectively
Right now both `LocalModule` and `ExternModule` refer to the same `ModuleData`, but the module data for local and extern modules can potentially be made quite different, and we can specialize name lookup for both cases as an optimization.
Declaration creation for local and external modules was already specialized as a part of the parallel import resolution work (see `define_local` and `define_extern`, rust-lang/rust#145108 and previous PRs), because they have different properties with regards to ownership and synchronization.
Fix attribute order implementation
The implementation in https://github.com/rust-lang/rust/pull/153041 contained a mistake :c
I swapped the place where the error message was on, but did not change any code for which attribute was also selected, which explains the empty crater results.
**Interestingly, the original code is broken too, before https://github.com/rust-lang/rust/pull/153041 it always took the last attribute, regardless of what the `AttributeOrder` actually was...**
Let's first see crater results before making a decision
TODO for this PR: Make better tests for this
delegation: fix def path hash collision, add per parent disambiguators
This PR addresses the following delegation issues:
- It fixesrust-lang/rust#153410 when generating new `DefId`s for generic parameters by ~saving `DisambiguatorState`s from resolve stage and using them at AST -> HIR lowering~ introducing per owner disambiguators and transferring them to AST -> HIR lowering stage
- ~Next it fixes the ICE which is connected to using `DUMMY_SP` in delegation code, which was found during previous fix~
- ~Finally, after those fixes the rust-lang/rust#143498 is also fixed, only bugs with propagating synthetic generic params are left.~
Fixesrust-lang/rust#153410. Part of rust-lang/rust#118212.
r? @petrochenkov
`Comment::prefix` iterated `CommentKind::BY_PREFIX` forward, so `/**/`
matched the `/**/` entry itself and returned the full 4-char string.
`block_to_line` then computed `&text[4..text.len()-2]` = `&text[4..2]`
and panicked.
Delegate `Comment::prefix` to `CommentKind::prefix`, which already
iterates in reverse and returns the canonical short form (`/*` for
non-doc block comments). The `/**/` and `/***` entries in `BY_PREFIX`
are still needed for `from_text` to classify them as non-doc blocks.
fixesrust-lang/rust-analyzer#22071
Example
---
```rust
fn main() {
$0let x = Foo { x };
}
```
**Before this PR**
```rust
fn main() {
if let x = Foo {
}
}
```
**After this PR**
```rust
fn main() {
if let x = (Foo { x }) {
}
}
```
compiletest: Remove the `//@ should-ice` directive
The `//@ should-ice` directive was only being used by one test, which can just as easily use the more general `//@ failure-status` directive instead.
All of the removed exit-code checks were redundant with other exit-code checks that are still present.
---
I have manually verified that `tests/incremental/delayed_span_bug.rs` fails if the failure-status directive is modified or removed.
Tweak how the "copy path" rustdoc button works to allow some accessibility tool to work with rustdoc
Fixes https://github.com/rust-lang/rust/issues/155032.
It's a bit better in term of "fragility" to retrieve this information: no need to parse text anymore, just to retrieve content. However it relies on HTML. I added extra tests to ensure it won't break without notice.
cc @Enyium
r? @lolbinarycat
Rearrange `rustc_ast_pretty`
`rustc_ast_pretty` has two modules, `pp::convenience` and `helpers`, that are small and silly. This PR eliminates them. Details in the individual commits.
r? @WaffleLapkin
tests/debuginfo/basic-stepping.rs: Remove FIXME related to ZSTs
We don't consider it a bug that users can't break on initialization of some non-zero sized types (see https://github.com/rust-lang/rust/pull/153941 and linked discussions), so it does not make sense to consider it a bug that users can't break on initialization of some zero-sized types.
Closesrust-lang/rust#97083
r? compiler (see https://github.com/rust-lang/rust/pull/155352)
ImproperCTypes: Move erasing_region_normalisation into helper function
This is "part 1/3 of 2/3 of 1/2" of the original pull request https://github.com/rust-lang/rust/pull/134697 (refactor plus overhaul of the ImproperCTypes family of lints)
(all pulls of this series of pulls are supersets of the previous pulls. If this pull is "too small" to be worth the effort, you can instead look at the next in the series)
This pull is a small internal change among the efforts to refactor the ImproperCTypes lints, by moving some "unwrapping" code (`cx.tcx.try_normalize_erasing_regions`) into a helper function.
r? petrochenkov
Make `convert_while_ascii` unsafe
`convert_while_ascii` assumes `convert` only returns ASCII to ensure the output remains valid UTF-8. This adds that requirement as a safety precondition.
changed the information provided by (mut x) to mut x (Fix 155030)
When trying to change a value without using mut in a for loop, the recommendation for this change is incorrect, so I am correcting it.
resolve: rust-lang/rust#155030
rustdoc: preserve `doc(cfg)` on locally re-exported type aliases
When a type alias is locally re-exported from a private module (an implicit inline), rustdoc drops its `cfg` attributes because it treats it like a standard un-inlined re-export. Since type aliases have no inner fields to carry the `cfg` badge (unlike structs or enums), the portability info is lost entirely.
This patch explicitly preserves the target's `cfg` metadata when the generated item is a `TypeAliasItem`, ensuring the portability badge renders correctly without breaking standard cross-crate re-export behavior.
Fixesrust-lang/rust#154921
Remove AttributeSafety from BUILTIN_ATTRIBUTES
Encodes the expected attribute safety in the attribute parsers, rather than in `BUILTIN_ATTRIBUTES`, with the goal of removing `BUILTIN_ATTRIBUTES` soon.
We can remove the old attribute safety logic already because unparsed attributes, just like the as of yet unparsed lint attributes, need to be safe.
r? @jdonszelmann (or @mejrs if you feel like doing it, since you are in T-compiler now 🎉)
c-variadic: fix implementation on `avr`
tracking issue: https://github.com/rust-lang/rust/issues/44930
cc target maintainer @Patryk27
I ran into multiple issues, and although with this PR and a little harness I can run the test with qemu on avr, the implementation is perhaps not ideal.
The problem we found is that on `avr` the `c_int/c_uint` types are `i16/u16`, and this was not handled in the c-variadic checks. Luckily there is a field in the target configuration that contains the targets `c_int_width`. However, this field is not actually used in `core` at all, there the 16-bit targets are just hardcoded.
1500f0f47f/library/core/src/ffi/primitives.rs (L174-L185)
Perhaps we should expose this like endianness and pointer width?
---
Finally there are some changes to the test to make it compile with `no_std`.
Suggest to bind `self.x` to `x` when field `x` may be in format string
Fixesrust-lang/rust#141350
I added the new test in the first commit, and committed the changes in the second one.
r? @fmease
cc @mejrs
This directive was only being used by one test, which can just as easily use
the more general `//@ failure-status` directive instead.
All of the removed exit-code checks were redundant with other exit-code checks
that are still present.
This creates an empty iterator, like `repeat_n(value, 0)` but without
needing any such value at hand. There's precedent in many other
iterators that the `Default` is empty, like `slice::Iter`.
I found myself wanting this for rayon's `RepeatN` as it lowers to a
sequential iterator [here][1]. Since rayon is also optimizing to avoid
extra clones, it may end up with parallel splits that have count 0 and
no item value. Calling `std::iter::repeat_n(x, 0)` just drops that
value, but there's no way to construct the same result without a value
yet. This would be straightforward with an empty `Default`.
[1]: ae07384e3e/src/iter/repeat.rs (L201-L202)
This commit updates the crate dependency that the standard library has
on the `wasi` crate. This is now updated to depending explicitly on the
`wasip1` crate and the `wasip2` crate published on crates.io. These
crates are managed in the [same location][repo] as the `wasi` crate and
represent a different versioning scheme which doesn't require
multi-version WASI support to require depending on the same crate at
multiple versions. The code in libstd is updated to reference `wasip1`
and `wasip2` directly as well.
[repo]: https://github.com/bytecodealliance/wasi-rs
Make `span_suggestions` always verbose
`span_suggestions` is to provide mutually exclusive suggestions. When it was introduced, we made its behavior be that if a single suggestion is given to it, we present the suggestion inline, otherwise in patch format. Changing this to make all of its uses be verbose, as that is closer in intent of output.
`rustc_ast_pretty::pp` defines `Printer` and has a 346 line `impl
Printer` block for it. `rustc_ast_pretty::pp::convenience` has another
`impl Printer` block with 85 lines. `rustc_ast_pretty::helpers` has
another `impl Printer` block with 45 lines.
This commit merges the two small `impl Printer` blocks into the bigger
one, because there is no good reason for them to be separate. Doing this
eliminates the `rustc_ast_pretty::pp::convenience` and
`rustc_ast_pretty::helpers` modules; no great loss given that they were
small and had extremely generic names.
When a type alias is locally re-exported from a private module (an implicit
inline), rustdoc drops its `cfg` attributes because it treats it like a
standard un-inlined re-export. Since type aliases have no inner fields to
carry the `cfg` badge (unlike structs or enums), the portability info
is lost entirely.
This patch explicitly preserves the target's `cfg` metadata when the
generated item is a `TypeAliasItem`, ensuring the portability badge
renders correctly without breaking standard cross-crate re-export behavior.
Reduce diagnostic type visibilities.
Most diagnostic types are only used within their own crate, and so have a `pub(crate)` visibility. We have some diagnostic types that are unnecessarily `pub`. This is bad because (a) information hiding, and (b) if a `pub(crate)` type becomes unused the compiler will warn but it won't warn for a `pub` type.
This commit eliminates unnecessary `pub` visibilities for some diagnostic types, and also some related things due to knock-on effects. (I found these types with some ad hoc use of `grep`.)
r? @Kivooeo
Handle nonnull pattern types in size skeleton
The original comment was correct, the size is always the same, but we have more information now. In theory there was an additional bug that would have allowed transmuting things of different sizes, but I don't see how that would have been actually doable as the `tail` types would always have differed.
fixesrust-lang/rust#155330
docs: Use `0b1` instead of `NonZero::MIN` in `NonZero::bit_width` doctests
This pull request updates the doctests for the `NonZero::bit_width` method. It replaces the use of the `NonZero::MIN` constant with an explicit binary literal `0b1`.
I think using `0b1` is more intuitive for illustrating the method's behavior than `NonZero::MIN`. Since other examples in the same doctests already use `0b111` and `0b1110`, this change brings the first example into alignment with the rest of the doctests.
I followed the existing pattern in the `NonZero::highest_one` and `NonZero::lowest_one` methods, which already use `0b1` in their doctests.
I also followed the convention of `uint::bit_width`, which uses the literal `0` instead of the `uint::MIN` constant in its doctests.
Disallow ZST allocations with `TypedArena`.
`DroplessArena::alloc` already disallows ZST allocation. `TypedArena::alloc` allows it but:
- (a) it's never used, and
- (b) writing to `NonNull::dangling()` seems dubious, even if the write is zero-sized.
This commit just changes it to panic on a ZST. This eliminates an untested code path, and we shouldn't be allocating ZSTs anyway. It also eliminates an unused ZST code path in `clear_last_chunk`.
r? @Nadrieril
Check diagnostic output in incremental `cpass` and `rpass` revisions
This allows compiler warnings to be annotated in `cpass` and `rpass` revisions, and verifies that no unexpected warnings occur.
---
My underlying motivation is that I want to be able to reduce or eliminate the confusing combination of `cfail` revisions with `//@ build-pass` directives, and replace them with a more straightforward `cpass` revision that also checks diagnostic output. That migration is not part of this PR.
Clean up `AttributeLintKind` and refactor diagnostic attribute linting
There was a fair amount of duplication here, and thanks to the proliferation of new diagnostic attributes these days, it was threatening to grow bigger.
Add `--quiet` flag to x.py and bootstrap to suppress output
This adds a `--quiet` flag to x.py and bootstrap to suppress some of the output when compiling Rust. It conflicts with `--verbose`, matching the behavior of `cargo` which does not allow `--verbose` and `--quiet`.
It works by passing quiet flags down to the underlying cargo, or LLVM build processes. Note that for LLVM, we only can suppress logs when we explicitly configure it with ninja. Otherwise we won't know what flag to pass along to whichever build system cmake decides to use.
This can be helpful with AI workloads in the Rust codebase to help shrink down the output to reduce token usage, which can help prevent context pollution and lower costs.
This patch was partially generated with Gemini, but I've reviewed the changes it made.
abort in core
Implements `core::process::abort_immediate` as a wrapper around `intrinsics::abort`.
- tracking issue: https://github.com/rust-lang/rust/issues/154601
(This PR used to also add `core::process::abort`, but that's been deferred to a later addition.)
clippy fix: non_canonical_clone_impl
Fixes:
```text
warning: non-canonical implementation of `clone` on a `Copy` type
--> library/core/src/clone.rs:682:33
|
682 | fn clone(&self) -> Self {
| _________________________________^
683 | | self
684 | | }
| |_________^ help: change this to: `{ *self }`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl
= note: requested on the command line with `-W clippy::non-canonical-clone-impl`
warning: non-canonical implementation of `clone` on a `Copy` type
--> library/core/src/convert/mod.rs:935:35
|
935 | fn clone(&self) -> Infallible {
| ___________________________________^
936 | | match *self {}
937 | | }
| |_____^ help: change this to: `{ *self }`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl
warning: non-canonical implementation of `clone` on a `Copy` type
--> library/core/src/marker.rs:856:29
|
856 | fn clone(&self) -> Self {
| _____________________________^
857 | | Self
858 | | }
| |_____^ help: change this to: `{ *self }`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl
```
Add `--remap-path-scope` as unstable in rustdoc
This PR adds support for `rustc` `--remap-path-scope` flag in rustdoc as unstable.
`rustc` documentation for the flag is [here](https://doc.rust-lang.org/nightly/rustc/remap-source-paths.html#--remap-path-scope).
I added some complementary tests for `rustdoc`, no need I think to duplicate `rustc` UI tests.
resolve: Remove `inaccessible_ctor_reexport` resolver field
Collect the necessary information during error reporting instead of doing it on a good path from the core name resolution infra.
Also cleanup the related diagnostic code for struct constructors in general, see the individual commits.
This mitigates most of the harm brought by https://github.com/rust-lang/rust/pull/133477.
Emit fatal on invalid const args with nested defs
Fixed https://github.com/rust-lang/rust/issues/123629
Fixes https://github.com/rust-lang/rust/issues/154539
Invalid const args are rejected, so their surrounding HIR is not preserved. But nested defs inside them can still get created, leaving children lowered without a valid HIR parent and causing an ICE when later error handling walks HIR parents.
r? @BoxyUwU
Require that a `<_ as Try>::Residual` implement the `Residual` trait
The `Residual` trait was even more experimental than `Try`, but now that https://github.com/rust-lang/rfcs/pull/3721 is merged, I think it would make sense to require this. Technically it's not strictly required, but without it something working on `<T: Try>` might need an extra bound even to use a homogeneous try block with the same output type as `T::Output`. (Another `where` will of course be needed to return a *different* `impl Try` type still.)
cc https://github.com/rust-lang/rust/issues/154391
We don't consider it a bug that users can't break on initialization of
some non-zero sized types (see comment on `maximally-steppable` at the
top of the file), so it does not make sense to consider it a bug that
users can't break on initialization of some zero-sized types.
Dead code elimination used to fail when a Drop impl contained a panic
and a potentially-panicking external function was called after the value
was created. This was fixed since 1.82 but no regression test was added.
The test verifies that foo() compiles to just a call to unknown() and
ret void, with no panic or panicking call in the function body.
Signed-off-by: Naveen R. Iyer <iyernaveenr@gmail.com>
Fix int_plus_one suggestion causing parse error when LHS is an
`AssocOp::Cast`
When int_plus_one rewrites an expression like `x as usize + 1 <= y`, it
suggests `x as usize < y`. This doesn't compile because the parser
interprets `usize<y>` as the start of generic arguments rather than a
lt comparison.
The fix parenthesizes the LHS if it's an `AssocOp::Cast` and the
replacement
operator is `<`: `(x as usize) < y`.
---
changelog: [int_plus_one]: Parenthesize `AssocOp::Cast` in suggestion
when replacement operator is < to avoid parse error
Most diagnostic types are only used within their own crate, and so have
a `pub(crate)` visibility. We have some diagnostic types that are
unnecessarily `pub`. This is bad because (a) information hiding, and (b)
if a `pub(crate)` type becomes unused the compiler will warn but it
won't warn for a `pub` type.
This commit eliminates unnecessary `pub` visibilities for some
diagnostic types, and also some related things due to knock-on effects.
(I found these types with some ad hoc use of `grep`.)
Another interal change that shouldn't impact rustc users.
To prepare for the upcoming split of visit_type, we reorganise the instances
of `cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty)`
into a helper function outside of the main structs.
In `autolabel."T-compiler"`, several `./tests/*` dirs are listed.
But many of them are missing from `assign.owners`. Add them all to
`assign.owners` so reviewers are picked from the compiler group, and not
from the small `assign.adhoc_groups.fallback` group.
Fallback `{float}` to `f32` when `f32: From<{float}>` and add `impl From<f16> for f32`
Currently, the following code compiles:
```rust
fn foo<T: Into<f32>>(_: T) {}
fn main() {
foo(1.0);
}
```
This is because the only `From<{float}>` impl for `f32` is currently `From<f32>`. However, once `impl From<f16> for f32` is added this is no longer the case. This would cause the float literal to fallback to `f64`, subsequently causing a type error as `f32` does not implement `From<f64>`. While this kind of change to type inference isn't technically a breaking change according to Rust's breaking change policy, the previous attempt to add `impl From<f16> for f32` was removed rust-lang/rust#123830 due to the large number of crates affected (by my count, there were root regressions in 42 crates and 52 GitHub repos, not including duplicates). This PR solves this problem by using `f32` as the fallback type for `{float}` when there is a trait predicate of `f32: From<{float}>`. This allows adding `impl From<f16> for f32` without affecting the code that currently compiles (such as the example above; this PR shouldn't affect what is possible on stable).
This PR also allows adding a future-incompatibility warning for the fallback to `f32` (currently implemented in the third commit) if the lang team wants one (allowing the `f32` fallback to be removed in the future); alternatively this could be expanded in the future into something more general like @tgross35 suggested in https://github.com/rust-lang/rust/issues/123831#issuecomment-2064728053. I think it would be also possible to disallow the `f32` fallback in a future edition.
As expected, a crater check showed [no non-spurious regressions](https://github.com/rust-lang/rust/pull/139087#issuecomment-2764732580).
For reference, I've based the implementation loosely on the existing `calculate_diverging_fallback`. This first commit adds the `f32` fallback, the second adds `impl From<f16> for f32`, and the third adds a FCW lint for the `f32` fallback. I think this falls under the types team, so
r? types
Fixes: rust-lang/rust#123831
Tracking issue: rust-lang/rust#116909
@rustbot label +T-lang +T-types +T-libs-api +F-f16_and_f128
To decide on whether a future-incompatibility warning is desired or otherwise (see above):
@rustbot label +I-lang-nominated
cc https://github.com/rust-lang/rust/issues/154024https://github.com/rust-lang/rust/issues/154005
This adds a `--quiet` flag to x.py and bootstrap to suppress some of the
output when compiling Rust. It conflicts with `--verbose`, matching the
behavior of `cargo` which does not allow `--verbose` and `--quiet`.
It works by passing quiet flags down to the underlying cargo, or LLVM
build processes. Note that for LLVM, we only can suppress logs when we
explicitly configure it with ninja. Otherwise we won't know what flag
to pass along to whichever build system cmake decides to use.
This can be helpful with AI workloads in the Rust codebase to help
shrink down the output to reduce token usage, which can help prevent
context pollution and lower costs.
This patch was partially generated with Gemini, but I've reviewed the
changes it made.
Type system consts (consts that participate in the type system, e.g. const generic params) have special properties: they must have strict equality independent of the user. For example, unions are not possible there. Therefore they are stored as a `ValTree`, a very simple representation that is good, mostly, for comparing things.
General consts can be anything (almost) - arbitrary bytes, even uninit bytes. They are stored like all consts previously were (in the type-system's `Const`), with bytes memory, in a new type called `Allocation` (named borrowed from rustc, although it isn't exactly accurate because in r-a it can represent multiple allocations).
The trigger for this change was a new requirement from rustc_type_ir, that type-system `Const` will be able to represent as a `ValTree`.
This is how rustc does it, because they're similar in many ways, and most importantly: they share (or will share, not yet) capture analysis.
Also:
- Copy closure inference from rustc again, this time really precisely.
- Have separate ID types for coroutine closures and normal closures, for better type safety.
- Validate, when constructing interned closures/coroutines/coroutine closures and `cfg(debug_assertions)`, that the `ExprId` is of an expr of the correct kind.
Reformat `top_level_options!` and `options!` macro declarations
These macros are already tricky, and having weird formatting doesn't help. Using a more regular style makes it easier to see where nesting begins and ends.
Extracted from https://github.com/rust-lang/rust/pull/154501 after the changes in https://github.com/rust-lang/rust/pull/149357 made rebasing very difficult.
There should be no change to compiler behaviour.
compiler: update hashbrown to 0.17
See library's rust-lang/rust#155154 for the bug fixes this brings.
This PR also updates `indexmap` in the compiler as a direct dependent.
`DroplessArena::alloc` already disallows ZST allocation.
`TypedArena::alloc` allows it but:
- (a) it's never used, and
- (b) writing to `NonNull::dangling()` seems dubious, even if the write
is zero-sized.
This commit just changes it to panic on a ZST. This eliminates an
untested code path, and we shouldn't be allocating ZSTs anyway.
It also eliminates an unused ZST code path in `clear_last_chunk`.
Tests are also updated accordingly.
Remove dead diagnostic structs.
One of these has a "FIXME(autodiff): I should get used somewhere" comment, but I figure YAGNI applies and it's so small that reinstating it if necessary would be trivial.
r? @Kivooeo
remove PointeeParser
this parser does nothing currently, as the current scope of `rustc_attr_parsing` only includes builtin attributes, and not derive macros
it isn't defined in `compiler/rustc_feature/src/builtin_attrs.rs`
all the actual parsing for `#[pointee]` is actually handled in `compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs`
r? @JonathanBrouwer
Delete unused `rustc_trait_selection` errors.
The first two of these are duplicated elsewhere in some form or another, apparently they became orphaned during various moves and refactors. The third is just never used.
Tests for precise-capture through RPIT and TAIT
- Tests for https://github.com/rust-lang/rust/issues/155151.
These tests succeed under `-Znext-solver`, but incorrectly fail under the old trait solver.
---
The bug can be triggered via return-position `impl Trait` on stable, but requires some rather contrived code. When using type-alias `impl Trait`, it's easier to imagine the issue being triggered by real code.
Test/lexer unicode pattern white space
This PR adds a test for the Rust lexer to verify it correctly accepts vertical tab (`\x0B`) as valid whitespace between tokens. Vertical tab is part of Unicode Pattern_White_Space, which the Rust language specification uses to define whitespace.
Related: Outreachy tracking [Pattern_White_Space](https://www.unicode.org/reports/tr31/#R3a)
Clarify ascii whitespace exclusion of vertical tab in the doc
This especially means that for `c: char`, `c.is_ascii() && c.is_whitespace()` does **not** imply `c.is_ascii_whitespace()`, which can cause bug and is highly counterintuitive.
docs: clarify path search behavior in std::process::Command::new
the existing docs mentioned that `PATH` is searched in an "os defined way" and that it could be controlled by setting PATH on the command but never explained which `PATH` is actually used.
on unix the key thing to understand is that when you modify the childs environment (via `env()`, `env_remove()`, or `env_clear()`), the `PATH` search uses whatever `PATH` ends up in the child's environment not the parents. so if you call `env_clear()` and forget to set `PATH`, you don't get the parents `PATH` as a fallback; you get the OS default (typically `/bin:/usr/bin`) which often won't find what you need.
the three cases are now documented:
- unmodified env: child inherits parents `PATH`, that gets searched
- `PATH` explicitly set `via env()`: the new value is searched
- `PATH` removed (`env_clear` or `env_remove`): falls back to OS default, not the parents `PATH`
on windows rust resolves the executable before spawning rather than letting `CreateProcessW` do it. the search order is: childs `PATH` (if explicitly set) first then system-defined directories then the parents `PATH`. the existing note about issue rust-lang/rust#37519 is preserved.
limitations in this doc:
- the unix fallback path behavior ("typically `/bin:/usr/bin`") is verified for linux/glibc. behavior on macOS, BSD, and musl is similar in practice but not fully confirmed here.
- the windows search order is summarized as "system-defined directories" which actually includes the application directory (the directory of the calling process's executable) as a distinct step before the system dirs that detail is omitted for brevity.
- `posix_spawnp` `PATH` source (calling process environ vs envp argument) is ambiguous in the `POSIX` spec; the behavior here is inferred from the guard in `unix.rs` that bypasses `posix_spawn` when `PATH` has been modified.
closesrust-lang/rust#137286 (hopefully)
`BorrowedBuf`: Update outdated safety comments in `set_init` users.
These comments appear to have been written before `BorrowedBuf`'s init tracking was simplified in
https://github.com/rust-lang/rust/pull/150129. The `BufWriter` comment of the usage within `BufWriter` will be handled separately.
CC rust-lang/rust#78485, rust-lang/rust#117693.
explicit-tail-calls: disable two tests on LoongArch
A [recent LLVM change](https://github.com/llvm/llvm-project/pull/191508) broke these on LLVM 23.
I suspect these will eventually be fixed, so maybe it'd be okay/better to just leave this pending so it applies to our CI without merging it? I'm open to opinions.
Fix ICE when Self is used in enum discriminant of a generic enum
Fixesrust-lang/rust#153756
Let discriminant AnonConst inherit parent generics via Node::Variant in generics_of, and emit a proper error instead of span_bug! for the TooGeneric case in wfcheck.
`span_suggestions` is to provide mutually exclusive suggestions. When it was introduced, we made its behavior be that if a single suggestion is given to it, we present the suggestion inline, otherwise in patch format. Changing this to make all of its uses be verbose, as that is closer in intent of output.
One of these has a "FIXME(autodiff): I should get used somewhere"
comment, but I figure YAGNI applies and it's so small that reinstating
it if necessary would be trivial.
These comments appear to have been written before `BorrowedBuf`'s
init tracking was simplified in
https://github.com/rust-lang/rust/pull/150129. The `BufWriter` comment
of the usage within `BufWriter` will be handled separately.
Previously the lint would be reported at the right span, but could not be `allow`ed or `expect`ed in that location, because the lint was actually emitted using `CRATE_HIR_ID`
Adds parser support for the unstable `type const` syntax from the
`min_generic_const_args` feature, e.g. `type const FOO: i32 = 2;`.
Closesrust-lang/rust-analyzer#22038.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Rollup of 7 pull requests
Successful merges:
- rust-lang/rust#154049 (delegation: Track more precise spans for glob delegations)
- rust-lang/rust#155134 (Replace custom trim_ascii_start with the standard library method)
- rust-lang/rust#155235 (add the `fma4` x86 target feature)
- rust-lang/rust#155218 (coroutines: Skip the closure signature annotation check for tainted bodies)
- rust-lang/rust#155274 (limit duplicate-profiler-builtins test to targets that can do dynamic linking)
- rust-lang/rust#155276 (`#[rustc_must_match_exhaustively]` detect let else)
- rust-lang/rust#155281 (Revert "allow `windows-gnu` targets to embed gdb visualizer scripts")
* Fix ICE when Self is used in enum discriminant of a generic enum
Move the validation into the existing `check_param_uses_if_mcg` machinery
in HIR ty lowering instead of adding a new check in wfcheck. After the
`AnonConstKind` refactoring, `ForbidMCGParamUsesFolder` was only gated on
`AnonConstKind::MCG`, causing discriminant anon consts (`NonTypeSystem`) to
bypass it entirely.
Add `anon_const_forbids_generic_params()` which returns the appropriate
`ForbidParamContext` for both MCG and enum discriminant contexts. Wire it
into `check_param_uses_if_mcg` so that `Self` aliasing a generic type is
caught before reaching `const_eval_poly`. Convert the `TooGeneric` span_bug
into a proper diagnostic as a fallback for anything slipping through
type-dependent path resolution.
* Address review comments
- Rename `ForbidMCGParamUsesFolder` to `ForbidParamUsesFolder`
- Rename `MinConstGenerics` variant to `ConstArgument` with updated doc
- Simplify doc comment on `anon_const_forbids_generic_params`
- Make match on `AnonConstKind` exhaustive
- Move `anon_const_def_id` inside the `if let` in `check_param_uses_if_mcg`
- Remove now-unreachable `TooGeneric` span_err in wfcheck
* Revert TooGeneric arm back to span_bug! as requested by reviewer
* Use generics_of to determine if NonTypeSystem anon consts allow generic params
* Also check InlineConst and Closure defs nested in enum discriminants
* Simplify logic for determining anonymous constant parent in generic contexts
* add test
limit duplicate-profiler-builtins test to targets that can do dynamic linking
this is the error I got for an example of such a target
```
=== STDERR ===
error: extern location for dylib_a does not exist: libdylib_a.so
--> main.rs:2:5
|
2 | dylib_a::something();
| ^^^^^^^
error: extern location for dylib_b does not exist: libdylib_b.so
--> main.rs:3:5
|
3 | dylib_b::something_else();
| ^^^^^^^
coroutines: Skip the closure signature annotation check for tainted bodies
When a coroutine has too many parameters, `check_match` fails and `construct_error` builds a MIR body with only the coroutine's computed arguments (env + resume type). The user-provided signature, however, still reflects all the parameters the user wrote. `check_signature_annotation` then tries to `zip_eq` these two mismatched iterators, causing a panic. Checking `tainted_by_errors` and bailing early avoids this, since `construct_error` bodies cannot meaningfully be compared against user annotations.
Example currently ICEing:
```rust
fn main() {
|(1, 42), ()| yield;
}
```
Closesrust-lang/rust#139570.
add the `fma4` x86 target feature
tracking issue: https://github.com/rust-lang/rust/issues/155233
Implications are based on LLVM
df6c82053c/llvm/lib/Target/X86/X86.td (L201-L206)
This feature adds a slightly better instruction encoding for fma. We might want to expose the intrinsics in `stdarch` with that target feature, but just adding the target feature in user code should already take advantage of this improved encoding.
This target feature is used in `libm`.
r? sayantn
Replace custom trim_ascii_start with the standard library method
The markdown parser in `rustc_errors` has a local `trim_ascii_start` function that strips leading ASCII whitespace from a byte slice. The standard library has had `<[u8]>::trim_ascii_start()` since Rust 1.80, which does the same thing.
This PR removes the custom function and calls the stdlib method directly in `parse_unordered_li` and `parse_ordered_li`. No behaviour change.
I also added a test covering the list item leading-whitespace trimming behaviour, including a tab case.
Fixesrustfoundation/interop-initiative#53
delegation: Track more precise spans for glob delegations
The last commit also fixes a macro hygiene issue with `self` in delegations found in https://github.com/rust-lang/rust/pull/154002.
Unless the feature is enabled (and we're on nightly).
We can choose to not complete any unstable item if its feature is not enabled. However people may first type the thing then insert the feature. Only doing that for internal features is a good middle ground: normal people don't want their completion list polluted by `std::intrinsics` (even if they use nightly), and std people still get their completion if the feature is enabled (and realistically, it will be).
Post-attribute ports cleanup pt. 1 (again)
This is a re-implementation of most (but not all) of https://github.com/rust-lang/rust/pull/154808
The code is the same as in that PR, other than a few changes, I'll leave comments where I changed things.
I did re-implement most of the commits rather than cherry-picking, so it's probably good to check the entire diff regardless
r? @jdonszelmann
Post-attribute ports cleanup pt. 1 (again)
This is a re-implementation of most (but not all) of https://github.com/rust-lang/rust/pull/154808
The code is the same as in that PR, other than a few changes, I'll leave comments where I changed things.
I did re-implement most of the commits rather than cherry-picking, so it's probably good to check the entire diff regardless
r? @jdonszelmann
Instead of the last segment of the delegation path.
`self` is something that introduced by the whole delegation item, not some specific part of it, and the last segment may need to have a different context for path resolution purposes.
Rollup of 3 pull requests
Successful merges:
- rust-lang/rust#152530 (Use the term struct-like variant instead of anonymous structs for data of struct-like enum variants)
- rust-lang/rust#155005 (preserve SIMD element type information)
- rust-lang/rust#155230 (Avoid linting `doc_cfg` as unused in rustc)
preserve SIMD element type information
Preserve the SIMD element type and provide it to LLVM for better optimization.
This is relevant for AArch64 types like `int16x4x2_t`, see also https://github.com/llvm/llvm-project/issues/181514. Such types are defined like so:
```rust
#[repr(simd)]
struct int16x4_t([i16; 4]);
#[repr(C)]
struct int16x4x2_t(pub int16x4_t, pub int16x4_t);
```
Previously this would be translated to the opaque `[2 x <8 x i8>]`, with this PR it is instead `[2 x <4 x i16>]`. That change is not relevant for the ABI, but using the correct type prevents bitcasts that can (indeed, do) confuse the LLVM pattern matcher.
This change will make it possible to implement the deinterleaving loads on AArch64 in a portable way (without neon-specific intrinsics), which means that e.g. Miri or the cranelift backend can run them without additional support.
discussion at [#t-compiler > loss of vector element type information](https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/loss.20of.20vector.20element.20type.20information/with/584483611)
There seemed to be non-deterministic failures on MSVC that looked like
corruption of the FFR in CI. Until this can be investigated, to avoid any
spurious failures, these tests are disabled.
`dumpbin.exe` produces `44a1c000`/`44e1c000`/`44a1c400`/`44e1c400` for
`[su]mull[tb]` instead of the instruction name - so skip `assert_instr`
for these intrinsics on MSVC targets.
The implementation for this has the same behaviour as a `pfalse` but
doesn't currently emit one until an intrinsic is added to emit a
`zeroinitializer` for this.
SVE intrinsics have both type and const generics and so the
`assert_instr` macro needs to be able to generate test cases with the
type generics instantiated with the types provided in the attribute.
Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
Co-authored-by: Adam Gemmell <adam.gemmell@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
tidy: handle `#[cfg_attr(bootstrap, doc = "...")]` in `compiler/` comments
For the unbalanced backtick check that Waffle ran into in https://github.com/rust-lang/rust/pull/154887.
This PR cherry-picks Waffle's tidy patch in that PR (and adds some explaining comments) even though I'd say this is somewhat hacky[^1]. But since the original tidy check implementation is already based on heuristics and so are likewise fuzzy, this is probably fine in practice for most cases.
[^1]: There can be false positives/negatives like having both fragments `cfg_attr` and `doc` inside a string literal, but I would expect that to be very very niche, so it's "good enough".
(I wanted to write a regression test, but this check needs some restructuring to make it more easy to test that I don't want to bundle in this PR.)
r? wafflelapkin (or bootstrap/compiler)
Trait aliases: Also imply default trait bounds on type params other than `Self`
Trait aliases already correctly imply default trait bounds on `Self` type params. However, due to an oversight, they didn't do that for normal type params.
Fixesrust-lang/rust#152687.
Implement `-Z allow-partial-mitigations` (RFC 3855)
This implements `-Z allow-partial-mitigations` as an unstable option, currently with support for control-flow-guard and stack-protector.
As a difference from the RFC, we have `-Z allow-partial-mitigations=!foo` rather than `-Z deny-partial-mitigations=foo`, since I couldn't find an easy way to have an allow/deny pair of flags where the latter flag wins.
To allow for stabilization, this is only enabled starting from the next edition. Maybe a better policy is possible (bikeshed).
r? @rcvalle
The local trim_ascii_start function in the markdown parser duplicates
<[u8]>::trim_ascii_start() from the standard library (stable since 1.80).
Remove the custom function and call the stdlib method directly.
No behaviour change.
Fixes https://github.com/rustfoundation/interop-initiative/issues/53
Start using pattern types in libcore
cc rust-lang/rust#135996
Replaces the innards of `NonNull` with `*const T is !null`.
This does affect LLVM's optimizations, as now reading the field preserves the metadata that the field is not null, and transmuting to another type (e.g. just a raw pointer), will also preserve that information for optimizations. This can cause LLVM opts to do more work, but it's not guaranteed to produce better machine code.
Once we also remove all uses of rustc_layout_scalar_range_start from rustc itself, we can remove the support for that attribute entirely and handle all such needs via pattern types
Start using pattern types in libcore
cc rust-lang/rust#135996
Replaces the innards of `NonNull` with `*const T is !null`.
This does affect LLVM's optimizations, as now reading the field preserves the metadata that the field is not null, and transmuting to another type (e.g. just a raw pointer), will also preserve that information for optimizations. This can cause LLVM opts to do more work, but it's not guaranteed to produce better machine code.
Once we also remove all uses of rustc_layout_scalar_range_start from rustc itself, we can remove the support for that attribute entirely and handle all such needs via pattern types
Fix manpage version replacement and use verbose version
- Fix a bug where `t!(fs::copy(&page_src, &page_dst))` was called after`fs::write`, silently overwriting the substituted content with the original template (restoring the `<INSERT VERSION HERE>` placeholder verbatim) (Related rust-lang/rust#93685)
- Use `rust_info().version()` instead of the bare version number, so the man page now includes the full version string with commit hash and date
Improve emission of `UnknownDiagnosticAttribute` lint
This checks features much less than the current implementation. See https://github.com/rust-lang/rust/pull/155155 for context. Minor fixes and comments are added in the second and third commit.
Move tests from `tests/ui/issues/` to appropriate directories
In this PR, I am moving the following test from `tests/ui/issues` directory to the appropriate directories, followed by the addition of issue links at the top and reblessing of the stderr files:
| old-name | new-sub-dir | new-name |
|-|-|-|
| `issue-29516.rs` | `auto-traits/` | `distinct-type-tuple-by-negative-impl.rs` |
| `issue-3874.rs` | `binding/` | `ref-in-let-lhs-in-field.rs` |
| `issue-32782.rs` | `feature-gates/` | `feature-gate-check-nested-macro-invocation.rs` |
| `issue-32782.stderr` | `feature-gates/` | `feature-gate-check-nested-macro-invocation.stderr` |
| `issue-5100.rs` | `pattern/` | `match-errors-derived-error-suppression.rs` |
| `issue-5100.stderr` | `pattern/` | `match-errors-derived-error-suppression.stderr` |
| `issue-21033.rs` | `pattern/` | `match-struct-var-having-boxed-field.rs` |
r? Kivooeo
r? Teapot4195
UI automation
# To move issue-3154 and issue-16774 to functional subdirectories:
I have moved 2 tests from tests/ui/issues to their appropriate directories using "test-manager" tool.
## Changes:
- Moved tests/ui/issues/issue-3154.rs to tests/ui/borrowck/missing-lifetime-in-return.rs
- Moved tests/ui/issues/issue-16774.rs to tests/ui/deref/derefmut-closure-drop-order.rs
These moves where performed using the test-manager automation tool.
Small refactor of `arena_cache` query values
Query modifier `arena_cache` automatically allocates only `Some` variant of query's value of type `Option<&'tcx T>`, so `mir_callgraph_cyclic` should've been doing it from the beginning. The same could be said for any `Result<&'tcx T, ErrorGuaranteed>` as `ErrorGuaranteed` is a zero sized type, but that requires adding a new `ArenaCached` implementation.
Make `DerefPure` dyn-incompatible
Fixes https://github.com/rust-lang/rust/issues/154619.
If `DerefPure` were dyn-compatible, a trait object of a subtrait of `DerefPure` could be created by unsize-coercing an existing type that implements `DerefPure`. But then the trait object could have its own non-pure impl of `Deref`/`DerefMut`, which is unsound, since the trait object would implement `DerefPure`. Thus, we make `DerefPure` dyn-incompatible.
r? types
Add --verbose-run-make-subprocess-output flag to suppress verbose run-make output for passing tests
- Adds `--verbose-run-make-subprocess-output` flag to `./x test` and compiletest
- `./x test --no-capture --verbose-run-make-subprocess-output=false` suppresses verbose subprocess output for passing run-make tests
- Failed tests always print their output regardless of `--verbose-run-make-subprocess-output`
- Default behavior (verbose) is unchanged
This addresses the request from @bjorn3 which needs `--no-capture` (due to `panic=abort`) but doesn't want output dumped for every passing test.
Helps with rust-lang/rust#154069
## Test plan
- [x] `./x test tests/run-make/bare-outfile --no-capture --force-rerun` — verbose output for passing test
- [x] `./x test tests/run-make/bare-outfile --no-capture --verbose-run-make-subprocess-output=false --force-rerun` — no verbose output for passing test
- [x] Failing test still dumps output with `--verbose-run-make-subprocess-output=false`
cg_ssa: transmute between scalable vectors
Like regular SIMD vectors, we can support casting between scalable vectors of integral or floating-point types without needing a temporary.
r? @Amanieu
Normalize individual predicate of `InstantiatedPredicates` inside `predicates_for_generics`
This is a cleanup to better land rust-lang/rust#155083. It allows us to wrap individual clause in `Unnormalized` wrapper. See [this comment](https://github.com/rust-lang/rust/pull/155083#discussion_r3072219035)
Besides that, this PR also adds missing normalization in some cases.
r? @lcnr
Add more robust handling of nested query cycles
This adds more robust handling of query cycle that occur while we are already printing a query cycle error. Such nested query cycle are compiler bugs and this adds special handling so that both the nested query cycle and the outer query cycle are printed. Doubly nested query cycle errors are ignored to prevent infinite recursion.
Implement EII for statics
This PR implements EII for statics. I've tried to mirror the implementation for functions in a few places, this causes some duplicate code but I'm also not really sure whether there's a clean way to merge the implementations.
This does not implement defaults for static EIIs yet, I will do that in a followup PR
Implement EII for statics
This PR implements EII for statics. I've tried to mirror the implementation for functions in a few places, this causes some duplicate code but I'm also not really sure whether there's a clean way to merge the implementations.
This does not implement defaults for static EIIs yet, I will do that in a followup PR
Fix thread::available_parallelism on WASI targets with threads
The refactoring in ba462864f1 ("std: Use more unix.rs code on WASI targets") moved WASI from its own thread module into the shared unix.rs module. However, it did not carry over the available_parallelism() implementation for WASI with threads, causing it to fall through to the unsupported catch-all. This silently regressed the support originally added in f0b7008648.
Fix this by adding WASI to the standard UNIX cfg_select branch.
Depends on rust-lang/rust#155057 (Update libc to v0.2.184).
Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for `bf16(xN)` and `i1xN`
*[View all comments](https://triagebot.infra.rust-lang.org/gh-comments/rust-lang/rust/pull/140763)*
This PR changes how LLVM intrinsics are codegen
# Explanation of the changes
## Current procedure
This is the same for all functions, LLVM intrinsics are _not_ treated specially
- We get the LLVM Type of a function simply using the argument types. For example, the following function
```rust
#[link_name = "llvm.sqrt.f32"]
fn sqrtf32(a: f32) -> f32;
```
will have LLVM type simply `f32 (f32)` due to the Rust signature
### Pros
- Simpler to implement, no extra complexity involved due to LLVM intrinsics
### Cons
- LLVM intrinsics have a well-defined signature, completely defined by their name (and if it is overloaded, the type parameters). So, this process of converting Rust signatures to LLVM signatures may not work, for example the following code generates LLVM IR without any problem
```rust
#[link_name = "llvm.sqrt.f32"]
fn sqrtf32(a: i32) -> f32;
```
but the generated LLVM IR is invalid, because it has wrong signature for the intrinsic ([Godbolt](https://godbolt.org/z/6ff9hrcd5), adding `-Zverify-llvm-ir` to it will fail compilation). I would expect this code to not compile at all instead of generating invalid IR.
- LLVM intrinsics that have types in their signature that can't be accessed from Rust (notable examples are the AMX intrinsics that have the `x86amx` type, and (almost) all intrinsics that have vectors of `i1` types) can't be linked to at all. This is a (major?) roadblock in the AMX and AVX512 support in stdarch.
- If code uses an non-existing LLVM intrinsic, even `-Zverify-llvm-ir` won't complain. Eventually it will error out due to the non-existing function (courtesy of the linker). I don't think this is a behavior we want.
## What this PR does
- When linking to **non-overloaded** intrinsics, we use the function `LLVMIntrinsicGetType` to directly get the function type of the intrinsic from LLVM.
- We then use this LLVM definition to _verify_ the Rust signature, and emit a proper error if it doesn't match, instead of silently emitting invalid IR.
- Lint if linking to deprecated or invalid LLVM intrinsics
> [!NOTE]
> This PR only focuses on non-overloaded intrinsics, overloaded can be done in a future PR
Regardless, the undermentioned functionalities work for **all** intrinsics
- If we can't find the intrinsic, we check if it has been `AutoUpgrade`d by LLVM. If not, that means it is an invalid intrinsic, and we error out.
- Don't allow intrinsics from other archs to be declared, e.g. error out if an AArch64 intrinsic is declared when we are compiling for x86
### Pros
- It is now not possible (or at least, it would require _significantly_ more leaps and bounds) to introduce invalid IR using **non-overloaded** LLVM intrinsics.
- As we are now doing the matching of Rust signatures to LLVM intrinsics ourselves, we can now add bypasses to enable linking to such non-Rust types (e.g. matching 8192-bit vectors to `x86amx` and injecting `llvm.x86.cast.vector.to.tile` and `llvm.x86.cast.tile.to.vector`s in callsite)
> [!NOTE]
> I don't intend for these bypasses to be permanent. A better approach will be introducing a `bf16` type in Rust, and allowing `repr(simd)` with `bool`s to get Rust-native `i1xN`s. These are meant to be short-time, as I mentioned, "bypass"es. They shouldn't cause any major breakage even if removed, as `link_llvm_intrinsics` is perma-unstable.
This PR adds bypasses for `bf16` (via `i16`), `bf16xN` (via `i16xN`) and `i1xN` (via `iM`, where `M` is the smallest power of 2 s.t. `M >= N`, unless `N <= 4`, where we use `M = 8`). This will unblock AVX512-VP2INTERSECT and a lot of bf16 intrinsics in stdarch. This PR also automatically destructures structs if the types don't exactly match (this is required for us to start emitting hard errors on mismmatches).
### Cons
- This only works for non-overloaded intrinsics (at least for now). Improving this to work with overloaded intrinsics too will involve significantly more work.
# Possible ways to extend this to overloaded intrinsics (future)
## Parse the mangled intrinsic name to get the type parameters
LLVM has a stable mangling of intrinsic names with type parameters (in `LLVMIntrinsicCopyOverloadedName2`), so we can parse the name to get the type parameters, and then just do the same thing.
### Pros
- For _most_ intrinsics, this will work perfectly, and is a easy way to do this.
### Cons
- The LLVM mangling is not perfectly reversible. When we have `TargetExt` types or identified structs, their name is a part of the mangling, making it impossible to reverse. Even more complexities arise when there are unnamed identified structs, as LLVM adds more mangling to the names.
- @nikic's work on LLVM intrinsics will remove the name mangling, making this approach impossible
## Use the `IITDescriptor` table and the Rust function signature
We can use the base name to get the `IITDescriptor`s of the corresponding intrinsic, and then manually implement the _matching_ logic based on the Rust signature.
### Pros
- Doesn't have the above mentioned limitation of the parsing approach, has correct behavior even when there are identified structs and `TargetExt` types. Also, fun fact, Rust exports all struct types as literal structs (unless it is emitting LLVM IR, then it always uses named identified structs, with mangled names)
### Cons
- **Doesn't** actually use the type parameters in the name, only uses the base name and the Rust signature to get the llvm signature (although we _can_ check that it is the correct name). It means there would be no way to (for example) link against `llvm.sqrt.bf16` until we have `bf16` types in Rust. Because if we are using `u16`s (or any other type) as `bf16`s, then the matcher will deduce that the signature is `u16 (u16)` not `bf16 (bf16)` (which would lead to an error because `u16` is not a valid type parameter for `llvm.sqrt`), even though the intended type parameter is specified in the name.
- Much more complex, and hard to maintain as LLVM gets new `IITDescriptorKind`s
These 2 approaches might give different results for same function. Let's take
```rust
#[link_name = "llvm.is.constant.bf16"]
fn foo(a: u16) -> bool
```
The name-based approach will decide that the type parameter is `bf16`, and the LLVM signature is `i1 (bf16)` and will inject some bitcasts at callsite.
The `IITDescriptor`-based approach will decide that the LLVM signature is `i1 (u16)`, and will see that the name given doesn't match the expected name (`llvm.is.constant.u16`), and will error out.
Reviews are welcome, as this is my first time _actually_ contributing to `rustc`
@rustbot label T-compiler A-codegen A-LLVM
r? codegen
Fixesrust-lang/rust-analyzer#21891.
Previously, the completion engine would aggressively bail out if the parent enum was marked . This pushes the visibility check down to the individual variants so they can be properly completed when accessed via a public type alias.
We want to complain on PRs that generate rustdoc warnings, but only
deploy the generate HTML on the master branch.
Also fix the existing rustdoc warning.
AI disclosure: Some Claude Opus usage.
Previously, we didn't recurse in Evaluator::create_memory_map() or
Evaluator::patch_addresses() when handling references with a known
size.
This caused problems for hover rendering on const values, which would
build a memory map for evaluated allocations and then pretty-printed
values by following references through that map.
As a result, references in the map still pointed to the original addresses,
meaning that the value pretty-printer would see the type parameters
before substitution. This could cause stack overflows on well-formed
Rust code using recursive const functions.
Add a regression test for hovering on a recursive const fn that
previously caused stack overflow.
Fixesrust-lang/rust-analyzer#21503
AI disclosure: I used Codex with GPT 5.4 to investigate the issue and
write the initial version of this commit.
GitHub actions are currently failing with:
error: unresolved link to `cfg_attr`
--> crates/ide-completion/src/context.rs:414:61
|
414 | /// Set if we are inside the predicate of a #[cfg] or #[cfg_attr].
| ^^^^^^^^ no item named `cfg_attr` in scope
|
= help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]`
= note: `-D rustdoc::broken-intra-doc-links` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(rustdoc::broken_intra_doc_links)]`
Documenting ide v0.0.0 (/home/runner/work/rust-analyzer/rust-analyzer/crates/ide)
error: could not document `ide-completion`
Use backticks to fix this.
AI disclosure: written with Claude Opus because it was marginally
faster.
Use closures more consistently in `dep_graph.rs`.
This file has several methods that take a `FnOnce() -> R` closure:
- `DepGraph::with_ignore`
- `DepGraph::with_query_deserialization`
- `DepGraph::with_anon_task`
- `DepGraphData::with_anon_task_inner`
It also has two methods that take a faux closure via an `A` argument and a `fn(TyCtxt<'tcx>, A) -> R` argument:
- DepGraph::with_task
- DepGraphData::with_task
The rationale is that the faux closure exercises tight control over what state they have access to. This seems silly when (a) they are passed a `TyCtxt`, and (b) when similar nearby functions take real closures. And they are more awkward to use, e.g. requiring multiple arguments to be gathered into a tuple. This commit changes the faux closures to real closures.
r? @Zalathar
Make the expansion of guard metavars begin guard non-terminals
While investigating something unrelated, I noticed a bug in the impl of unstable feature `macro_guard_matcher` (tracking issue: rust-lang/rust#153104). Namely, the following doesn't compile:
```rs
#![feature(macro_guard_matcher)]
macro_rules! a { ($guard:guard) => { b!($guard); }; }
macro_rules! b { ($guard:guard) => {}; }
a!(if true);
```
```
error: no rules expected `guard` metavariable
--> src/lib.rs:3:41
|
3 | macro_rules! a { ($guard:guard) => { b!($guard); }; }
| ^^^^^^ no rules expected this token in macro call
4 | macro_rules! b { ($guard:guard) => {}; }
| -------------- when calling this macro
5 | a!(if true);
| ----------- in this macro invocation
|
note: while trying to match meta-variable `$guard:guard`
--> src/lib.rs:4:19
|
4 | macro_rules! b { ($guard:guard) => {}; }
| ^^^^^^^^^^^^
= note: this error originates in the macro `a` (in Nightly builds, run with -Z macro-backtrace for more info)
```
---
While I'm still skeptical of `guard` fragment specifiers in general (although I can't quite pinpoint why), I figured I should fix this issue.
add regression test for OpenOptionsExt downstream compat
Following up on rust-lang/rust#153491, which added a warning comment there, but no automated guardrail to prevent another breaking change like rust-lang/rust#149718
This adds a simple windows-only ui test that manually implements `OpenOptionsExt`. That way, if someone accidentally adds another required method to the trait, we catch it before it reaches stable and breaks downstream crates like Tokio again.
Closesrust-lang/rust#153486
cg_llvm: scalable vectors with `simd_cast` and `simd_select`
Previously `sve_cast`'s implementation was abstracted to power both `sve_cast` and `simd_cast` which supported scalable and non-scalable vectors respectively. In anticipation of having to do this for another `simd_*` intrinsic, `sve_cast` is removed and `simd_cast` is changed to accept both scalable and non-scalable intrinsics, an approach that will scale better to the other intrinsics.
Building on the previous change, support scalable vectors with `simd_select`. Previous patches already landed the necessary changes in the implementation of this intrinsic, but didn't allow scalable vector arguments to be passed in.
delegation: support proper interaction of user-specified args and impl Traits
This PR supports usages of user-specified args with impl Traits. When there are user-specified args in child we still need to generate synthetic generic params and use them during signature inheritance:
```rust
fn foo<T, const N: usize>(f: impl FnOnce()) {}
reuse foo::<String, 123> as bar;
//desugaring
fn bar<TSynth: impl FnOnce()>(f: _) {
foo::<String, 123>(f)
}
```
When inheriting predicates we process impl Trait ones, so we need generic params to instantiate them. Other approach may involve not generating synthetic generic params and try to filter out those predicates, but fairly generating synthetic params seems more consistent?.
Fixesrust-lang/rust#154780, part of rust-lang/rust#118212.
r? @petrochenkov
Add #![unstable_removed(..)] attribute to track removed features
Adds the #![unstable_removed(..)] attribute to enable tracking removed library features.
Produce an error when a removed attribute is used.
Add a test that it works.
For https://github.com/rust-lang/rust/issues/141617
r? @jyn514
When a coroutine has too many parameters, `check_match` fails and
`construct_error` builds a MIR body with only the coroutine's computed
args (env + resume type). The user-provided signature, however, still
reflects all the parameters the user wrote. `check_signature_annotation`
then tries to `zip_eq` these two mismatched iterators, causing a panic.
Checking `tainted_by_errors` and bailing early avoids this, since
`construct_error` bodies cannot meaningfully be compared against user
annotations.
`Into::into` can't be used here because the implementations can't have
the required target feature, so `SveInto` needs to be introduced and
written by the generator
Add the SVE types (without any of the generated intrinsics) and empty
modules where the generated intrinsics will be. Enables the
`adt_const_params` crate feature that the generated intrinsics will use.
Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
Co-authored-by: Adam Gemmell <adam.gemmell@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
Matching the current behaviour for arguments, `auto_llvm_sign_conversion`
should only be required for `as_unsigned` conversions, not `into`
conversions.
`simd_reinterpret` was expected to be used when it was added as
`transmute_unchecked` requires `Sized`, but scalable vectors are now
`Sized` so `transmute_unchecked` can be used and `simd_reinterpret` was
not added in rust-lang/rust#143924.
The `SvUndef` expression is no longer necessary as a
`core::intrinsics::scalable::sve_undef` intrinsic has been introduced
to produce an undefined SVE vector, used by `svundef*` intrinsics. Other
intrinsics that used `SvUndef` now use the `svundef*` intrinsics.
Instead of generating load/store tests based on the input filename -
which no longer works given the expected input file structure of
`stdarch-gen-arm` - add a simple global context option that SVE specs can
set.
Building on the previous change, support scalable vectors with
`simd_select`. Previous patches already landed the necessary changes in
the implementation of this intrinsic, but didn't allow scalable vector
arguments to be passed in.
Previously `sve_cast`'s implementation was abstracted to power both
`sve_cast` and `simd_cast` which supported scalable and non-scalable
vectors respectively. In anticipation of having to do this for another
`simd_*` intrinsic, `sve_cast` is removed and `simd_cast` is changed to
accept both scalable and non-scalable intrinsics, an approach that will
scale better to the other intrinsics.
For the unbalanced backtick check. This fix is arguably a hack, however
the original tidy check implementation is already based on heuristics
and so are likewise fuzzy. This is probably fine in practice.
Co-authored-by: Waffle Lapkin <waffle.lapkin@gmail.com>
The spdx-rs crate is no longer maintained and is behind on its own dependency
updates. The only function that collect-license-metadata uses from it is
`spdx_rs::parsers::spdx_from_tag_value`, which parses the output of the `reuse`
tool to extract file names, licences and copyright text.
Replace this with a small minimal parser that handles just the subset
of the SPDX tag-value format that is needed: `Tag: Value` line pairs
and multi-line `<text>...</text>` blocks.
Coincidentally, this gets rid of the last transitive dependency on syn v1.
allow `windows-gnu` targets to embed gdb visualizer scripts
Pretty straigthforward, works exactly the same as any other `*-gnu` target so i'm not sure why it wasn't enabled already.
- Fixes API calls to existing GenMC functions, which now
return the number by which event_count should be increased
- Properly handles "Invalid" results (where applicable)
- Introduces handle_non_atomic_{store,load} in Miri and
ensures they call their GenMC counterparts.
- Adds NA handlers in Miri's GenmcCtx, and renames the previous
handle_{load,store} to handle_atomic_{load,store}.
- Removes handle_load_reset_if_none, the only purpose of which
was to decrease the event counter.
- Removes dec_pos(), which is now also unnecessary.
Add a flag to control verbose subprocess output for run-make tests. When using --no-capture on panic=abort test suites like cg_clif, passing test output can flood the terminal. This flag (default true) lets users opt out via --verbose-run-make-subprocess-output=false.
Extract a private print_command_output helper in run-make-support to avoid inlining the output logic in handle_failed_output, ensuring failures always print regardless of the flag.
Use Vec::push_mut when adding a chunk to arenas
This fixes https://github.com/rust-lang/rust/issues/155148, which may or may not be worth fixing on its own merits, but I think `Vec::push_mut` also makes the code nicer.
Fix ICE in `span_extend_prev_while` with multibyte characters
Fixes https://github.com/rust-lang/rust/issues/155037
The function assumed that the character found by `rfind` was always one byte wide, using a hardcoded `1` instead of `c.len_utf8()`. When a multibyte character appeared immediately before the span, this caused the resulting span to point into the middle of a UTF-8 sequence, triggering an assertion failure in `bytepos_to_file_charpos`.
Hexagon: add scalar arch-version target features (v60-v79, audio)
Add target features corresponding to Hexagon LLVM CPU generations to complement the existing HVX vector features. These are needed for gating scalar intrinsics by architecture version.
New features: audio, v60, v62, v65, v66, v67, v68, v69, v71, v73, v75, v79
Each version implies the previous (e.g. v68 implies v67 which implies v66, etc.), matching LLVM's ArchV60-ArchV79 subtarget features.
Also adds hexagon revisions to the feature-hierarchy test to verify the implied feature chains work correctly.
Fix ICE when reporting host-effect errors for const Fn HRTBs in next trait solver
Avoid leaking bound vars into the diagnostic selection path for HRTB host-effect predicates.
Closesrust-lang/rust#151894 .
In the newer GenMC version, two RMWs might read from the same
write during an exploration. In such a case, the exploration
has to be dropped so that an alternative one can be explored.
Miri did not provide a way to completely stop an execution
without throwing an error. This commit adds a new TerminationInfo
case in diagnostics that is used by GenMC to signal that an
execution should be aborted.
On the API side, a new result field is introduced.
The new parameter allows to step the event index by an arbitrary
amount. The functions now return void.
This is a preparatory commit that lays the ground before adjusting
all API calls to match the new GenMC API. The code does not
compile.
The "ExecutionGraph" GenMC folder has been renamed to "Execution",
and there is a GenMC class named ExecutionState.
This commit adjust the include paths in some cpp files, and renames
an enum in lib.rs (ExecutionState->ExecutionStatus).
Update hashbrown to 0.17
The main benefit of this update is to include one potential UB fix and one bug; relevant changelog entries:
* Fixed potential UB in `RawTableInner::fallible_with_capacity` (rust-lang/hashbrown#692)
* Fixed incorrect length if a hasher panics during rehash (rust-lang/hashbrown#710)
cc @Amanieu
Also cc @RalfJung who had also noticed the UB issue with `-Zmiri-recursive-validation`.
The refactoring in ba462864f1 ("std: Use more unix.rs code on WASI
targets") moved WASI from its own thread module into the shared unix.rs
module. However, it did not carry over the available_parallelism()
implementation for WASI, causing it to fall through to the unsupported
catch-all. This silently regressed the support originally added in
f0b7008648.
Fix this by adding WASI to the sysconf-based cfg_select arm alongside
other platforms that use libc::sysconf(_SC_NPROCESSORS_ONLN). This
delegates to wasi-libc, which currently always returns 1 but opens up
the possibility for wasi-libc to report actual processor counts in the
future.
This requires libc to export _SC_NPROCESSORS_ONLN for WASI targets,
which has been added in libc 0.2.184.
unsafe keyword docs: bring back unsafe_op_in_unsafe_fn lint discussion
@traviscross in rust-lang/rust#141471 you asked me to also update the text to account for the edition change. Apparently I did that by entirely removing this part of the discussion (except for a dangling forward reference, a "see below"). Given that old editions still exist and given that `unsafe_op_in_unsafe_fn` is just a lint so the old behavior also still exists on new editions, I am no longer sure that was a good idea, so this brings back the old text with some editing to explain the current situation.
Deprioritize doc(hidden) re-exports in diagnostic paths
Fixesrust-lang/rust#153477.
This is the other half of rust-lang/rust#99698, which fixed the case where the *parent module* is `#[doc(hidden)]` but left the case where the re-export itself is `#[doc(hidden)]` as a FIXME (with a tracking test in `dont-suggest-doc-hidden-variant-for-enum/hidden-child.rs`).
The problem: when a crate does `#[doc(hidden)] pub use core::error::Error`, diagnostics pick up the hidden re-export path instead of the canonical one. For example, `snafu::Error` instead of `std::error::Error`.
Two changes:
In `visible_parent_map`, the `add_child` closure now checks whether the re-export itself is `#[doc(hidden)]` via `reexport_chain` and sends it to `fallback_map`, same treatment as doc-hidden parents and underscore re-exports.
`should_encode_attrs` now returns `true` for `DefKind::Use`. Without this, `#[doc(hidden)]` on `use` items was never written to crate metadata, so `is_doc_hidden` always returned `false` cross-crate. This was the actual root cause, the check in `visible_parent_map` alone isn't enough if the attribute isn't in the metadata.
The existing FIXME test now serves as the regression test. The `.stderr` goes from suggesting `hidden_child::__private::Some(1i32)` to just `Some(1i32)`.
cc @eggyal
Patch musl's CVE-2026-6042 and CVE-2026-40200
- [CVE-2026-6042] is a denial of service in `iconv`.
- [CVE-2026-40200] is an out-of-bounds write in `qsort`.
Neither is relevant to Rust itself, but they could be used in mixed-language projects that link with our `self-contained/libc.a`.
[CVE-2026-6042]: https://www.openwall.com/lists/oss-security/2026/04/09/19
[CVE-2026-40200]: https://www.openwall.com/lists/musl/2026/04/10/3
replace <name> @ ty::AliasTy matches with just using args: <name>_args
ref rust-lang/rust#154941
replace `<name> @ ty::AliasTy` matches with just using `args: <name>_args`
I updated all occurrences where <name> @ ty::AliasTy became unnecessary after the change. In cases where both forms are still used, no changes were made.
r? @WaffleLapkin
fix spurious test failure in `metadata_access_times`
Fixesrust-lang/rust#148408
The metadata_access_times test checks if the creation of a file occurs before another file, this check happens only on Linux. While on Win and Macos we check only that the created metadata is available. Given that the SystemTime is non monotonic as Instant this test could result in failures when the system clock changes.
add `cfg(target_object_format = "...")`
tracking issue: https://github.com/rust-lang/rust/issues/152586
I'm implementing the predicate as `target_object_format`, because that's what is useful to me (for testing `#[link_section = "..."]` where `mach-o` has some extra restrictions) and maps cleanly to the `BinaryFormat` enum that is used internally. There is still room for a future `target_executable_format` when there is a use case.
cc @joshtriplett as the lang sponsor of this feature, @workingjubilee as the author of the proposal.
r? JonathanBrouwer a sidequest from the sidequest that is https://github.com/rust-lang/rust/pull/155065
This allows us to simplify expansion of cfg_attr in `expand_cfg_attr()`, and also fixes a bunch of bugs like expansion of `doc = macro!()` inside `cfg_attr`.
`ty::Alias`: replace `def_id: did` with `def_id`
related issue: https://github.com/rust-lang/rust/issues/154941
tackling this task:
- [x] replace def_id: did with def_id where possible
r? @WaffleLapkin
Make Box/Rc/Arc::into_array allocator-aware (and add doctest)
Tracking issue for `alloc_slice_into_array`: https://github.com/rust-lang/rust/issues/148082
Tracking issue for `allocator_api`: https://github.com/rust-lang/rust/issues/32838
Make the `into_array` methods on `Box`, `Rc`, and `Arc` allocator-aware.
I think the allocator-aware-ness should not be observable on stable, so these should not be additionally (comment-)gated behind `feature(allocator_api)`, just like e.g. `Box::leak` and `Vec::into_boxed_slice`. The added doctests do not use `feature(allocator_api)`.
@rustbot label T-libs-api
Test(lib/sync): Fix `test_rwlock_max_readers` for x86 Win7
The test recently added in rust-lang/rust#153555 currently systematically deadlocks when running it under i686 Windows 7, but not x86_64 that passes it fine. This therefore fixes the test for the target.
Empirically, the correct value for `MAX_READERS` seems to be `2^28 - 1`: removing the `- 1` re-introduces the deadlock, at least under our testing environment. This fix thus uses this value. However, I have no real justification to support that, because I find myself a bit at a loss when comparing the implementation details, the comment added above the test and what the current value is; some help would therefore be nice in this aspect. Also, the value change is restricted to 32-bit Win7 as there is no evidence to support it should be done for other targets.
cc @roblabla
@rustbot label O-windows-msvc O-windows-7 O-x86_32 A-atomic T-libs
Update libc to v0.2.184
This includes the WASI _SC_* sysconf constants needed for `thread::available_parallelism` on WASI targets (rust-lang/rust#153604).
* Extend `core::char`'s documentation of casing issues
* Fix typos
* Fix typo
Co-authored-by: GrigorenkoPV <GrigorenkoPV+github@yandex.ru>
* Document maximum 3x character expansion
This is guaranteed by Unicode.
* Fix error in `str` casing method docs
Use `black_box` on SIMD intrinsic inputs to prevent the compiler from
constant folding SIMD operations, ensuring the corresponding SIMD
instructions are actually emitted and covered by tests.
Rollup of 3 pull requests
Successful merges:
- rust-lang/rust#154827 (distinguish "expected a single argument" and "expected an argument" on attribute parsing)
- rust-lang/rust#155104 (bootstrap: auto-patch libgccjit.so for NixOS)
- rust-lang/rust#155120 (Use a linting node closer the parsing of `#[cfg_attr]`)
Use a linting node closer the parsing of `#[cfg_attr]`
The parsing of `#[cfg_attr]` unconditionally used the crate-root as a linting node to attach lints, but the `unexpected_cfgs` lint can fire when parsing the attribute and users expect to be able to allow it at places other than the crate-root.
Let's instead use the linting node id, which is unfortunately always the parent but that's better than the crate-root when you are in a sub-module.
The parsing of `#[cfg]` and other already use the expansion linting node id, so no change required there.
Related to https://github.com/rust-lang/rust/issues/155118
bootstrap: auto-patch libgccjit.so for NixOS
Currently all downloaded rustc and LLVM components are auto patched on NixOS, but this is not done for libgccjit.so, so when GCC backend is enabled on NixOS, the build ICEs with errors like this:
thread 'rustc' (2286205) panicked at compiler/rustc_codegen_gcc/src/lib.rs:191:9:
Cannot load libgccjit.so: libzstd.so.1: cannot open shared object file: No such file or directory
Fix this by auto-patch libgccjit.so, too. `zstd` is added to the dependency environment.
Suggest similar target names on unrecognized `--target`
When an unrecognized `--target` is passed check the list of available targets and suggest the closest matching built-in target as a help message.
### Before
```
error: error loading target specification: could not find specification for target "x86_64-linux-gnu"
= help: run `rustc --print target-list` for a list of built-in targets
```
### After
```
error: error loading target specification: could not find specification for target "x86_64-linux-gnu"
= help: run `rustc --print target-list` for a list of built-in targets
= help: did you mean `x86_64-unknown-linux-gnu`?
```
Regarding the expected test case in https://github.com/rust-lang/rust/issues/155085#issuecomment-4222050023 the `edit_distance_with_substrings` was used over `edit_distance` because in the case of `x86_64-linux-gnu` the `edit_distance` would return `x86_64-linux-android` instead of `x86_64-unknown-linux-gnu`
rust-lang/rust#155085
Semantic checks of `impl` restrictions
This PR implements semantic checks for `impl` restrictions proposed in the [Restrictions RFC](https://rust-lang.github.io/rfcs/3323-restrictions.html) (Tracking Issue rust-lang/rust#105077), and linked to a [GSOC idea/proposal](142433eb3b (implementing-impl-and-mut-restrictions)).
It lowers the resolved paths of `impl` restrictions from the AST to HIR and into `TraitDef`, and integrates the checks into the coherence phase by extending `check_impl`. As parsing (rust-lang/rust#152943) and path resolution (rust-lang/rust#153556) have already been implemented, this PR provides a working implementation of `impl` restrictions.
r? @Urgau
cc @jhpratt
Semantic checks of `impl` restrictions
This PR implements semantic checks for `impl` restrictions proposed in the [Restrictions RFC](https://rust-lang.github.io/rfcs/3323-restrictions.html) (Tracking Issue rust-lang/rust#105077), and linked to a [GSOC idea/proposal](142433eb3b (implementing-impl-and-mut-restrictions)).
It lowers the resolved paths of `impl` restrictions from the AST to HIR and into `TraitDef`, and integrates the checks into the coherence phase by extending `check_impl`. As parsing (rust-lang/rust#152943) and path resolution (rust-lang/rust#153556) have already been implemented, this PR provides a working implementation of `impl` restrictions.
r? @Urgau
cc @jhpratt
A `Duration` is essentially a 94-bit value (64-bit sec and ~30-bit ns),
so there's some inherent loss when converting to floating-point for
`mul_f64` and `div_f64`. We could go to greater lengths to compute these
with more accuracy, like rust-lang/rust#150933 or rust-lang/rust#154107,
but it's not clear that it's worth the effort. The least we can do is
document that some rounding is to be expected, which this commit does
with simple examples that only multiply or divide by `1.0`.
This also changes the `f32` methods to just forward to `f64`, so we keep
more of that duration precision, as the range is otherwise much more
limited there.
Rollup of 6 pull requests
Successful merges:
- rust-lang/rust#152901 (Introduce a `#[diagnostic::on_unknown]` attribute)
- rust-lang/rust#155078 (Reject dangling attributes in where clauses)
- rust-lang/rust#154449 (Invert dependency between `rustc_errors` and `rustc_abi`.)
- rust-lang/rust#154646 (Add suggestion to `.to_owned()` used on `Cow` when borrowing)
- rust-lang/rust#154993 (compiletest: pass -Zunstable-options for unpretty and no-codegen paths)
- rust-lang/rust#155097 (Make `rustc_attr_parsing::SharedContext::emit_lint` take a `MultiSpan` instead of a `Span`)
Add suggestion to `.to_owned()` used on `Cow` when borrowing
fixesrust-lang/rust#144792
supersedes rust-lang/rust#144925 with the review comments addressed
the tests suggested from @Kivooeo from https://github.com/rust-lang/rust/pull/144925#discussion_r2252703007 didn't work entirely, because these tests failed due to error `[E0308]` mismatched types, which actually already provides a suggestion, that actually makes the code compile:
```
$ cargo check
error[E0308]: mismatched types
--> src/main.rs:3:5
|
1 | fn test_cow_suggestion() -> String {
| ------ expected `std::string::String` because of return type
2 | let os_string = std::ffi::OsString::from("test");
3 | os_string.to_string_lossy().to_owned()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `String`, found `Cow<'_, str>`
|
= note: expected struct `std::string::String`
found enum `std::borrow::Cow<'_, str>`
help: try using a conversion method
|
3 | os_string.to_string_lossy().to_owned().to_string()
| ++++++++++++
```
now this suggestion is of course not good or efficient code, but via clippy with `-Wclippy::nursery` lint group you can actually get to the correct code, so i don't think this is too much of an issue:
<details>
<summary>the clippy suggestions</summary>
```
$ cargo clippy -- -Wclippy::nursery
warning: this `to_owned` call clones the `Cow<'_, str>` itself and does not cause its contents to become owned
--> src/main.rs:3:5
|
3 | os_string.to_string_lossy().to_owned().to_string()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/beta/index.html#suspicious_to_owned
= note: `#[warn(clippy::suspicious_to_owned)]` on by default
help: depending on intent, either make the `Cow` an `Owned` variant
|
3 | os_string.to_string_lossy().into_owned().to_string()
| ++
help: or clone the `Cow` itself
|
3 - os_string.to_string_lossy().to_owned().to_string()
3 + os_string.to_string_lossy().clone().to_string()
|
$ # apply first suggestion
$ cargo c -- -Wclippy::nursery
warning: redundant clone
--> src/main.rs:3:45
|
3 | os_string.to_string_lossy().into_owned().to_string()
| ^^^^^^^^^^^^ help: remove this
|
note: this value is dropped without further use
--> src/main.rs:3:5
|
3 | os_string.to_string_lossy().into_owned().to_string()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= help: for further information visit https://rust-lang.github.io/rust-clippy/beta/index.html#redundant_clone
= note: `-W clippy::redundant-clone` implied by `-W clippy::nursery`
= help: to override `-W clippy::nursery` add `#[allow(clippy::redundant_clone)]`
```
</details>
the actual error that we are looking for is error `[E0515]`, cannot return value referencing local variable, which was only present in the original issue due to automatic type inference assuming you want to return a cloned `Cow<'_, str>`, which is of course not possible. this is why i took the original test functions and turned them into closures, where it's less obvious that it's trying to return the wrong type.
r? davidtwco
(because you reviewed the last attempt)
(also, let me know if i should squash this down to one commit and add myself as the co-contributor)
Example
---
```rust
fn main() {
<Bar as Foo>::foo$0
}
mod m {
pub fn foo() {}
}
struct Bar;
trait Foo {}
impl Foo for Bar {}
```
**Before this PR**
```
fn foo() (use m::foo) fn()
```
**After this PR**
no any imports
Currently all downloaded rustc and LLVM components are auto patched on
NixOS, but this is not done for libgccjit.so, so when GCC backend is
enabled on NixOS, the build ICEs with errors like this:
thread 'rustc' (2286205) panicked at compiler/rustc_codegen_gcc/src/lib.rs:191:9:
Cannot load libgccjit.so: libzstd.so.1: cannot open shared object file: No such file or directory
Fix this by auto-patch libgccjit.so, too. `zstd` is added to the dependency
environment.
Signed-off-by: Gary Guo <gary@garyguo.net>
When `rustfmt.overrideCommand` is a relative path, it's joined with the
workspace root to make it an absolute path. Without this the command
path can't be resolved, especially because rustfmt changes the cwd to
make sure rustfmt.toml works correctly.
Currently `run_rustfmt` only does this when it finds a `target_spec`
using `target_spec_for_file` which only works for the root file of the
target.
This commit changes it to use `TargetSpec::from_file` which works for
any file in the crate.
Implement `__clear_cache` for Hexagon targets in Rust. Hexagon has
separate instruction and data caches, so this flushes dirty data cache
lines with `dccleaninva`, invalidates stale instruction cache lines
with `icinva`, then issues an `isync` barrier.
Based on the compiler-rt implementation from
llvm/llvm-project#188411.
In cg_gcc ModuleBuffer already only contains a path anyway. And for
moving LTO into -Zlink-only we will need to serialize MaybeLtoModules.
By storing a path cached modules we avoid writing them to the disk a
second time during serialization of MaybeLtoModules.
Add target features corresponding to Hexagon LLVM CPU generations to
complement the existing HVX vector features. These are needed for
gating scalar intrinsics by architecture version.
New features: audio, v60, v62, v65, v66, v67, v68, v69, v71, v73, v75, v79
Each version implies the previous (e.g. v68 implies v67 which implies
v66, etc.), matching LLVM's ArchV60-ArchV79 subtarget features.
Also adds hexagon revisions to the feature-hierarchy test to verify
the implied feature chains work correctly.
Use fine grained component-wise span tracking in use trees
This often produces nicer spans and even doesn't need a Span field anymore (not that I expect the unused field to affect any perf, but still neat).
The recently-added test currently systematically deadlocks when running
it under i686 Windows 7, but not x86_64 that passes it fine. This
therefore fixes the test for the target.
Empirically, the correct value for `MAX_READERS` seems to be `2^28 - 1`:
removing the `- 1` re-introduces the deadlock, at least under our
testing environment. This fix thus uses this value. However, I have no
real justification to support that, because I find myself a bit at a
loss when comparing the implementation details, the comment added above
the test and what the current value is; some help would therefore be
nice in this aspect. Also, the value change is restricted to 32-bit Win7
as there is no evidence to support it should be done for other targets.
Signed-off-by: Paul Mabileau <paul.mabileau@harfanglab.fr>
This impl skips:
- All doc comments
- A handful of other attributes, mostly `rustc_*` ones related to
incremental compilation testing.
This skipping originated in #36025 and was extended a couple of times,
e.g. in #36370. Those PRs don't have any explanation of why the skipping
exists. Perhaps the reasoning was that doc comments should only affect
rustdoc and rustdoc doesn't use incremental compilation? But doc
comments end up in metadata, and there is a query `attrs_for_def` that
returns a `&'tcx [hir::Attribute]`. So skipping some attributes just
seems plainly wrong.
This commit removes the impl, which means `[hir::Attribute]` hashing
falls back to the default impl for `[T]`. This has no noticeable effect
on the test suite. It does slightly hurt performance, because of the doc
comments. This perf regression seems worth it for the correctness
benefits.
Add an assembly implementation for roundeven which also works for
`rint`, similar to the existing `ceil` and `floor` implementations. This
resolves cases where values close to the *.5 boundary would round the
incorrect direction, such as -519629176421.49976 (tested in
`case_list`).
This implements `-Z allow-partial-mitigations` as an unstable option,
currently with support for control-flow-guard and stack-protector.
As a difference from the RFC, we have `-Z allow-partial-mitigations=!foo`
rather than `-Z deny-partial-mitigations=foo`, since I couldn't find an easy
way to have an allow/deny pair of flags where the latter flag wins.
To allow for stabilization, this is only enabled starting from the next edition. Maybe a
better policy is possible (bikeshed).
The test array is sorted by name at compile time. When `--exact` is
passed in, use binary search for O(f log n) lookups instead of an O(n)
linear scan, under the assumption that f << n (which is true for the
most relevant cases).
This is important for Miri, where the interpreted execution makes the
linear scan very expensive.
I measured this against a repo with 1000 empty tests, running
`cargo +stage1 miri nextest run test_00` (100 tests) under hyperfine:
* Before (linear scan): 49.7s ± 0.6s
* After (binary search): 41.9s ± 0.2s (-15.7%)
I also tried a few other variations (particularly swapping matching tests to the front of the list + truncating the list), but the index + swap_remove approach proved to be the fastest.
Questions:
- [ ] To be conservative, I've assumed that test_main can potentially receive an unsorted list of tests. Is this assumption correct?
After performance concers on the `nonminimal_bool` lint, we [performed a
crater run](https://github.com/rust-lang/rust/issues/153883)
This crater run revealed that in 19120 suggestions taken from 1.3
million crates, only about 36% had resulted in multi-terminal
suggestions (suggestions that were not only a single boolean).
This suggests that most cases of this lint firing, the expression that
triggered was pretty simple. And thus, we should not take such a huge
toll for a lint that isn't that useful.
In the future, a rewrite of that `bool_expr` function could be very
useful to alleviate the performance toll. Because clearly running the
Quine McCluskey algorithm on all those boolean operations is not ideal.
---
## Performance report:
`cargo clippy` -> 5,077,447,157 icount
`cargo check` -> 3,629,576,891 icount
So the Clippy that `rustup` delivers is about 1.4b instructions more
than `cargo check`.
`NonminimalBool` lint pass -> 318,169,034
$$\frac{nonminimal\\_bool}{clippy-check}*100 = 21.97496844$$
So, the `NonminimalBool` lint pass is about 22% of all Clippy-exclusive
instruction count.
---
After this change, we can now compare the Clippy BUILT FROM MASTER, NOT
DELIVERED BY RUSTUP, with the Clippy from this PR.
`master/target/release/cargo-clippy` -> 5,296,838,955 (Slower than
Rustup)
`pr/target/release/cargo-clippy` -> 4,977,035,941.
So, $master - PR = 319803014$, which is the exact icount of
`Nonminimal_bool` and about 22% of Clippy's whole execution time.
Profiled on `syn-2.0.71`, with Callgrind.
changelog:[`nonminimal_bool`]: Move to `pedantic`.
changelog:[`overly_complex_bool_expr`]: Move to `pedantic`.
This is going to be used as part of more thoroughly checking whether we
can change the type of an expression. e.g. `range_plus_one` suggests
changing `Range` to `RangeInclusive`.
changelog: none
In some cases, removing a cast that looks unnecessary can
still change type inference, even when the cast is to the
expected same type.
The lint now handles casts that flow through
intermediate expressions (e.g. calls, blocks, let
bindings, loops...). It also treats placeholder
generics (e.g. `::<_>`) as inference sensitive.
Added regression tests with similar behavior
as the original bug, some edge cases and
tests to check if false negative cases
weren't created.
Closesrust-lang/rust-clippy#16449
changelog: [`unnecessary_cast`]: fixed a suggestion to remove a cast
that can cause a compilation error if followed.
closes: rust-lang/rust-clippy#16768
I agree with the:
> importing it just to get the side effects of the trait being in scope
(anonymously, via as _) is not renaming it...
even without changing the name, we still not able to see it's original
name when calling a trait method, so I think this should be fine.
---
changelog: [`unsafe_removed_from_name`]: skip linting when renaming to
'_'
Closesrust-lang/rust-clippy#16751
changelog: [`question_mark`] fix FN for manual unwrap with `if let` or
`match`
changelog: [`question_mark`] fix FN when the match scrutinee is behind
reference
changelog: [`question_mark`] fix FN when match binding is behind `ref`
or `mut`
Add callee-saved register save/restore routines for three hexagon ABIs
(abi1, abi2, legacy) and a double-word loop memcpy implementation. Also
add a FALLTHROUGH_TAIL_CALL macro to func_macro.s for chaining function
entry points without branches.
Refer to c1fd7d7a1f/compiler-rt/lib/builtins/hexagon for corresponding clang-rt hexagon builtin source.
also removes E0452 and splits
`tests/rustdoc-ui/lints/renamed-lint-still-applies` into 2 tests
this is because of delayed warn lint being lost on compiler aborting on
error
In some cases, removing a cast that looks unnecessary
can still change type inference, even when the cast is
to the expected same type.
The lint now handles casts that flow through
intermediate expressions (e.g. calls, blocks, let
bindings, loops...). It also treats placeholder
generics (e.g. `::<_>`) as inference sensitive.
Added regression tests with similar behavior
as the original bug, some edge cases and
tests to check if false negative cases
weren't created.
Closes#16449
These no longer test just softfloat and hardfloat, but also the fallback
implementations in `mem` compared to those that make use of assembly.
Change the baseline names to be more accurate of the difference.
This was needed while some codegen backends did not support inline
assembly, or ran into circular issues using vector intrinsics. All such
issues have since been resolved with the in-tree backends. The remaining
need was to be able to toggle these features in tests, which we can do
via the enabled-by-default `arch` feature. Since there aren't any cases
requiring `force-soft-float`, remove its functionality and deprecate it.
It is possible that future codegen backends may have a similar need to
disable inline assembly until pairity with the LLVM backend can be
reached. In these cases rather than having `force-soft-float`, it would
be better to have rustc provide a `cfg(target_supports_inline_asm)`.
`build.rs` can then do something like:
let nightly = cfg!(feature = "compiler-builtins") || cfg!(feature = "unstable");
let asm_support = env::var("CARGO_CFG_TARGET_SUPPORTS_INLINE_ASM").is_ok();
let arch_enabled = cfg!(feature = "arch") && (!nightly || (nightly && asm_support));
set_cfg("arch_enabled", arch_enabled);
This is about what we have now with `cfg(target_has_reliable_f16)` and
`cfg(target_has_reliable_f128)` being set by rustc, which is
significantly easier to use than the `feature = "no-f16-f128"` that it
replaced. Having rustc directly tell us what it supports means we don't
need to bubble subtractive options up to bootstrap via a chain of Cargo
features that aren't really meant to support disabling things.
I'm sketching this out for future reference since it seems likely that
the need comes back up eventually.
Unfortunately the `gh` CLI tool can't yet download non-zipped archives.
Attempting to do so says:
error downloading baseline-icount-i686-202604011355-ba4c48868cad.tar.xz: error extracting zip archive: zip: not a valid zip file
Drop this change until the CLI is updated.
This reverts commit 0a57b9e3eda70c3673815fc47fad137a3c62da98.
Implement saturating, checked, and strict casting between
signed and unsigned integer primitives of the same bit-width.
Add `cast_integer` function to `overflow_panic.rs`
Make `libm` and `compiler-builtins` use the same configuration:
* By default there is an `arch` feature which allows `core::arch` and
inline assembly.
* Disabling the `arch` feature turns these off.
Positive feature flags are easier to reason about than negative, so this
will allow for some build script cleanup as well.
`mem` only enables the unmangled names; the functions are always
available via mangled names, so this doesn't have any purpose in our
tests. Thus, remove it from `builtins-test`.
The remaining `feature = "mem"` configuration in tests is for the
`aeabi_mem*` files, which call the compiler-builtins functions via
extern definitions. Move these to builtins-test-intrinsics, which is the
home of other tests that require unmangled symbols. Unfortunately these
tests have apparently not worked for a long time; this situation is
unchanged.
Ensure that our compiler-builtins is providing the runtime, so we can
see the effect of changes in c-b on libm functions. This was happening
implicitly before because the `mangled-names` feature was not enabled in
tests, so unmangled names were exposed. In commit "c-b: Change the
`mangled-names` feature to `unmangled-names`" things were reversed,
meaning the unmangled names are no longer exposed by default, so our
benches started using the platform symbols. (Hence apparent regressions
in fmaf128, ldexpf128, powif128, and scalbnf128).
This feature is somewhat backwards because the mangled names are always
available; enabling the `mangled-names` feature disables unmangled
names. This was likely somehow related to default features when the
crate was published on crates.io.
Rename the feature and reverse the logic such that unmangled names are
exposed when the feature `unmangled-names` is enabled.
Note that this changes some benchmarking logic; see the following commit
message for details.
This isn't used anywhere in CI and there doesn't seem to be a reason
that it would need to be toggled. Enable `mangled-names` on the
`compiler-builtins` dependency by default and remove the from
`builtins-test`.
As we port more correctly rounded implementatinos from CORE-MATH, it
would be nice to keep the existing versions around since they are
simpler, typically smaller and faster, and easier to port to other float
types. The implementations have also been reasonably well tested.
Introduce an `approx` module that will serve as a home for these. As the
first member, add back the old `cbrt` implementation that was replaced
in 75a7f3df3ed7 ("Port the CORE-MATH version of `cbrt`").
This file has several methods that take a `FnOnce() -> R` closure:
- `DepGraph::with_ignore`
- `DepGraph::with_query_deserialization`
- `DepGraph::with_anon_task`
- `DepGraphData::with_anon_task_inner`
It also has two methods that take a faux closure via an `A` argument and
a `fn(TyCtxt<'tcx>, A) -> R` argument:
- DepGraph::with_task
- DepGraphData::with_task
The rationale is that the faux closure exercises tight control over what
state they have access to. This seems silly when (a) they are passed a
`TyCtxt`, and (b) when similar nearby functions take real closures. And
they are more awkward to use, e.g. requiring multiple arguments to be
gathered into a tuple. This commit changes the faux closures to real
closures.
Fixes https://github.com/rust-lang/rust/issues/154619.
If `DerefPure` were dyn-compatible, a trait object of a subtrait of
`DerefPure` could be created by unsize-coercing an existing type that
implements `DerefPure`. But then the trait object could have its own
non-pure impl of `Deref`/`DerefMut`, which is unsound, since the trait
object would implement `DerefPure`. Thus, we make `DerefPure`
dyn-incompatible.
We use this option for both `f32`- and `f64`-related configuration, but
the original SSE only had support for single-precision operations.
Update this config to check for the SSE2 feature instead, which includes
double-precision support.
In practice this config is mostly used to differentiate between the i586
target (no SSE required) and the i686 target (SSE2 required) so for that
purpose, the existing behavior is fine. Building on an i586 baseline
with SSE enabled (but not sse2) also isn't really something we worry
about, so this change is mostly only for improving code readability.
The libm and c-b versions of these are (intentionally) near identical.
Switch c-b to use the libm versions rather than having its own
definitions, which allows cleaning up a significant amount of code.
Split functions across files so `arch/` closer mirrors the top-level
`math` directory. Similar operations are still kept in the same file
since many of these functions are pretty tiny.
This will make it a bit easier to extend assembly implementations
without winding up with cluttered files, and helps avoid false positives
in the ci-util.py checks for changed operations.
Move arch-specific files to an arch-named directory with a name based on
whatever most of the operations in the file are, in preparation for
splitting the file up. Moving to these names in a separate commit is
done as a git hack to keep as much of the blame intact as possible,
without needing `-M` or `-C`.
Note that libm does not build after this commit. The next commit
resolves this.
Currently an exact xfail result is needed on platforms that have variability
(i586) but this is awkward to work with, especially for bessel
functions. Change this to allow `SpecialCase` to be used.
The current flow is somewhat confusing in what is an inaccuracy due to
musl (either from implementation or from problems in the C ABI that we
avoid) and what is an inaccuracy in our library on specific platforms.
Clean up the structure here, which allows for some more narrow bounds.
The icount benchmarks are significantly more reliable, and I don't think
these results get looked at too much. They can be run locally if needed,
so save the CI time here.
Having them as part of the `LazyLock` means that if something is
unsorted, the macro panics and produces a lot of warnings. Move these to
a test instead.
This file is already used in two places and was going to be needed in
another. Turning it into its own crate makes things easier to work with,
and allows for the removal of a few `allow(dead_code)` instances.
* Add support for Hexagon HVX
Add vendor module and tests for Qualcomm Hexagon HVX (Hexagon Vector
eXtension) SIMD support. HVX provides wide vector operations in either
64-byte (512-bit) or 128-byte (1024-bit) mode.
Note: u8x128/i8x128 types are not included because portable-simd
currently limits lane count to 64 (bitmask operations use u64).
In 128-byte HVX mode, u8x64 maps to a half-vector (512-bit).
* fixup! Add support for Hexagon HVX
fixup! Add support for Hexagon HVX
Address reviewer feedback:
- Remove hexagon_hvx test file (existing tests suffice with -C flags)
- Move HvxVector imports into their respective cfg modules
- Change u8x128/i8x128 comment to FIXME for discoverability
Avoid two of its uses in diagnostic reporting and effective visibility collection.
The method is only supposed to be used inside the import resolution algorithm, and the removed uses happened after import resolution already converged.
Some comments are also added.
After performance concers on the `nonminimal_bool` lint, we performed a
crater run (rust-lang/rust issue number 153883).
This crater run revealed that in 19120 suggestions taken from 1.3
million crates, only about 36% had resulted in multi-terminal
suggestions (suggestions that were not only a single boolean).
This suggests that most cases of this lint firing, the expression that
triggered was pretty simple. And thus, we should not take such a huge
toll for a lint that isn't that useful.
changelog:[`nonminimal_bool`]: Move to `pedantic`.
changelog:[`overly_complex_bool_expr`]: Move to `pedantic`.
Now that tests have moved to using argument types instead of a whole-
function float type, remove `FTy` and its relevant configuration. This
will make it possible to use the same infrastructure for functions that
don't have any floats as arguments, or don't have any at all.
Some uses of `FTy` have been replaced with the `Group` enum, e.g. for
match arm patterns and selecting extensive tests. Anything that doesn't
have float types in the signature will be in the `Integer` category.
We can always access individual arguments rather than relying on the
common `FTy` type. This is a cleaner design anyway since it handles
functions with integers in the signature better.
The .dockerenv check was a workaround for Docker CI where the
checkout is mounted read-only. However, its presence does not reliably
indicate that the filesystem is unwritable.
Use CARGO_TARGET_DIR as the condition instead, which directly
captures when a custom writable target directory is in use and avoids
false assumptions.
This allows us to use a single base name for functions that have
multiple types in the signature, such as `extend_f32_f64`.
The compiler-builtins `trunc` operation wrappers had to be renamed to
`narrow` to avoid conflicting with libm `trunc`.
Create a new struct `Hex` that serves all of these purposes via a new
trait `DisplayHex`. This is easier to work with because we can make
`DisplayHex` a bound of `Float`.
Add wrappers for compiler-builtins that closer match the libm
interfaces, and add basic compiler-builtins float arithmetic to the set
of tested functions.
This means we now get tests against MPFR, better edge case coverage,
extensive testing, and benchmarks for the following functions:
* `__add[hsdt]f3`
* `__sub[hsdt]f3`
* `__mul[hsdt]f3`
* `__div[sdt]f3`
* `__powi[sdt]f2`
Functions from compiler-builtins have not yet been tied in with
`update-api-list.py` and the CI tooling that reads it, that will need to
be updated in a follow up.
- Note that working directory matters
- Note that stdarch-gen-arm uses nightly
- Fix missing directory. Without this, it would print to stdout in one
giant merged file.
Resolve the following lints:
* `unpinned-uses`: Pin action versions using `zizmor --fix`
* `excessive-permissions`: Add `permissions: {}` to all workflows
* `template-injection`: This one wasn't too concerning since `${{ ...
}}` was only used for `matrix` and `needs` access, but it is easy
enough to resolve by storing in an environment variable.
Some optimization passes _improve_ compile times [1]. So we want to run
some passes even with `-Copt-level=0`. That means that some of the lines
in the test can be optimized away. To make regression testing more
robust, we also want to run the test with such passes disabled. The
solution is to use two revisions. One with default `-Copt-level=0`
passes, and one "even less optimized", with enough optimization passes
disabled to keep the maximum number of lines steppable.
[1]: https://github.com/rust-lang/compiler-team/issues/319
Apply two optimizations to `Mask::first_set`:
1) Move the call to `simd_cast` into the `const` block when initializing
`index`. This removes runtime shuffles necessary to translate a
`Simd<usize, N>` to a `Simd<T, N>`.
2) Replace the call to `mask.select` with `simd_or(!self, index)`. This
is cheaper than doing a comparison and on some architectures the `or`
can be combined with the `not` into a single instruction.
See https://godbolt.org/z/YebG6aoMY for an example of the difference in
generated assembly.
- Follow UEFI Shell search flow to search for programs while launching.
- Tested using OVMF on QEMU.
Signed-off-by: Ayush Singh <ayush@beagleboard.org>
- beginners-guide.md: fix missing letter ("within you" → "within your")
- .github/PULL_REQUEST_TEMPLATE.md: remove duplicate word ("tests for test interactions" → "tests for interactions")
Targets that set `requires_lto = true` were not actually using lto when
compiling with cargo by default. They needed an extra `lto = true` in
`Cargo.toml` to work.
Fix this by letting lto take precedence over the `embed_bitcode` flag
when lto is required by a target.
If both these flags would be supplied by the user, an error is
generated. However, this did not happen when lto was requested by the
target instead of the user.
- [Stabilize `if let` guards on match arms](https://github.com/rust-lang/rust/pull/141295)
- [`irrefutable_let_patterns` lint no longer lints on let chains](https://github.com/rust-lang/rust/pull/146832)
- [Support importing path-segment keywords with renaming](https://github.com/rust-lang/rust/pull/146972)
- [Stabilize inline assembly for PowerPC and PowerPC64](https://github.com/rust-lang/rust/pull/147996)
- [const-eval: be more consistent in the behavior of padding during typed copies](https://github.com/rust-lang/rust/pull/148967)
- [Const blocks are no longer evaluated to determine if expressions involving fallible operations can implicitly be constant-promoted.](https://github.com/rust-lang/rust/pull/150557). Expressions whose ability to implicitly be promoted would depend on the result of a const block are no longer implicitly promoted.
- [Make operational semantics of pattern matching independent of crate and module](https://github.com/rust-lang/rust/pull/150681)
<a id="1.95-Compiler"></a>
Compiler
--------
- [Stabilize `--remap-path-scope` for controlling the scoping of how paths get remapped in the resulting binary](https://github.com/rust-lang/rust/pull/147611)
- [Apply patches for CVE-2026-6042 and CVE-2026-40200 to vendored musl](https://github.com/rust-lang/rust/pull/155171)
<a id="1.95-Platform-Support"></a>
Platform Support
----------------
- [Promote `powerpc64-unknown-linux-musl` to Tier 2 with host tools](https://github.com/rust-lang/rust/pull/149962)
- [Promote `aarch64-apple-tvos` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-tvos-sim` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-watchos` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-watchos-sim` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-visionos` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-visionos-sim` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
Refer to Rust's [platform support page][platform-support-doc]
for more information on Rust's tiered platform support.
- [Add new "hide deprecated items" setting in rustdoc](https://github.com/rust-lang/rust/pull/151091)
<a id="1.95-Compatibility-Notes"></a>
Compatibility Notes
-------------------
- [Array coercions may now result in less inference constraints than before](https://github.com/rust-lang/rust/pull/140283)
- Importing `$crate` without renaming, i.e. `use $crate::{self};`, is now no longer permitted due to stricter error checking for `self` imports.
- [const-eval: be more consistent in the behavior of padding during typed copies.](https://github.com/rust-lang/rust/pull/148967)
In very rare cases, this may cause compilation errors due to bytes from parts of a pointer ending up in the padding bytes of a `const` or `static`.
- [A future-incompatibility warning lint `ambiguous_glob_imported_traits` is now reported when using an ambiguously glob imported trait](https://github.com/rust-lang/rust/pull/149058)
- [Check lifetime bounds of types mentioning only type parameters](https://github.com/rust-lang/rust/pull/149389)
- [Report more visibility-related ambiguous import errors](https://github.com/rust-lang/rust/pull/149596)
- [Deprecate `Eq::assert_receiver_is_total_eq` and emit future compatibility warnings on manual impls](https://github.com/rust-lang/rust/pull/149978)
- [powerpc64: Use the ELF ABI version set in target spec instead of guessing](https://github.com/rust-lang/rust/pull/150468) (fixes the ELF ABI used by the OpenBSD target)
- Matching on a `#[non_exhaustive]` enum [now reads the discriminant, even if the enum has only one variant](https://github.com/rust-lang/rust/pull/150681). This can cause closures to capture values that they previously wouldn't.
-`mut ref` and `mut ref mut` patterns, part of the unstable [Match Ergonomics 2024 RFC](https://github.com/rust-lang/rust/issues/123076), were accidentally allowed on stable within struct pattern field shorthand. These patterns are now correctly feature-gated as unstable in this position.
- [Add future-compatibility warning for derive helper attributes which conflict with built-in attributes](https://github.com/rust-lang/rust/pull/151152)
- [JSON target specs](https://doc.rust-lang.org/rustc/targets/custom.html) have been destabilized and now require `-Z unstable-options` to use. Previously, they could not be used without the standard library, which has no stable build mechanism. In preparation for the `build-std` project adding that support, JSON target specs are being proactively gated to ensure they remain unstable even if `build-std` is stabilized. Cargo now includes the `-Z json-target-spec` CLI flag to automatically pass `-Z unstable-options` to the compiler when needed. See [#150151](https://github.com/rust-lang/rust/pull/150151), [#151534](https://github.com/rust-lang/rust/pull/150151), and [rust-lang/cargo#16557](https://github.com/rust-lang/cargo/pull/16557).
- [The arguments of `#[feature]` attributes on invalid targets are now checked](https://github.com/rust-lang/rust/issues/153764)
<a id="1.95-Internal-Changes"></a>
Internal Changes
----------------
These changes do not affect any public interfaces of Rust, but they represent
significant improvements to the performance or internals of rustc and related
tools.
- [Update to LLVM 22](https://github.com/rust-lang/rust/pull/150722)
#[note("this attribute does not have an `!`, which means it is applied to this {$target}")]
pubtarget_span: Option<Span>,
pubtarget: &'staticstr,
}
#[derive(Diagnostic)]
#[diag("doc alias is duplicated")]
pub(crate)structDocAliasDuplicated{
#[label("first defined here")]
pubfirst_definition: Span,
}
#[derive(Diagnostic)]
#[diag("only `hide` or `show` are allowed in `#[doc(auto_cfg(...))]`")]
pub(crate)structDocAutoCfgExpectsHideOrShow;
#[derive(Diagnostic)]
#[diag("there exists a built-in attribute with the same name")]
pub(crate)structAmbiguousDeriveHelpers;
#[derive(Diagnostic)]
#[diag("`#![doc(auto_cfg({$attr_name}(...)))]` only accepts identifiers or key/value items")]
pub(crate)structDocAutoCfgHideShowUnexpectedItem{
pubattr_name: Symbol,
}
#[derive(Diagnostic)]
#[diag("`#![doc(auto_cfg({$attr_name}(...)))]` expects a list of items")]
pub(crate)structDocAutoCfgHideShowExpectsList{
pubattr_name: Symbol,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `include`")]
pub(crate)structDocUnknownInclude{
pubinner: &'staticstr,
pubvalue: Symbol,
#[suggestion(
"use `doc = include_str!` instead",
code="#{inner}[doc = include_str!(\"{value}\")]"
)]
pubsugg: (Span,Applicability),
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `spotlight`")]
#[note("`doc(spotlight)` was renamed to `doc(notable_trait)`")]
#[note("`doc(spotlight)` is now a no-op")]
pub(crate)structDocUnknownSpotlight{
#[suggestion(
"use `notable_trait` instead",
style="short",
applicability="machine-applicable",
code="notable_trait"
)]
pubsugg_span: Span,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `{$name}`")]
#[note(
"`doc` attribute `{$name}` no longer functions; see issue #44136 <https://github.com/rust-lang/rust/issues/44136>"
)]
#[note("`doc({$name})` is now a no-op")]
pub(crate)structDocUnknownPasses{
pubname: Symbol,
#[label("no longer functions")]
pubnote_span: Span,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `plugins`")]
#[note(
"`doc` attribute `plugins` no longer functions; see issue #44136 <https://github.com/rust-lang/rust/issues/44136> and CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>"
)]
#[note("`doc(plugins)` is now a no-op")]
pub(crate)structDocUnknownPlugins{
#[label("no longer functions")]
publabel_span: Span,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `{$name}`")]
pub(crate)structDocUnknownAny{
pubname: Symbol,
}
#[derive(Diagnostic)]
#[diag("expected boolean for `#[doc(auto_cfg = ...)]`")]
pub(crate)structDocAutoCfgWrongLiteral;
#[derive(Diagnostic)]
#[diag("`#[doc(test(...)]` takes a list of attributes")]
span_mirbug!(self,term,"call to {:?} with wrong # of args",sig);
}
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.