resolve: Explicit Set for detecting resolution cycles
Instead of using the `borrow_mut` counter of a `RefCell` for a `NameResolution` for detecting cyclic imports during import resolution, we use an explicit recursion stack that keeps track of the current used `NameResolution`s.
Because of the upcoming parallelisation of the import resolution algorithm, the current way cannot used in a parallel context.
r? @petrochenkov
Move `std::io::Error` into `core`
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/155574
Related: https://github.com/rust-lang/rust/pull/152918
## Description
Moves `std::io::Error` into `core`, deferring `Box`-adjacent methods to incoherent implementations in `alloc`, and `RawOsError` methods to `std`. This requires some substantial changes to the internals of `Error`, but none of them are breaking changes or externally visible.
Notably, I've replaced usage of `Box` with a wrapper around a pointer and an appropriate drop function. This requires the addition of quite a few lines of unsafe, but is required to work around `Box` only being accessible from `alloc`. Additionally, an atomic pointer to a VTable is used for working with `RawOsError` in `core`, since we cannot know the required implementations without `std`.
As mention in [this comment](https://github.com/rust-lang/rust/pull/155625#issuecomment-4744932682), there may be concern around having a static `AtomicPtr` in `core` for certain users. I've added a configuration option `no_io_statics` which (similar to `no_sync`/etc. in `alloc`) can be used to prevent their inclusion in `core`. When active, the fallback default implementation will always be used.
---
## Notes
* This PR adopts the VTable technique from rust-lang/rust#152918
* This PR builds on my previous PR rust-lang/rust#155574
* No AI tooling of any kind was used during the creation of this PR.
Change `Location<'_>` lifetime to `'static` in `Panic[Hook]Info`
I'm writing a library that would benefit from being able to store a `&'static str` instead of a `String` for the file location of a panic. Currently, the API of [`std::panic::PanicHookInfo::location`](https://doc.rust-lang.org/nightly/std/panic/struct.PanicHookInfo.html#method.location) and [`core::panic::PanicInfo::location`](https://doc.rust-lang.org/nightly/core/panic/struct.PanicInfo.html#method.location) return a `Location<'_>` (and by extension, a file name `&str`) whose lifetime is tied to the borrow of the `Panic[Hook]Info`.
It is my understanding that the `Location`/`&str` will always be `Location<'static>`/`&'static str`, since the file name is embedded directly into the compiled binary (and I don't see a likely reason/way for that to ever change in the future). Since it seems unlikely to ever need to change, and since making the guarantee that the returned lifetime is `'static` has a real benefit (allows users to avoid unnecessary allocations), I think changing to the returned `Location<'_>`'s lifetime to `'static` would be a worthwhile change.
see also the recent [#1320870](https://github.com/rust-lang/rust/pull/132087), which made a similar change to [`std::panic::Location`](https://doc.rust-lang.org/nightly/std/panic/struct.Location.html)
Rollup of 4 pull requests
Successful merges:
- rust-lang/rust#158486 (std: treat ENFILE as transient in the pidfd support probe)
- rust-lang/rust#158454 (regression test for `Trait<A><B>` in "consider further restricting this bound" suggestion)
- rust-lang/rust#158518 (Fix mixed use of "a" / "an" article in E0277)
- rust-lang/rust#158519 (add crashtests [2/N])
Fix mixed use of "a" / "an" article in E0277
This PR fixes a tiny little annoyance typo in error E0277. Currently, this code fails to compile (correctly) with the following error:
```rs
struct A<F: Fn()>(F);
impl<F> A<F> {}
fn main() {}
```
```rs
error[E0277]: expected a `Fn()` closure, found `F`
--> src/main.rs:3:9
|
3 | impl<F> A<F> {}
| ^^^^ expected an `Fn()` closure, found `F`
|
= note: wrap the `F` in a closure with no arguments: `|| { /* code */ }`
... truncated
```
Unfortunately, the first line of the error message uses the article "a", when it should be "an" for the `Fn` trait and friends. The help label does use the correct article, "an".
Unless if I have been pronouncing `Fn` incorrectly...
regression test for `Trait<A><B>` in "consider further restricting this bound" suggestion
when a bound already has generic args (e.g. `impl Pair<Left = A>`) the "consider further restricting this bound" suggestion would generate invalid syntax by appending a new `<Right = B>` producing `Pair<Left = A><Right = B>`.
the fix detects when the insertion point immediately follows a `>` and merges into the existing arg list instead producing the valid `Pair<Left = A, Right = B>`.
fixes https://github.com/rust-lang/rust/issues/142803
std: treat ENFILE as transient in the pidfd support probe
The pidfd support probe special-cases `EMFILE` from `pidfd_open`: it returns the
error without caching anything, so the next spawn re-probes. `ENFILE` falls
through instead, into the fallback arm, so the probe caches pidfd as unsupported
for the rest of the process, even after descriptors free up.
Both errnos come from the same `pidfd_open` call and mean the same thing: the
process is out of file descriptors, just per-process (`EMFILE`) vs system-wide
(`ENFILE`). I don't see a reason to treat them differently here, so this handles
`ENFILE` the same way:
```rust
Err(e) if matches!(e.raw_os_error(), Some(libc::EMFILE | libc::ENFILE)) => {
```
I kept the raw `raw_os_error()` check rather than `ErrorKind::TooManyOpenFiles`
(rust-lang/rust#158326, which maps both) to match the rest of this probe, but can switch if
you'd prefer.
I didn't add a test, since triggering it needs real fd exhaustion during the
probe, which isn't practical to reproduce. The `EMFILE` arm isn't tested either.
r? libs
Merge and reframe strict_provenance_lints
There does not seem to be any good reason to have separate lints for ptr2int and int2ptr casts. The main reason to enable this lint is to help with replacing `as` casts with strict provenance APIs (if possible) or explicit provenance APIs (when needed). That applies equally to both directions.
Merging the lints requires coming up with new name and lint explanation. This is a good chance to reconsider the purpose and messaging of the lints which have been essentially unchanged since the early days of the "strict provenance experiment". For reasons described below, I called the merged lint `implicit_provenance_casts`, rewrote its explanation from scratch, and made some changes to diagnostics.
First, the lint is not (only) about strict provenance any more. While strict provenance is often the best fix, migrating `as` casts to exposed provenance APIs also silences the lint. The exposed provenance APIs aren't any better for Miri and CHERI, but at least provenance considerations are made *explicit*, not picked up as side effect of the `as` keyword. (Banning use of exposed provenance APIs can be done with clippy's existing `disallowed_methods` lint.)
Second, provenance is now officially part of the language and prominently explained in the `std::ptr` documentation. The new lint refers to those docs and is more consistent with them.
Third, while strict provenance is encouraged whenever possible, exposed provenance is also part of the language and here to stay. Indeed, if we eventually enable the lint by default and make it `cargo fix`-able to keep the ecosystem migration manageable, we may want to suggest exposed provenance APIs to err on the side of not introducing UB. Thus, I made the diagnostics more neutral and descriptive. I've kept the suggestions that introduce strict provenance APIs, but we may want to reconsider this later.
Tracking issue: rust-lang/rust#130351
std: fix xous dns ipv6 parsing off-by-one
the ipv6 arm read the 16-byte address from offset+1 instead of offset, unlike the ipv4 arm. this mis-parsed every ipv6 result and let the slice reach offset+17 while the bounds check only guards offset+16, so a malformed dns response could index past the 4096-byte buffer and panic.
Upgrade `jsonsocck` and `jsondoclint` to edition 2024.
No code changes were necessary to perform the upgrade. I used `cargo fix --edition`, and additionally had an AI tool review the source code against the [Rust 2024 edition guide](https://github.com/rust-lang/edition-guide/tree/master/src/rust-2024) and the [edition upgrade guide](https://doc.rust-lang.org/edition-guide/editions/transitioning-an-existing-project-to-a-new-edition.html) to ensure the change works properly.
r? @GuillaumeGomez
**AI disclosure:** This PR is the product of a combination of manual work and AI tools. I secured approval in advance from the designated reviewer. I stand behind the quality of the code I'm submitting, and I vouch it's as good or better compared to if I had written every line by my own hand.
Fix inconsistent safety requirement in VecDeque::nonoverlapping_ranges
The safety documentation of `nonoverlapping_ranges` says that its `head` argument must be in bounds:
```rust
/// Get source, destination and count (like the arguments to [`ptr::copy_nonoverlapping`])
/// for copying `count` values from index `src` to index `dst`.
/// One of the ranges can wrap around the physical buffer, for this reason 2 triples are returned.
///
/// Use of the word "ranges" specifically refers to `src..src + count` and `dst..dst + count`.
///
/// # Safety
///
/// - Ranges must not overlap: `src.abs_diff(dst) >= count`.
/// - Ranges must be in bounds of the logical buffer: `src + count <= self.capacity()` and `dst + count <= self.capacity()`.
/// - `head` must be in bounds: `head < self.capacity()`.
#[cfg(not(no_global_oom_handling))]
unsafe fn nonoverlapping_ranges(
&mut self,
src: usize,
dst: usize,
count: usize,
head: usize,
) -> [(*const T, *mut T, usize); 2] {
```
However, this is slightly stricter than the `VecDeque` internal invariant for `head`. The struct-level invariant allows `head == 0` when the buffer capacity is zero:
```rust
pub struct VecDeque<
T,
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
> {
// `self[0]`, if it exists, is `buf[head]`.
// `head < buf.capacity()`, unless `buf.capacity() == 0` when `head == 0`.
head: WrappedIndex,
// the number of initialized elements, starting from the one at `head` and potentially wrapping around.
// if `len == 0`, the exact value of `head` is unimportant.
// if `T` is zero-Sized, then `self.len <= usize::MAX`, otherwise `self.len <= isize::MAX as usize`.
len: usize,
buf: RawVec<T, A>,
}
```
This zero-capacity case is reachable through the public API. I create the corresponding case in [Rustplayground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=c1632f2a9170264c3ae50f6c229027db). This case can run without UB, also Miri runs successfully.
So it seems that the safety documentation of `VecDeque::nonoverlapping_ranges` is incorrect, or this API should add additional processing to approach this condition. This PR provides the minimal fix: updates the safety documentation for `nonoverlapping_ranges` to match the existing VecDeque invariant.
If needed, I can add a debug_assert! to check whether the input satisfies the requirement.
No behavior is changed.
Allow the unstable attribute on foreign type
While working the `FnPtr` trait in rust-lang/rust#156176 @carbotaniuman was trying to implement `Code` as an extern type but got an error as the current stability infrastructure does not allow `unstable` attribute on foreign type. rust-lang/rust#158200
This PR fixes that by allowing the `unstable` attribute on ForeignTy and adds test to verify.
@rustbot r? @JonathanBrouwer
Expand `OptionFlatten`'s iterator methods
If someone considers moving from `option.into_iter().flatten()` to
`option.into_flat_iter()`, it may be important for performance that this
iterator "specializes" methods the same way `Flatten` does, especially
forwarding to underlying `fold`, etc.
rustdoc: show impl Trait<Box<Local>> for Foreign, etc on Local's docs
This is a generalization of rust-lang/rust#92940: that PR handled cases like `impl Foreign for Box<Local>`, but was missing handling for a few other closely related cases.
My particular interest was with showing `impl From<Box<Utf8Path>> for Box<Path>` in camino's documentation. But I ended up handling a bunch of related cases along the way.
I'm new to rustdoc so please let me know if I got anything wrong :) took a bit to fully understand how this worked.
<img width="1733" height="483" alt="image" src="https://github.com/user-attachments/assets/4b987c61-bdac-4de3-a491-c0577e06fa7c" />
Adds RmetaLinkCache a per-link cache that uses path as the key of dec…
Adds `RmetaLinkCache` a per link and path keyed cache of decoded `lib.rmeta-link` archive members and routes the add_archive read through it so that each rlib link metadata is decoded only one per link at most.
This is a request that originated from the discussion in rust-lang/rust#156735 and we split it out as its own PR. It gives that PR a decode once path to read instead of reparsing each `rlib` per crate, and this will be in effect once `native_lib_filenames` moves to a link-time read.
Part of rust-lang/rust#138243
Add supertrait item shadowing for type-level path resolution
This makes type-level name resolution (used primarily for associated types) also prefer subtrait items to supertrait items in case of ambiguity.
This addresses the concern from rust-lang/rust#148605 about the inconsistency with name resolution in expressions and method calls.
Revert "LLVM 23: Adapt codegen test to moved assume"
This reverts https://github.com/rust-lang/rust/pull/158067.
Fixes https://github.com/rust-lang/rust/issues/158500
The fix that was applied here is not robust against layout randomization, specifically the IR to load through the slice head pointer needs to come after a gepi, and not just a `load ptr, ptr %x`.
Based on the PR discussion, I think it's possible that the `min-llvm-version: 22` was mistakenly added when CI happened to choose the bad layout during the initial merge.
I'm not yet sure what the right fix is, but this is causing about half of all merges to fail right now so a revert seems prudent.
I don't think we have a way to skip tests when randomize-layout is set. The problem here is that we run codegen tests against the globally-configured sysroot, so setting `-Zrandomize-layout` in the test doesn't do anything.
the 256-bit implementation actually takes a 6-bit IMM and uses the low 3 bits for the first 128-bit chunk, the next 3 bits for the second 128-bit chunk. Previously we only used the low 3 bits for both chunks.