Remove cfg(test) from library/core
The diff here is very small with the ignore whitespace option.
`core` doesn't/can't have unit tests. All of its tests are just modules under `tests/`, so it has no use for `cfg(test)`, because the entire contents of `library/core/src` are only ever compiled with that cfg off, and the entire contents of `library/core/tests` are only ever compiled with that cfg on.
You can tell this is what's happening because we had `#[cfg(test)]` on a module declaration that has no source file.
I also deleted the extra `mod tests {` layer of nesting; there's no need to mention again in the module path that this is a module of tests. This exposes a name collision between the `u128` module of tests and `core::u128`. Fixed that by using `<u128>::MAX` like is done in the `check!` macro, which is what avoids this name ambiguity for the other types.
link to Future::poll from the Poll docs
The most important thing about Poll is that Future::poll returns it, but previously the docs didn't emphasize this.
Add implementations for `unbounded_shl`/`unbounded_shr`
Tracking Issue: https://github.com/rust-lang/rust/issues/129375
This implements `unbounded_shl` and `unbounded_shr` under the feature gate `unbounded_shifts`
Rollup of 9 pull requests
Successful merges:
- #129288 (Use subtyping for `UnsafeFnPointer` coercion, too)
- #129405 (Fixing span manipulation and indentation of the suggestion introduced by #126187)
- #129518 (gitignore: ignore ICE reports regardless of directory)
- #129519 (Remove redundant flags from `lower_ty_common` that can be inferred from the HIR)
- #129525 (rustdoc: clean up tuple <-> primitive conversion docs)
- #129526 (Use `FxHasher` on new solver unconditionally)
- #129544 (Removes dead code from the compiler)
- #129553 (add back test for stable-const-can-only-call-stable-const)
- #129590 (Avoid taking reference of &TyKind)
r? `@ghost`
`@rustbot` modify labels: rollup
rustdoc: clean up tuple <-> primitive conversion docs
This adds a minor missing feature to `fake_variadic`, so that it can render `impl From<(T,)> for [T; 1]` correctly.
library: Move unstable API of new_uninit to new features
- `new_zeroed` variants move to `new_zeroed_alloc`
- the `write` fn moves to `box_uninit_write`
The remainder will be stabilized in upcoming patches, as it was decided to only stabilize `uninit*` and `assume_init`.
Build `library/profiler_builtins` from `ci-llvm` if appropriate
Running all of `tests/coverage` requires the LLVM profiler runtime, which requires setting `build.profiler = true`.
Historically, doing that has required checking out the entire `src/llvm-project` submodule. For compiler contributors who otherwise don't need that submodule (thanks to `download-ci-vm`), that's quite inconvenient.
However, thanks to #129116, the downloaded CI LLVM tarball now contains a copy of LLVM's `compiler-rt` directory, which includes all the files needed to build the profiler runtime. So with a little bit of extra logic in bootstrap, we can have `library/profiler_builtins` look for the `compiler-rt` files in `ci-llvm` instead of the `src/llvm-project` submodule.
Put Pin::as_deref_mut in impl Pin<Ptr> / rearrange Pin methods
Tracking issue: #86918
Based on the suggestion in https://github.com/rust-lang/rust/issues/86918#issuecomment-2189367582
> Some advantages:
>
> * Synergy with the existing `as_ref` and `as_mut` signatures (stable since Rust 1.33)
>
> * Lifetime elision reduces noise in the signature
>
> * Turbofish less verbose: `Pin::<&mut T>::as_deref_mut` vs `Pin::<&mut Pin<&mut T>>::as_deref_mut`
The comment seemed to imply that `Pin::as_ref` and `Pin::as_mut` already share an impl block, which they don't. So, I rearranged it so that they do, and we can see which looks better in the docs.
<details><summary><b>Docs screenshots</b></summary>
Current nightly:
![image](https://github.com/user-attachments/assets/b432cb82-8f4b-48ae-bafc-2fe49d0ad48c)
`Pin::as_deref_mut` moved into the same block as `as_mut`:
![image](https://github.com/user-attachments/assets/f9b35722-6a88-4465-ad1c-28d8e91902ac)
`Pin::as_ref`, `as_mut`, and `as_deref_mut` all in the same block:
![image](https://github.com/user-attachments/assets/9a1b2bf0-70a6-4751-b13f-390f1d575244)
</details>
I think I like the last one the most; obviously I'm biased since I'm the one who rearranged it, but it doesn't make sense to me to have `as_ref` methods split up by an `into_inner` method.
r? dtolnay
Add a special case for `CStr`/`CString` in the `improper_ctypes` lint
Revives #120176. Just needed to bless a test and fix an argument, but seemed reasonable to me otherwise.
Instead of saying to "consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct", we now tell users to "Use `*const ffi::c_char` instead, and pass the value from `CStr::as_ptr()`" when the type involved is a `CStr` or a `CString`.
The suggestion is not made for `&mut CString` or `*mut CString`.
r? ``````@cjgillot`````` (since you were the reviewer of the original PR #120176, but feel free to reroll)
remove invalid `TyCompat` relation for effects
if the current impl uses `Maybe` (`impl const`), the parent impl must use `Maybe` (`impl const`) as well.
I'd like to rename `TyCompat` to `Sub` which is probably clearer. But it would conflict with my other PR.
r? ``@rust-lang/project-const-traits``
- `new_zeroed` variants move to `new_zeroed_alloc`
- the `write` fn moves to `box_uninit_write`
The remainder will be stabilized in upcoming patches, as
it was decided to only stabilize `uninit*` and `assume_init`.
Documents that `BikeshedIntrinsicFrom` models transmute-via-union,
which is slightly more expressive than the transmute-via-cast
implemented by `transmute_copy`. Additionally, we provide an
implementation of transmute-via-union as a method on the
`BikeshedIntrinsicFrom` trait with additional documentation on
the boundary between trait invariants and caller obligations.
Whether or not transmute-via-union is the right kind of transmute
to model remains up for discussion [1]. Regardless, it seems wise
to document the present behavior.
[1] https://rust-lang.zulipchat.com/#narrow/stream/216762-project-safe-transmute/topic/What.20'kind'.20of.20transmute.20to.20model.3F/near/426331967
Rollup of 9 pull requests
Successful merges:
- #128511 (Document WebAssembly target feature expectations)
- #129243 (do not build `cargo-miri` by default on stable channel)
- #129263 (Add a missing compatibility note in the 1.80.0 release notes)
- #129276 (Stabilize feature `char_indices_offset`)
- #129350 (adapt integer comparison tests for LLVM 20 IR changes)
- #129408 (Fix handling of macro arguments within the `dropping_copy_types` lint)
- #129426 (rustdoc-search: use tighter json for names and parents)
- #129437 (Fix typo in a help diagnostic)
- #129457 (kobzol vacation)
r? `@ghost`
`@rustbot` modify labels: rollup
Stabilize feature `char_indices_offset`
Stabilized API:
```rust
impl CharIndices<'_> {
pub fn offset(&self) -> usize;
}
```
Tracking issue: https://github.com/rust-lang/rust/issues/83871
Closes https://github.com/rust-lang/rust/issues/83871
I also attempted to improved the documentation to make it more clear that it returns the offset of the character that will be returned by the next call to `next()`.
Update `compiler_builtins` to `0.1.120`
Includes https://github.com/rust-lang/compiler-builtins/pull/672 which fixes regression issue with Apple and Windows compilers.
try-job: aarch64-apple
try-job: x86_64-apple-1
try-job: x86_64-msvc
The current `build.rs` will automatically skip source files that don't exist.
An unfortunate side-effect is that if _no_ files could be found (e.g. because
the directory was wrong), the build fails with a mysterious linker error.
We can reduce the awkwardness of this by explicitly checking that at least one
source file was found.
Rollup of 8 pull requests
Successful merges:
- #128432 (WASI: forbid `unsafe_op_in_unsafe_fn` for `std::{os, sys}`)
- #129373 (Add missing module flags for CFI and KCFI sanitizers)
- #129374 (Use `assert_unsafe_precondition!` in `AsciiChar::digit_unchecked`)
- #129376 (Change `assert_unsafe_precondition` docs to refer to `check_language_ub`)
- #129382 (Add `const_cell_into_inner` to `OnceCell`)
- #129387 (Advise against removing the remaining Python scripts from `tests/run-make`)
- #129388 (Do not rely on names to find lifetimes.)
- #129395 (Pretty-print own args of existential projections (dyn-Trait w/ GAT constraints))
r? `@ghost`
`@rustbot` modify labels: rollup
Add `const_cell_into_inner` to `OnceCell`
`Cell` and `RefCell` have their `into_inner` methods const unstable. `OnceCell` has the same logic, so add it under the same gate.
Tracking issue: https://github.com/rust-lang/rust/issues/78729
`Cell` and `RefCell` have their `into_inner` methods const unstable.
`OnceCell` has the same logic, so add it under the same gate.
Tracking issue: https://github.com/rust-lang/rust/issues/78729
Fix `thread::sleep` Duration-handling for ESP-IDF
Addresses the ESP-IDF specific aspect of https://github.com/rust-lang/rust/issues/129212
#### A short summary of the problems addressed by this PR:
================================================
1. **Problem 1** - the current implementation of `std:🧵:sleep` does not properly round up the passed `Duration`
As per the documentation of `std:🧵:sleep`, the implementation should sleep _at least_ for the provided duration, but not less. Since the minimum supported resolution of the `usleep` syscall which is used with ESP-IDF is one microsecond, this means that we need to round-up any sub-microsecond nanos to one microsecond. Moreover, in the edge case where the user had passed a duration of < 1000 nanos (i.e. less than one microsecond), the current implementation will _not_ sleep _at all_.
This is addressed by this PR.
2. **Problem 2** - the implementation of `usleep` on the ESP-IDF can overflow if the passed number of microseconds is >= `u32::MAX - 1_000_000`
This is also addressed by this PR.
Extra details for Problem 2:
`u32::MAX - 1_000_000` is chosen to accommodate for the longest possible systick on the ESP IDF which is 1000ms.
The systick duration is selected when compiling the ESP IDF FreeRTOS task scheduler itself, so we can't know it from within `STD`. The default systick duration is 10ms, and might be lowered down to 1ms. (Making it longer I have never seen, but in theory it can go up to a 1000ms max, even if obviously a one second systick is unrealistic - but we are paranoid in the PR.)
While the overflow is reported upstream in the ESP IDF repo[^1], I still believe we should workaround it in the Rust wrappers as well, because it might take time until it is fixed, and they might not fix it for all released ESP IDF versions.
For big durations, rather than calling `usleep` repeatedly on the ESP-IDF in chunks of `u32::MAX - 1_000_000`us, it might make sense to call instead with 1_000_000us (one second) as this is the max period that seems to be agreed upon as a safe max period in the `usleep` POSIX spec. On the other hand, that might introduce less precision (as we need to call more times `usleep` in a loop) and, we would be fighting a theoretical problem only, as I have big doubts the ESP IDF will stop supporting durations higher than 1_000_000us - ever - because of backwards compatibility with code which already calls `usleep` on the ESP IDF with bigger durations.
[^1]: https://github.com/espressif/esp-idf/issues/14390
Implement `debug_more_non_exhaustive`
This implements the ACP at https://github.com/rust-lang/libs-team/issues/248, adding `.finish_non_exhaustive()` for `DebugTuple`, `DebugSet`, `DebugList`, and `DebugMap`.
Also used this as an opportunity to make some documentation and tests more readable by using raw strings instead of escaped quotes.
Tracking issue: https://github.com/rust-lang/rust/issues/127942
Avoid extra `cast()`s after `CStr::as_ptr()`
These used to be `&str` literals that did need a pointer cast, but that
became a no-op after switching to `c""` literals in #118566.
Add a precondition check for Layout::from_size_align_unchecked
Ran into this while looking into https://github.com/rust-lang/miri/issues/3679. This is of course not the cause of the ICE, but the reproducer doesn't encounter a precondition check and it ought to.
doc: std::env::var: Returns None for names with '=' or NUL byte
The documentation incorrectly stated that std::env::var could return an error for variable names containing '=' or the NUL byte. Copy the correct documentation from var_os.
var_os was fixed in Commit 8a7a665, Pull Request #109894, which closed Issue #109893.
This documentation was incorrectly added in commit f2c0f292, which replaced a panic in var_os by returning None, but documented the change as "May error if ...".
Reference the specific error values and link to them.
CloneToUninit impls
As per #126799.
Also implements it for `Wtf8` and both versions of `os_str::Slice`.
Maybe it is worth to slap `#[inline]` on some of those impls.
r? `@dtolnay`
float to/from bits and classify: update for float semantics RFC
With https://github.com/rust-lang/rfcs/pull/3514 having been accepted, it is clear that hardware which e.g. flushes subnormal to zero is just non-conformant from a Rust perspective -- this is a hardware bug, or maybe an LLVM backend bug (where LLVM doesn't lower floating-point ops in a way that they have the standardized behavior). So update the comments here to make it clear that we don't have to do any of this, we're just being nice.
Also remove the subnormal/NaN checks from the (unstable) const-version of to/from-bits; they are not needed since we decided with the aforementioned RFC that it is okay to get a different result at const-time and at run-time.
r? `@workingjubilee` since I think you wrote many of the comments I am editing here.
Implement DoubleEnded and ExactSize for Take<Repeat> and Take<RepeatWith>
Repeat iterator always returns the same element and behaves the same way
backwards and forwards. Take iterator can trivially implement backwards
iteration over Repeat inner iterator by simply doing forwards iteration.
DoubleEndedIterator is not currently implemented for Take<Repeat<T>>
because Repeat doesn’t implement ExactSizeIterator which is a required
bound on DEI implementation for Take.
Similarly, since Repeat is an infinite iterator which never stops, Take
can trivially know how many elements it’s going to return. This allows
implementing ExactSizeIterator on Take<Repeat<T>>.
While at it, observe that ExactSizeIterator can also be implemented for
Take<RepeatWhile<F>> so add that implementation too. Since in contrast
to Repeat, RepeatWhile doesn’t guarante to always return the same value,
DoubleEndedIterator isn’t implemented.
Those changes render core::iter::repeat_n somewhat redundant.
Issue: https://github.com/rust-lang/rust/issues/104434
Issue: https://github.com/rust-lang/rust/issues/104729
- [ ] ACP: https://github.com/rust-lang/libs-team/issues/120 (this is actually ACP for repeat_n but this is nearly the same functionality so hijacking it so both approaches can be discussed in one place)
Improve docs for Waker::noop and LocalWaker::noop
* Add a warning about a likely misuse. (See my commit message for longer rationale.)
* Apply some probably-accidentally-omitted changes to `LocalWaker`'s docs
* Add a comment about the clone-and-hack of the docs
I have used [semantic linefeeds](https://rhodesmill.org/brandon/2012/one-sentence-per-line/) for the docs formatting.
Hash Ipv*Addr as an integer
The `Ipv4Addr` and `Ipv6Addr` structs always have a fixed size, but directly derive `Hash`. This causes them to call the bytestring hasher implementation, which adds extra work for most hashers. This PR converts the internal representation to a fixed-width integer before passing to the hasher to prevent this.
derive(SmartPointer): register helper attributes
Fix#128888
This PR enables built-in macros to register helper attributes, if any, to support correct name resolution in the correct lexical scope under the macros.
Also, `#[pointee]` is moved into the scope under `derive(SmartPointer)`.
cc `@Darksonn` `@davidtwco`
CommandExt::before_exec: deprecate safety in edition 2024
Similar to `set_var`, we had to find out after 1.0 was released that `before_exec` should have been unsafe. We partially rectified this by deprecating that function a long time ago, but since https://github.com/rust-lang/rust/pull/124636 we have the ability to also deprecate the safety of the old function and make it a *hard error* to call the old function outside `unsafe` in the next edition. So just in case anyone still uses the old function, let's ensure this can't be ignored when moving code to the new edition.
Cc `@rust-lang/libs-api`
Tracking:
- https://github.com/rust-lang/rust/issues/124866
Explicitly specify type parameter on FromResidual for Option and ControlFlow.
~~Remove type parameter default `R = <Self as Try>::Residual` from `FromResidual`~~ _Specify default type parameter on `FromResidual` impls in the stdlib_ to work around https://github.com/rust-lang/rust/issues/99940 / https://github.com/rust-lang/rust/issues/87350 ~~as mentioned in https://github.com/rust-lang/rust/issues/84277#issuecomment-1773259264~~.
This does not completely fix the issue, but works around it for `Option` and `ControlFlow` specifically (`Result` does not have the issue since it already did not use the default parameter of `FromResidual`).
~~(Does this need an ACP or similar?)~~ ~~This probably needs at least an FCP since it changes the API described in [the RFC](https://github.com/rust-lang/rfcs/pull/3058). Not sure if T-lang, T-libs-api, T-libs, or some combination (The tracking issue is tagged T-lang, T-libs-api).~~ This probably doesn't need T-lang input, since it is not changing the API of `FromResidual` from the RFC? Maybe needs T-libs-api FCP?
Rollup of 7 pull requests
Successful merges:
- #122884 (Optimize integer `pow` by removing the exit branch)
- #127857 (Allow to customize `// TODO:` comment for deprecated safe autofix)
- #129034 (Add `#[must_use]` attribute to `Coroutine` trait)
- #129049 (compiletest: Don't panic on unknown JSON-like output lines)
- #129050 (Emit a warning instead of an error if `--generate-link-to-definition` is used with other output formats than HTML)
- #129056 (Fix one usage of target triple in bootstrap)
- #129058 (Add mw back to review rotation)
r? `@ghost`
`@rustbot` modify labels: rollup
Add windows-targets crate to std's sysroot
With this PR, when backtrace is used as a crate from crates.io it will (once updated) use the real [windows-targets](https://crates.io/crates/windows-targets) crate. But when used from std it'll use std's replacement version.
This allows sharing our customized `windows_tagets::link!` macro between std proper and the backtrace crate when used as part of std, ensuring a consistent linking story. This will be especially important once we move to using [`raw-dylib`](https://doc.rust-lang.org/reference/items/external-blocks.html#dylib-versus-raw-dylib) by default.
Add `#[must_use]` attribute to `Coroutine` trait
[Coroutines tracking issue](https://github.com/rust-lang/rust/issues/43122)
Like closures (`FnOnce`, `AsyncFn`, etc.), coroutines are lazy and do nothing unless called (resumed). Closure traits like `FnOnce` have `#[must_use = "closures are lazy and do nothing unless called"]` to catch likely bugs for users of APIs that produce them. This PR adds such a `#[must_use]` attribute to `trait Coroutine`.
Allow to customize `// TODO:` comment for deprecated safe autofix
Relevant for the deprecation of `CommandExt::before_exit` in #125970.
Tracking:
- #124866
Optimize integer `pow` by removing the exit branch
The branch at the end of the `pow` implementations is redundant with multiplication code already present in the loop. By rotating the exit check, this branch can be largely removed, improving code size and reducing instruction cache misses.
Testing on my machine (`x86_64`, 11th Gen Intel Core i5-1135G7 @ 2.40GHz), the `num::int_pow` benchmarks improve by some 40% for the unchecked operations and show some slight improvement for the checked operations as well.
Remove unused lifetime parameter from spawn_unchecked
Amanieu caught this when reviewing the stabilization proposal in https://github.com/rust-lang/rust/issues/55132.
The `'a` lifetime here is useless. The signature is asking the caller of `spawn_unchecked` to "give me any lifetime that is shorter than your F's and T's lifetime", which they can always to with no effect, because arbitrarily short lifetimes exist.
std: refactor UNIX random data generation
This PR makes a number of changes to the UNIX randomness implementation:
* Use `io::Error` for centralized error handling
* Move the file-fallback logic out of the `getrandom`-specific module
* Stop redefining the syscalls on macOS and DragonFly, they have appeared in `libc`
* Add a `OnceLock` to cache the random device file descriptor
miri: make vtable addresses not globally unique
Miri currently gives vtables a unique global address. That's not actually matching reality though. So this PR enables Miri to generate different addresses for the same type-trait pair.
To avoid generating an unbounded number of `AllocId` (and consuming unbounded amounts of memory), we use the "salt" technique that we also already use for giving constants non-unique addresses: the cache is keyed on a "salt" value n top of the actually relevant key, and Miri picks a random salt (currently in the range `0..16`) each time it needs to choose an `AllocId` for one of these globals -- that means we'll get up to 16 different addresses for each vtable. The salt scheme is integrated into the global allocation deduplication logic in `tcx`, and also used for functions and string literals. (So this also fixes the problem that casting the same function to a fn ptr over and over will consume unbounded memory.)
r? `@saethlin`
Fixes https://github.com/rust-lang/miri/issues/3737
std: do not overwrite style in `get_backtrace_style`
If another thread calls `set_backtrace_style` while a `get_backtrace_style` is reading the environment variables, `get_backtrace_style` will overwrite the value. Use an atomic CAS to avoid this.
nontemporal_store: make sure that the intrinsic is truly just a hint
The `!nontemporal` flag for stores in LLVM *sounds* like it is just a hint, but actually, it is not -- at least on x86, non-temporal stores need very special treatment by the programmer or else the Rust memory model breaks down. LLVM still treats these stores as-if they were normal stores for optimizations, which is [highly dubious](https://github.com/llvm/llvm-project/issues/64521). Let's avoid all that dubiousness by making our own non-temporal stores be truly just a hint, which is possible on some targets (e.g. ARM). On all other targets, non-temporal stores become regular stores.
~~Blocked on https://github.com/rust-lang/stdarch/pull/1541 propagating to the rustc repo, to make sure the `_mm_stream` intrinsics are unaffected by this change.~~
Fixes https://github.com/rust-lang/rust/issues/114582
Cc `@Amanieu` `@workingjubilee`
If another thread calls `set_backtrace_style` while a `get_backtrace_style` is reading the environment variables, `get_backtrace_style` will overwrite the value. Use an atomic CAS to avoid this.
fix: #128855 Ensure `Guard`'s `drop` method is removed at `opt-level=s` for `…
fix: #128855
…Copy` types
Added `#[inline]` to the `drop` method in the `Guard` implementation to ensure that the method is removed by the compiler at optimization level `opt-level=s` for `Copy` types. This change aims to align the method's behavior with optimization expectations and ensure it does not affect performance.
r? `@scottmcm`
Apply "polymorphization at home" to RawVec
The idea here is to move all the logic in RawVec into functions with explicit size and alignment parameters. This should eliminate all the fussing about how tweaking RawVec code produces large swings in compile times.
This uncovered https://github.com/rust-lang/rust-clippy/issues/12979, so I've modified the relevant test in a way that tries to preserve the spirit of the test without tripping the ICE.
core: optimise Debug impl for ascii::Char
Rather than writing character at a time, optimise Debug implementation
for core::ascii::Char such that it writes the entire representation
with a single write_str call.
With that, add tests for Display and Debug.
Issue: https://github.com/rust-lang/rust/issues/110998
Improve `Ord` violation help
Recent experience in #128083 showed that the panic message when an Ord violation is detected by the new sort implementations can be confusing. So this PR aims to improve it, together with minor bug fixes in the doc comments for sort*, sort_unstable* and select_nth_unstable*.
Is it possible to get these changes into the 1.81 release? It doesn't change behavior and would greatly help when users encounter this panic for the first time, which they may after upgrading to 1.81.
Tagging `@orlp`
Rather than writing character at a time, optimise Debug implementation
for core::ascii::Char such that it writes the entire representation as
with a single write_str call.
With that, add tests for Display and Debug implementations.
The documentation incorrectly stated that std::env::var could return
an error for variable names containing '=' or the NUL byte. Copy the
correct documentation from var_os.
var_os was fixed in Commit 8a7a665, Pull Request #109894, which
closed Issue #109893.
This documentation was incorrectly added in commit f2c0f292, which
replaced a panic in var_os by returning None, but documented the
change as "May error if ...".
Reference the specific error values and link to them.
VxWorks code refactored
1. Extern TaskNameSet as minimum supported version of os is VxWorks 7 which would have taskNameSet
2. Vx_TASK_NAME_LEN is 31 on VxWorks7, defined variable res.
3. Add unsafe blocks on Non::Zero usage in available_parallelism()
4. Update vxworks docs.
r? `@tgross35`
cc `@devnexen`
Added `#[inline]` to the `drop` method in the `Guard` implementation to ensure that the method is removed by the compiler at optimization level `opt-level=s` for `Copy` types. This change aims to align the method's behavior with optimization expectations and ensure it does not affect performance.
rwlock: disable 'frob' test in Miri on macOS
Due to https://github.com/rust-lang/rust/issues/121950, Miri will sometimes complain about this test on macOS. Better disable the test, as otherwise it can fail for unrelated PRs.
r? ``@joboet``
Mark `{f32,f64}::{next_up,next_down,midpoint}` inline
Most float functions are marked `#[inline]` so any float symbols used by these functions only need to be provided if the function itself is used. RFL recently noticed that `next_up`, `next_down`, and `midpoint` for `f32` and `f64` are not inline, which causes linker errors when building with certain configurations <https://lore.kernel.org/all/20240806150619.192882-1-ojeda@kernel.org/>.
Add the missing attributes so the symbols should no longer be required.
Add tracking issue to core-pattern-type
While the actual `pattern_types` feature flag has an issue assigned, the exported macro and its module do not.
cc #123646
impl `Default` for collection iterators that don't already have it
There is a pretty strong precedent for implementing `Default` for collection iterators, and this does so for some where this implementation was missed.
I don't think this needs a separate ACP (since this precedent already exists, and these feel like they were just missed), however, it *will* need an FCP since these implementations are instantly stable.
Most float functions are marked `#[inline]` so any float symbols used by
these functions only need to be provided if the function itself is used.
RFL recently noticed that `next_up`, `next_down`, and `midpoint` for
`f32` and `f64` are not inline, which causes linker errors when building
with certain configurations [1].
Add the missing attributes so the symbols should no longer be required.
Cc: Gary Guo <gary@garyguo.net>
Reported-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/all/20240806150619.192882-1-ojeda@kernel.org/ [1]
Trivial grammar fix in const keyword docs
This PR makes a trivial fix to the wording of a sentence in the `const` keyword docs.
> `const` items looks remarkably similar to `static` items, [...]
Either this should be written as
> A `const` items looks remarkably similar to a `static` item, [...]
or "looks" should be changed to "look".
I have selected the smaller diff.
Add `f16` and `f128` math functions
This adds intrinsics and math functions for `f16` and `f128` floating point types. Support is quite limited and some things are broken so tests don't run on many platforms, but this provides a starting point.
> `const` items looks remarkably similar to `static` items, [...]
Either this should be written as
> A `const` items looks remarkably similar to a `static` item,
or "looks" should be changed to "look".
I have selected the smaller diff.
Forbid unused unsafe in vxworks-specific std modules
Tracking issue #127747
Adding deny(unsafe_op_in_unsafe_fn) in VxWorks specific files did not cause any error.
Most of VxWorks falls back on Unix libraries. So we'll have to wait for Unix changes.
r? ```@workingjubilee```
Instead of saying to "consider adding a `#[repr(C)]` or
`#[repr(transparent)]` attribute to this struct", we now tell users to
"Use `*const ffi::c_char` instead, and pass the value from
`CStr::as_ptr()`" when the type involved is a `CStr` or a `CString`.
Co-authored-by: Jieyou Xu <jieyouxu@outlook.com>
Rollup of 8 pull requests
Successful merges:
- #128026 (std:🧵 available_parallelism implementation for vxWorks proposal.)
- #128471 (rustdoc: Fix handling of `Self` type in search index and refactor its representation)
- #128607 (Use `object` in `run-make/symbols-visibility`)
- #128609 (Remove unnecessary constants from flt2dec dragon)
- #128611 (run-make: Remove cygpath)
- #128619 (Correct the const stabilization of `<[T]>::last_chunk`)
- #128630 (docs(resolve): more explain about `target`)
- #128660 (tests: more crashes)
r? `@ghost`
`@rustbot` modify labels: rollup
Correct the const stabilization of `<[T]>::last_chunk`
`<[T]>::first_chunk` became const stable in 1.77, but `<[T]>::last_chunk` was left out. This was fixed in 3488679768, which reached stable in 1.80, making `<[T]>::last_chunk` const stable as of that version, but it is documented as being const stable as 1.77. While this is what should have happened, the documentation should reflect what actually did happen.
Remove unnecessary constants from flt2dec dragon
The "dragon" `flt2dec` algorithm uses multi-precision multiplication by (sometimes large) powers of 10. It has precomputed some values to help with these calculations.
BUT:
* There is no need to store powers of 10 and 2 * powers of 10: it is trivial to compute the second from the first.
* We can save a chunk of memory by storing powers of 5 instead of powers of 10 for the large powers (and just shifting as appropriate).
* This also slightly speeds up the routines (by ~1-3%) since the intermediate products are smaller and the shift is cheap.
In this PR, we remove the unnecessary constants and do the necessary adjustments.
Relevant benchmarks before (on my Threadripper 3970X, x86_64-unknown-linux-gnu):
```
num::flt2dec::bench_big_shortest 137.92/iter +/- 2.24
num::flt2dec::strategy:🐉:bench_big_exact_12 2135.28/iter +/- 38.90
num::flt2dec::strategy:🐉:bench_big_exact_3 904.95/iter +/- 10.58
num::flt2dec::strategy:🐉:bench_big_exact_inf 47230.33/iter +/- 320.84
num::flt2dec::strategy:🐉:bench_big_shortest 3915.05/iter +/- 51.37
```
and after:
```
num::flt2dec::bench_big_shortest 137.40/iter +/- 2.03
num::flt2dec::strategy:🐉:bench_big_exact_12 2101.10/iter +/- 25.63
num::flt2dec::strategy:🐉:bench_big_exact_3 873.86/iter +/- 4.20
num::flt2dec::strategy:🐉:bench_big_exact_inf 47468.19/iter +/- 374.45
num::flt2dec::strategy:🐉:bench_big_shortest 3877.01/iter +/- 45.74
```
Implement cursors for `BTreeSet`
Tracking issue: https://github.com/rust-lang/rust/issues/107540
This is a straightforward wrapping of the map API, except that map's `CursorMut` does not make sense, because there is no value to mutate. Hence, map's `CursorMutKey` is wrapped here as just `CursorMut`, since it's unambiguous for sets and we don't normally speak of "keys". On the other hand, I can see some potential for confusion with `CursorMut` meaning different things in each module. I'm happy to take suggestions to improve that.
r? ````@Amanieu````
`<[T]>::first_chunk` became const stable in 1.77, but `<[T]>::last_chunk` was
left out. This was fixed in 3488679768, which reached stable in 1.80,
making `<[T]>::last_chunk` const stable as of that version, but it is
documented as being const stable as 1.77. While this is what should have
happened, the documentation should reflect what actually did happen.
Move the standard library to a separate workspace
This ensures that the Cargo.lock packaged for it in the rust-src component is up-to-date, allowing rust-analyzer to run cargo metadata on the standard library even when the rust-src component is stored in a read-only location as is necessary for loading crates.io dependencies of the standard library.
This also simplifies tidy's license check for runtime dependencies as it can now look at all entries in library/Cargo.lock without having to filter for just the dependencies of runtime crates. In addition this allows removing an exception in check_runtime_license_exceptions that was necessary due to the compiler enabling a feature on the object crate which pulls in a dependency not allowed for the standard library.
While cargo workspaces normally enable dependencies of multiple targets to be reused, for the standard library we do not want this reusing to prevent conflicts between dependencies of the sysroot and of tools that are built using this sysroot. For this reason we already use an unstable cargo feature to ensure that any dependencies which would otherwise be shared get a different -Cmetadata argument as well as using separate build dirs.
This doesn't change the situation around vendoring. We already have several cargo workspaces that need to be vendored. Adding another one doesn't change much.
There are also no cargo profiles that are shared between the root workspace and the library workspace anyway, so it doesn't add any extra work when changing cargo profiles.
This PR makes a number of changes to the UNIX randomness implementation:
* Use `io::Error` for centralized error handling
* Move the file-fallback logic out of the `getrandom`-specific module
* Stop redefining the syscalls on macOS and DragonFly, they have appeared in `libc`
* Add a `OnceLock` to cache the random device file descriptor
chore: refactor backtrace style in panic
# Refactor get_backtrace_style for better readability and potential performance improvements
This PR aims to improve the readability and maintainability of the `set_backtrace_style` and `get_backtrace_style` function.
Implement `UncheckedIterator` directly for `RepeatN`
This just pulls the code out of `next` into `next_unchecked`, rather than making the `Some` and `unwrap_unchecked`ing it.
And while I was touching it, I added a codegen test that `array::repeat` for something that's just `Clone`, not `Copy`, still ends up optimizing to the same thing as `[x; n]`: <https://rust.godbolt.org/z/YY3a5ajMW>.
The "dragon" `flt2dec` algorithm uses multi-precision multiplication by
(sometimes large) powers of 10. It has precomputed some values to help
with these calculations.
BUT:
* There is no need to store powers of 10 and 2 * powers of 10: it is
trivial to compute the second from the first.
* We can save a chunk of memory by storing powers of 5 instead of powers
of 10 for the large powers (and just shifting by 2 as appropriate).
* This also slightly speeds up the routines (by ~1-3%) since the
intermediate products are smaller and the shift is cheap.
In this PR, we remove the unnecessary constants and do the necessary
adjustments.
Relevant benchmarks before (on my Threadripper 3970X, x86_64-unknown-linux-gnu):
```
num::flt2dec::bench_big_shortest 137.92/iter +/- 2.24
num::flt2dec::strategy:🐉:bench_big_exact_12 2135.28/iter +/- 38.90
num::flt2dec::strategy:🐉:bench_big_exact_3 904.95/iter +/- 10.58
num::flt2dec::strategy:🐉:bench_big_exact_inf 47230.33/iter +/- 320.84
num::flt2dec::strategy:🐉:bench_big_shortest 3915.05/iter +/- 51.37
```
and after:
```
num::flt2dec::bench_big_shortest 137.40/iter +/- 2.03
num::flt2dec::strategy:🐉:bench_big_exact_12 2101.10/iter +/- 25.63
num::flt2dec::strategy:🐉:bench_big_exact_3 873.86/iter +/- 4.20
num::flt2dec::strategy:🐉:bench_big_exact_inf 47468.19/iter +/- 374.45
num::flt2dec::strategy:🐉:bench_big_shortest 3877.01/iter +/- 45.74
```
Revert recent changes to dead code analysis
This is a revert to recent changes to dead code analysis, namely:
* efdf219 Rollup merge of #128104 - mu001999-contrib:fix/128053, r=petrochenkov
* a70dc297a8 Rollup merge of #127017 - mu001999-contrib:dead/enhance, r=pnkfelix
* 31fe9628cf Rollup merge of #127107 - mu001999-contrib:dead/enhance-2, r=pnkfelix
* 2724aeaaeb Rollup merge of #126618 - mu001999-contrib:dead/enhance, r=pnkfelix
* 977c5fd419 Rollup merge of #126315 - mu001999-contrib:fix/126289, r=petrochenkov
* 13314df21b Rollup merge of #125572 - mu001999-contrib:dead/enhance, r=pnkfelix
There is an additional change stacked on top, which suppresses false-negatives that were masked by this work. I believe the functions that are touched in that code are legitimately unused functions and the types are not reachable since this `AnonPipe` type is not publically reachable -- please correct me if I'm wrong cc `@NobodyXu` who added these in ##127153.
Some of these reverts (#126315 and #126618) are only included because it makes the revert apply cleanly, and I think these changes were only done to fix follow-ups from the other PRs?
I apologize for the size of the PR and the churn that it has on the codebase (and for reverting `@mu001999's` work here), but I'm putting this PR up because I am concerned that we're making ad-hoc changes to fix bugs that are fallout of these PRs, and I'd like to see these changes reimplemented in a way that's more separable from the existing dead code pass. I am happy to review any code to reapply these changes in a more separable way.
cc `@mu001999`
r? `@pnkfelix`
Fixes#128272Fixes#126169
Add `#[must_use]` to some `into_raw*` functions.
cc #121287
r? ``@cuviper``
Adds `#[must_use = "losing the pointer will leak memory"]`[^1] to `Box::into_raw(_with_allocator)`, `Vec::into_raw_parts(_with_alloc)`, `String::into_raw_parts`[^2], and `rc::{Rc, Weak}::into_raw_with_allocator` (Rc's normal `into_raw` and all of `Arc`'s `into_raw*`s are already `must_use`).
Adds `#[must_use = "losing the raw <resource name may leak resources"]` to `IntoRawFd::into_raw_fd`, `IntoRawSocket::into_raw_socket`, and `IntoRawHandle::into_raw_handle`.
[^1]: "*will* leak memory" may be too-strong wording (since `Box`/`Vec`/`String`/`rc::Weak` might not have a backing allocation), but I left it as-is for simplicity and consistency.
[^2]: `String::into_raw_parts`'s `must_use` message is changed from the previous (possibly misleading) "`self` will be dropped if the result is not used".
Added SHA512, SM3, SM4 target-features and `sha512_sm_x86` feature gate
This is an effort towards #126624. This adds support for these 3 target-features and introduces the feature flag `sha512_sm_x86`, which would gate these target-features and the yet-to-be-implemented detection and intrinsics in stdarch.
This ensures that the Cargo.lock packaged for it in the rust-src
component is up-to-date, allowing rust-analyzer to run cargo metadata on
the standard library even when the rust-src component is stored in a
read-only location as is necessary for loading crates.io dependencies of
the standard library.
This also simplifies tidy's license check for runtime dependencies as it
can now look at all entries in library/Cargo.lock without having to
filter for just the dependencies of runtime crates. In addition this
allows removing an exception in check_runtime_license_exceptions that
was necessary due to the compiler enabling a feature on the object crate
which pulls in a dependency not allowed for the standard library.
While cargo workspaces normally enable dependencies of multiple targets
to be reused, for the standard library we do not want this reusing to
prevent conflicts between dependencies of the sysroot and of tools that
are built using this sysroot. For this reason we already use an unstable
cargo feature to ensure that any dependencies which would otherwise be
shared get a different -Cmetadata argument as well as using separate
build dirs.
This doesn't change the situation around vendoring. We already have
several cargo workspaces that need to be vendored. Adding another one
doesn't change much.
There are also no cargo profiles that are shared between the root
workspace and the library workspace anyway, so it doesn't add any extra
work when changing cargo profiles.
Rewrite binary search implementation
This PR builds on top of #128250, which should be merged first.
This restores the original binary search implementation from #45333 which has the nice property of having a loop count that only depends on the size of the slice. This, along with explicit conditional moves from #128250, means that the entire binary search loop can be perfectly predicted by the branch predictor.
Additionally, LLVM is able to unroll the loop when the slice length is known at compile-time. This results in a very compact code sequence of 3-4 instructions per binary search step and zero branches.
Fixes#53823Fixes#115271
raw_eq: using it on bytes with provenance is not UB (outside const-eval)
The current behavior of raw_eq violates provenance monotonicity. See https://github.com/rust-lang/rust/pull/124921 for an explanation of provenance monotonicity. It is violated in raw_eq because comparing bytes without provenance is well-defined, but adding provenance makes the operation UB.
So remove the no-provenance requirement from raw_eq. However, the requirement stays in-place for compile-time invocations of raw_eq, that indeed cannot deal with provenance.
Cc `@rust-lang/opsem`
Due to a LLVM bug, `f128` math functions link successfully but LLVM
chooses the wrong symbols (`long double` symbols rather than those for
binary128).
Since this is a notable problem that may surprise a number of users, add
a note about it.
Link: https://github.com/llvm/llvm-project/issues/44744