9803 Commits

Author SHA1 Message Date
Bart Jacobs
06e2e7aae1
CStr docs: Fix CStr vs &CStr confusion
The CStr docs used to say things about CStr that are only true for &CStr.

Also, it's the bytes that are being borrowed, not the reference. One could say that it's the reference that is doing the borrowing, rather than being borrowed.
2025-11-11 17:18:28 +01:00
bors
2636cb4c13 Auto merge of #148818 - Zalathar:rollup-4vujcg0, r=Zalathar
Rollup of 13 pull requests

Successful merges:

 - rust-lang/rust#148694 (std: support `RwLock` and thread parking on TEEOS)
 - rust-lang/rust#148712 (Port `cfg_select!` to the new attribute parsing system)
 - rust-lang/rust#148760 (rustc_target: hide TargetOptions::vendor)
 - rust-lang/rust#148771 (IAT: Reinstate early bailout)
 - rust-lang/rust#148775 (Fix a typo in the documentation for the strict_shr function)
 - rust-lang/rust#148779 (Implement DynSend and DynSync for std::panic::Location.)
 - rust-lang/rust#148781 ([rustdoc] Remove unneeded `allow(rustc::potential_query_instability)`)
 - rust-lang/rust#148783 (add test for assoc type norm wf check)
 - rust-lang/rust#148785 (Replace `master` branch references with `main`)
 - rust-lang/rust#148791 (fix "is_closure_like" doc comment)
 - rust-lang/rust#148792 (Prefer to use file.stable_id over file.name from source map)
 - rust-lang/rust#148805 (rustc-dev-guide subtree update)
 - rust-lang/rust#148807 (Document (and test) a problem with `Clone`/`Copy` deriving.)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-11-11 13:30:50 +00:00
Stuart Cook
0c615a1adb
Rollup merge of #148775 - reddevilmidzy:fix-typo, r=joboet
Fix a typo in the documentation for the strict_shr function

fix: rust-lang/rust#148761
2025-11-11 21:11:51 +11:00
Stuart Cook
044c079b15
Rollup merge of #147771 - nxsaken:div_shlr_exact, r=dtolnay
Rename `*exact_{div,shr,shl}` to `*{div,shr,shl}_exact`

Related to rust-lang/rust#144336 and rust-lang/rust#139911, see https://github.com/rust-lang/rust/issues/139911#issuecomment-3406807537. I haven't touched the `exact_div`, `exact_udiv` and `exact_sdiv` intrinsics. Let me know if I should.
2025-11-11 21:09:34 +11:00
Stuart Cook
5b9211c5b3
Rollup merge of #141470 - GuillaumeGomez:function_casts_as_integer, r=urgau
Add new `function_casts_as_integer` lint

The `function_casts_as_integer` lint detects cases where users cast a function pointer into an integer.

*warn-by-default*

### Example

```rust
fn foo() {}
let x = foo as usize;
```

```
warning: casting a function into an integer implicitly
  --> $DIR/function_casts_as_integer.rs:9:17
   |
LL |     let x = foo as usize;
   |                 ^^^^^^^^
   |
help: add `fn() as usize`
   |
LL |     let x = foo as fn() as usize;
   |                 +++++++
```

### Explanation

You should never cast a function directly into an integer but go through a cast as `fn` first to make it obvious what's going on. It also allows to prevent confusion with (associated) constants.

Related to https://github.com/rust-lang/rust/issues/81686 and https://stackoverflow.com/questions/68701177/whats-the-meaning-of-casting-a-rust-enum-variant-to-a-numeric-data-type

r? ````@urgau````
2025-11-11 21:09:32 +11:00
sayantn
740b8ba8ad
Make SIMD intrinsics available in const-contexts 2025-11-11 03:27:33 +05:30
Shun Sakai
f4efc370e6 feat: Add bit_width for unsigned NonZero<T> 2025-11-11 01:14:38 +09:00
bors
055d0d6aaf Auto merge of #135634 - joboet:trivial-clone, r=Mark-Simulacrum
stop specializing on `Copy`

fixes https://github.com/rust-lang/rust/issues/132442

`std` specializes on `Copy` to optimize certain library functions such as `clone_from_slice`. This is unsound, however, as the `Copy` implementation may not be always applicable because of lifetime bounds, which specialization does not take into account; the result being that values are copied even though they are not `Copy`. For instance, this code:
```rust
struct SometimesCopy<'a>(&'a Cell<bool>);

impl<'a> Clone for SometimesCopy<'a> {
    fn clone(&self) -> Self {
        self.0.set(true);
        Self(self.0)
    }
}

impl Copy for SometimesCopy<'static> {}

let clone_called = Cell::new(false);
// As SometimesCopy<'clone_called> is not 'static, this must run `clone`,
// setting the value to `true`.
let _ = [SometimesCopy(&clone_called)].clone();
assert!(clone_called.get());
```
should not panic, but does ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6be7a48cad849d8bd064491616fdb43c)).

To solve this, this PR introduces a new `unsafe` trait: `TrivialClone`. This trait may be implemented whenever the `Clone` implementation is equivalent to copying the value (so e.g. `fn clone(&self) -> Self { *self }`). Because of lifetime erasure, there is no way for the `Clone` implementation to observe lifetime bounds, meaning that even if the `TrivialClone` has stricter bounds than the `Clone` implementation, its invariant still holds. Therefore, it is sound to specialize on `TrivialClone`.

I've changed all `Copy` specializations in the standard library to specialize on `TrivialClone` instead. Unfortunately, the unsound `#[rustc_unsafe_specialization_marker]` attribute on `Copy` cannot be removed in this PR as `hashbrown` still depends on it. I'll make a PR updating `hashbrown` once this lands.

With `Copy` no longer being considered for specialization, this change alone would result in the standard library optimizations not being applied for user types unaware of `TrivialClone`. To avoid this and restore the optimizations in most cases, I have changed the expansion of `#[derive(Clone)]`: Currently, whenever both `Clone` and `Copy` are derived, the `clone` method performs a copy of the value. With this PR, the derive macro also adds a `TrivialClone` implementation to make this case observable using specialization. I anticipate that most users will use `#[derive(Clone, Copy)]` whenever both are applicable, so most users will still profit from the library optimizations.

Unfortunately, Hyrum's law applies to this PR: there are some popular crates which rely on the precise specialization behaviour of `core` to implement "specialization at home", e.g. [`libAFL`](89cff63702/libafl_bolts/src/tuples.rs (L27-L49)). I have no remorse for breaking such horrible code, but perhaps we should open other, better ways to satisfy their needs – for example by dropping the `'static` bound on `TypeId::of`...
2025-11-10 15:41:43 +00:00
Guillaume Gomez
40be1db6b8 Fix new function_casts_as_integer lint errors in core, std, panic_unwind and compiler crates 2025-11-10 16:38:28 +01:00
reddevilmidzy
3d44acac27 Fix a typo in the documentation for the strict_shr function 2025-11-10 15:22:08 +09:00
reddevilmidzy
5d595cf8ba Expand pow docs with special-case tests 2025-11-10 14:56:05 +09:00
nxsaken
1d9be661a8 Add tracking issue number 2025-11-10 09:38:04 +04:00
joboet
16d2b5534e
prevent TrivialClone implementations from appearing in rustdoc output 2025-11-09 22:26:15 +01:00
Matthias Krüger
5591d7e134
Rollup merge of #148285 - nxsaken:const_control_flow_1, r=Mark-Simulacrum
Constify `ControlFlow` methods with unstable bounds

Feature: `const_control_flow`
Tracking issue: rust-lang/rust#148739

This PR constifies the methods on `ControlFlow` with a dependency on rust-lang/rust#143874.
2025-11-09 20:59:53 +01:00
Matthias Krüger
5598d535da
Rollup merge of #148248 - nxsaken:const_control_flow, r=Mark-Simulacrum
Constify `ControlFlow` methods without unstable bounds

Feature: `min_const_control_flow`
Tracking issue: rust-lang/rust#148738

This PR constifies some of the methods on `ControlFlow`.
2025-11-09 20:59:52 +01:00
nxsaken
264c6d41aa Constify mem::take 2025-11-09 21:52:04 +04:00
Matthias Krüger
e5a69bb215
Rollup merge of #148683 - fmease:rm-const_trait-attr, r=fee1-dead
Remove `#[const_trait]`

Remove `#[const_trait]` since we now have `const trait`. Update all structured diagnostics that still suggested the attribute.

r? ```@rust-lang/project-const-traits```
2025-11-09 17:37:05 +01:00
joboet
7c430e7646
automatically implement TrivialClone for closures and tuples
If each of the component types is `TrivialClone`, the closure/tuple itself can be trivially cloned.
2025-11-09 17:31:19 +01:00
joboet
7b72cc6156
make TrivialClone a #[marker]-trait to keep it from appearing in error messages 2025-11-09 17:31:19 +01:00
joboet
e4e765b1f6
add a TrivialClone implementation when deriving both Clone and Copy 2025-11-09 17:31:17 +01:00
nxsaken
fc4056ec78 Constify ManuallyDrop::take 2025-11-09 20:21:12 +04:00
joboet
5fb5861765
(almost) get rid of the unsound #[rustc_unsafe_specialization_marker] on Copy, introduce TrivialClone 2025-11-09 15:51:25 +01:00
Scott McMurray
86c3ba754a Implement the alternative try desugaring 2025-11-09 04:09:10 -08:00
nxsaken
d05133f3a4 Update feature name, add tracking issue number 2025-11-09 13:36:35 +04:00
nxsaken
3175799208 Add tracking issue number 2025-11-09 13:33:47 +04:00
nxsaken
852bd86d17 Constify ControlFlow methods (unstable bounds) 2025-11-09 13:30:59 +04:00
bors
20f1c045c4 Auto merge of #148721 - Zalathar:rollup-398va3y, r=Zalathar
Rollup of 22 pull requests

Successful merges:

 - rust-lang/rust#128666 (Add `overflow_checks` intrinsic)
 - rust-lang/rust#146305 (Add correct suggestion for multi-references for self type in method)
 - rust-lang/rust#147179 ([DebugInfo] Fix container types failing to find template args)
 - rust-lang/rust#147743 (Show packed field alignment in mir_transform_unaligned_packed_ref)
 - rust-lang/rust#148079 (Rename `downcast_[ref|mut]_unchecked` -> `downcast_unchecked_[ref|mut]`)
 - rust-lang/rust#148084 (Optimize path components iteration on platforms that don't have prefixes)
 - rust-lang/rust#148126 (Fix rust stdlib build failing for VxWorks)
 - rust-lang/rust#148204 (Modify contributor email entries in .mailmap)
 - rust-lang/rust#148279 (rustc_builtin_macros: rename bench parameter to avoid collisions with user-defined function names)
 - rust-lang/rust#148333 (constify result unwrap unchecked)
 - rust-lang/rust#148539 (Add Allocator proxy impls for Box, Rc, and Arc)
 - rust-lang/rust#148601 (`invalid_atomic_ordering`: also lint `update` & `try_update`)
 - rust-lang/rust#148612 (Add note for identifier with attempted hygiene violation)
 - rust-lang/rust#148613 (Switch hexagon targets to rust-lld)
 - rust-lang/rust#148619 (Enable std locking functions on AIX)
 - rust-lang/rust#148644 ([bootstrap] Make `--open` option work with `doc src/tools/error_index_generator`)
 - rust-lang/rust#148649 (don't completely reset `HeadUsages`)
 - rust-lang/rust#148673 (Remove a remnant of `dyn*` from the parser)
 - rust-lang/rust#148675 (Remove eslint-js from npm dependencies)
 - rust-lang/rust#148680 (Recover `[T: N]` as `[T; N]`)
 - rust-lang/rust#148688 (Remove unused argument `features` from `eval_config_entry`)
 - rust-lang/rust#148711 (Use the current lint note id when parsing `cfg!()`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-11-09 08:27:35 +00:00
Stuart Cook
020dd317db
Rollup merge of #148333 - bend-n:const_result_unwrap_unchecked, r=mark-simulacrum
constify result unwrap unchecked

constifies unwrap unchecked on result
will make tracking issue if good
2025-11-09 13:22:29 +11:00
Stuart Cook
f424eb908e
Rollup merge of #148079 - taj-p:master, r=Mark-Simulacrum
Rename `downcast_[ref|mut]_unchecked` -> `downcast_unchecked_[ref|mut]`

## Intent

Renames `downcast_[ref|mut]_unchecked` to `downcast_unchecked_[ref|mut]` because we want to emphasise that it is the downcast that is unsafe, not the aliasing per:

https://github.com/rust-lang/rust/issues/90850#issuecomment-2749035832

## Tracking Issue: https://github.com/rust-lang/rust/issues/90850#issuecomment-3437027607

cc `@marc0246`
2025-11-09 13:22:26 +11:00
Stuart Cook
d3475140ee
Rollup merge of #128666 - pitaj:intrinsic-overflow_checks, r=BoxyUwU
Add `overflow_checks` intrinsic

This adds an intrinsic which allows code in a pre-built library to inherit the overflow checks option from a crate depending on it. This enables code in the standard library to explicitly change behavior based on whether `overflow_checks` are enabled, regardless of the setting used when standard library was compiled.

This is very similar to the `ub_checks` intrinsic, and refactors the two to use a common mechanism.

The primary use case for this is to allow the new `RangeFrom` iterator to yield the maximum element before overflowing, as requested [here](https://github.com/rust-lang/rust/issues/125687#issuecomment-2151118208). This PR includes a working `IterRangeFrom` implementation based on this new intrinsic that exhibits the desired behavior.

[Prior discussion on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Ability.20to.20select.20code.20based.20on.20.60overflow_checks.60.3F)
2025-11-09 13:22:23 +11:00
bendn
edd7d8a2fd
constify result unwrap unchecked 2025-11-09 04:17:15 +07:00
Peter Jaszkowiak
cc8b95cc54 add overflow_checks intrinsic 2025-11-08 10:57:35 -07:00
Matthias Krüger
9ccff4ae27
Rollup merge of #147686 - vrtgs:non-zero-isolate, r=joboet
update isolate_highest_one for NonZero<T>

## Rationale
Let `x = self` and
`m = (((1 as $Int) << (<$Int>::BITS - 1)).wrapping_shr(self.leading_zeros()))`
Then the previous code computed `NonZero::new_unchecked(x & m)`.
Since `m` has exactly one bit set (the most significant 1-bit of `x`), `(x & m) == m`.
Therefore, the masking step was redundant.

The shift is safe and does not need wrapping because:
* `self.leading_zeros() < $Int::BITS` because `self` is non-zero.
* The result of `unchecked_shr` is non-zero, satisfying the `NonZero` invariant. if wrapping happens we would be violating `NonZero` invariants.

why this micro optimization?
the old code was suboptimal it duplicated `$Int`’s isolate_highest_one logic instead of delegating to it. Since the type already wraps `$Int`, either delegation should be used for clarity or, if keeping a custom implementation, it should be optimized as above.
2025-11-08 15:42:22 +01:00
Matthias Krüger
da2e3aabca
Rollup merge of #147540 - bjoernager:slice-as-array, r=Amanieu
Stabilise `as_array` in `[_]` and `*const [_]`; stabilise `as_mut_array` in `[_]` and `*mut [_]`.

Tracking issue: rust-lang/rust#133508

Closes: rust-lang/rust#133508

This PR stabilises the `as_array` and `as_mut_array` associated functions from the `core_slice_as_array` feature gate:

```rust
// core::slice

impl<T> [T] {
    pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]>;

    pub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>;
}

// core::ptr

impl<T> *const [T] {
    pub const fn as_array<const N: usize>(self) -> Option<*const [T; N]>;
}

impl<T> *mut [T] {
    pub const fn as_mut_array<const N: usize>(self) -> Option<*mut [T; N]>;
}
```

It also updates the feature gates and tracking issues for all items associated with the previous `slice_as_array` tracking issue (including these four that are being stabilised).

~~FCP missing.~~
2025-11-08 15:42:22 +01:00
bors
bbb6f68e28 Auto merge of #147803 - jsgf:move-copy-codegen, r=madsmtm,saethlin
Add -Zannotate-moves for profiler visibility of move/copy operations (codegen)

**Note:** this is an alternative implementation of https://github.com/rust-lang/rust/pull/147206; rather than being a MIR transform, it adds the annotations closer to codegen. It's functionally the same but the implementation is lower impact and it could be more correct.

---

This implements a new unstable compiler flag `-Zannotate-moves` that makes move and copy operations visible in profilers by creating synthetic debug information. This is achieved with zero runtime cost by manipulating debug info scopes to make moves/copies appear as calls to `compiler_move<T, SIZE>` and `compiler_copy<T, SIZE>` marker functions in profiling tools.

This allows developers to identify expensive move/copy operations in their code using standard profiling tools, without requiring specialized tooling or runtime instrumentation.

The implementation works at codegen time. When processing MIR operands (`Operand::Move` and `Operand::Copy`), the codegen creates an `OperandRef` with an optional `move_annotation` field containing an `Instance` of the appropriate profiling marker function. When storing the operand, `store_with_annotation()` wraps the store operation in a synthetic debug scope that makes it appear inlined from the marker.

Two marker functions (`compiler_move` and `compiler_copy`) are defined in `library/core/src/profiling.rs`. These are never actually called - they exist solely as debug info anchors.

Operations are only annotated if:
   - We're generating debug info and the feature is enabled.
   - Meets the size threshold (default: 65 bytes, configurable via `-Zannotate-moves=SIZE`), and is non-zero
   - Has a memory representation

This has a very small size impact on object file size. With the default limit it's well under 0.1%, and even with a very small limit of 8 bytes it's still ~1.5%. This could be enabled by default.
2025-11-08 07:57:14 +00:00
León Orell Valerian Liehr
8aedbf12f6
Replace #[const_trait] with const in libcore 2025-11-08 06:40:27 +01:00
Vrtgs
057127cfee update isolate_highest_one for NonZero<T> 2025-11-08 00:22:36 +03:00
Gabriel Bjørnager Jensen
fa8e8649ad
Stabilise 'as_array' in '[_]' and '*const [_]'; Stabilise 'as_mut_array' in '[_]' and '*mut [_]'; Update feature gate and tracking issue for 'alloc_slice_into_array' items; 2025-11-07 15:14:41 +01:00
Jacob Pratt
c932d7c45f
Rollup merge of #148609 - AMDmi3:rsplit_once_example, r=chenyukang
Sync str::rsplit_once example with str::split_once

This adds `"cfg=".rsplit_once('=')` case to `rsplit_once` example, bringing it in sync with example for `split_once`. For consistency and to make life easier for ones who want to ensure bahaviour of this specific edge case.
2025-11-07 00:21:24 -05:00
Jacob Pratt
9d001902ae
Rollup merge of #148578 - WaffleLapkin:equal-alignment-atomic-from-mut-slice, r=m-ou-se
core docs: add notes about availability of `Atomic*::from_mut_slice`

See https://github.com/rust-lang/rust/issues/76314#issuecomment-3496758620

r? libs-api
2025-11-07 00:21:23 -05:00
Jacob Pratt
3d765e3788
Rollup merge of #148520 - sorairolake:update-lowest-highest-one-doctests, r=tgross35
style: Use binary literals instead of hex literals in doctests for `highest_one` and `lowest_one`

For example, I think it's easier to understand that the index of the highest bit set to one in `16` is `4` as `0b10000` than as `0x10`.

```rust
assert_eq!(0x10_u64.highest_one(), Some(4));
```

Instead of:

```rust
assert_eq!(0b10000_u64.highest_one(), Some(4));
```

rust-lang/rust#145203
2025-11-07 00:21:19 -05:00
Jeremy Fitzhardinge
5f29f11a4d Add -Zannotate-moves for profiler visibility of move/copy operations
This implements a new unstable compiler flag `-Zannotate-moves` that makes
move and copy operations visible in profilers by creating synthetic debug
information. This is achieved with zero runtime cost by manipulating debug
info scopes to make moves/copies appear as calls to `compiler_move<T, SIZE>`
and `compiler_copy<T, SIZE>` marker functions in profiling tools.

This allows developers to identify expensive move/copy operations in their
code using standard profiling tools, without requiring specialized tooling
or runtime instrumentation.

The implementation works at codegen time. When processing MIR operands
(`Operand::Move` and `Operand::Copy`), the codegen creates an `OperandRef`
with an optional `move_annotation` field containing an `Instance` of the
appropriate profiling marker function. When storing the operand,
`store_with_annotation()` wraps the store operation in a synthetic debug
scope that makes it appear inlined from the marker.

Two marker functions (`compiler_move` and `compiler_copy`) are defined
in `library/core/src/profiling.rs`. These are never actually called -
they exist solely as debug info anchors.

Operations are only annotated if the type:
   - Meets the size threshold (default: 65 bytes, configurable via
     `-Zannotate-moves=SIZE`)
   - Has a non-scalar backend representation (scalars use registers,
     not memcpy)

This has a very small size impact on object file size. With the default
limit it's well under 0.1%, and even with a very small limit of 8 bytes
it's still ~1.5%. This could be enabled by default.
2025-11-06 15:39:45 -08:00
Dmitry Marakasov
b975c570fa Sync str::rsplit_once example with str::split_once 2025-11-07 01:01:54 +03:00
Yosh
a15c21ecdb
Update drop_guard.rs 2025-11-06 18:44:49 +01:00
Ralf Jung
b032fac34e stabilize duration_from_nanos_u128 2025-11-06 18:08:29 +01:00
Yosh
30cdb68848
DropGuard::into_inner -> DropGuard::dismiss
Also changes it from a static method to an instance method.
2025-11-06 17:27:12 +01:00
Waffle Lapkin
893f0d2cff
core docs: add notes about availability of Atomic*::from_mut_slice 2025-11-06 15:23:11 +01:00
Matthias Krüger
f7f128fd48
Rollup merge of #146861 - antonilol:vec_deque_extend_front, r=joboet
add extend_front to VecDeque with specialization like extend

ACP: https://github.com/rust-lang/libs-team/issues/658
Tracking issue: rust-lang/rust#146975

_Text below was written before opening the ACP_

Feature was requested in rust-lang/rust#69939, I recently also needed it so decided to implement it as my first contribution to the Rust standard library. I plan on doing more but wanted to start with a small change.

Some questions I had (both on implementation and design) with answers:
- Q: `extend` allows iterators that yield `&T` where `T` is `Clone`, should extend_front do too?
  A: No, users can use [`copied`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.copied) and/or [`cloned`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.cloned).
- Q: Does this need a whole new trait like Extend or only a method on `VecDeque`?
  A: No, see ACP.
- Q: How do I deal with all the code duplication? Most code is similar to that of `extend`, maybe there is a nice way to factor out the code around `push_unchecked`/`push_front_unchecked`.
  Will come back to this later.
- Q: Why are certain things behind feature gates, `cfg(not(test))` like `vec::IntoIter` here and `cfg(not(no_global_oom_handling))` like `Vec::extend_from_within`? (I am also looking at implementing `VecDeque::extend_from_within`)
  A: See https://github.com/rust-lang/rust/pull/146861#pullrequestreview-3250163369
- Q: Should `extend_front` act like repeated pushes to the front of the queue? This reverses the order of the elements. Doing it different might incur an extra move if the iterator length is not known up front (where do you start placing elements in the buffer?).
  A: `extend_front` acts like repeated pushes, `prepend` preserves the element order, see ACP or tracking issue.
2025-11-06 12:29:57 +01:00
Shun Sakai
d956fa10ce style: Update doctests for highest_one and lowest_one
Use binary literals instead of hex literals.
2025-11-06 20:07:47 +09:00
Ralf Jung
434cb5e700 document behavior of rotations for n >= BITS 2025-11-06 08:02:10 +01:00