Commit Graph

3398 Commits

Author SHA1 Message Date
Matthias Krüger
47bd38c2f1 Rollup merge of #145685 - Qelxiros:cell_get_cloned, r=programmerjake,tgross35
add CloneFromCell and Cell::get_cloned

Tracking issue: rust-lang/rust#145329
2025-10-04 17:11:08 +02:00
Jeremy Smart
08b4641f50 add CloneFromCell and Cell::get_cloned 2025-10-01 18:47:09 -04:00
edwloef
8dfea22c97 implement Box::take 2025-10-01 17:21:12 +02:00
Matthias Krüger
f7c7e34ae4 Rollup merge of #146886 - taiki-e:rc-inner-align, r=Mark-Simulacrum
Add repr(align(2)) to RcInner and ArcInner

`Rc` currently assumes that `RcInner` has at least 2-byte alignment, but on AVR, `usize` has 1-byte alignment (this is because the AVR has 1-byte register sizes, so having 2-byte alignment is generally useless), breaking this assumption.

9f32ccf35f/library/alloc/src/rc.rs (L3005-L3008)

This PR adds `repr(align(2))` to force `RcInner` to always have at least 2-byte alignment.

Note that `ArcInner` doesn't need `repr(align(2))` because atomic types have the alignment same as its size. This PR adds a comment about this.
2025-09-30 20:46:45 +02:00
Taiki Endo
9e79fac035 Add repr(align(2)) to RcInner and ArcInner 2025-09-30 22:39:10 +09:00
Yotam Ofek
68a7c25078 Use Iterator::eq and (dogfood) eq_by in compiler and library 2025-09-29 08:08:05 +03:00
bors
c7f6aa2869 Auto merge of #147042 - Noratrieb:untrack-caller-vec, r=tgross35
Remove most `#[track_caller]` from allocating Vec methods

They cause significant binary size overhead while contributing little value.

closes rust-lang/rust#146963, see that issue for more details.
2025-09-28 03:23:45 +00:00
Guillaume Gomez
254a2139f6 Remove cfg(bootstrap) for doc_cfg feature following #141925 2025-09-27 11:29:49 +02:00
Guillaume Gomez
a7ed9bf6c7 fmt 2025-09-27 11:29:49 +02:00
Guillaume Gomez
fccba2c341 Remove doc_cfg_hide feature 2025-09-27 11:29:49 +02:00
Guillaume Gomez
63aefe0737 Strenghten checks for doc(auto_cfg(show/hide)) attributes 2025-09-27 11:29:48 +02:00
Guillaume Gomez
7c00bccd3b Implement RFC 3631 2025-09-27 11:29:48 +02:00
Mark Rousskov
4e9716fbc5 Update CURRENT_RUSTC_VERSION post-bump 2025-09-26 18:41:32 -04:00
bors
7ac0330c6d Auto merge of #147037 - matthiaskrgr:rollup-xtgqzuu, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - rust-lang/rust#116882 (rustdoc: hide `#[repr]` if it isn't part of the public ABI)
 - rust-lang/rust#135771 ([rustdoc] Add support for associated items in "jump to def" feature)
 - rust-lang/rust#141032 (avoid violating `slice::from_raw_parts` safety contract in `Vec::extract_if`)
 - rust-lang/rust#142401 (Add proper name mangling for pattern types)
 - rust-lang/rust#146293 (feat: non-panicking `Vec::try_remove`)
 - rust-lang/rust#146859 (BTreeMap: Don't leak allocators when initializing nodes)
 - rust-lang/rust#146924 (Add doc for `NonZero*` const creation)
 - rust-lang/rust#146933 (Make `render_example_with_highlighting` return an `impl fmt::Display`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-09-25 20:35:49 +00:00
Noratrieb
9316d4508c Remove most #[track_caller] from allocating Vec methods
They cause significant binary size overhead while contributing little
value.

Also removes them from the wrapping String methods that do not panic.
2025-09-25 20:52:03 +02:00
Matthias Krüger
83cf8f9860 Rollup merge of #146859 - cammeresi:btree-alloc-20250920, r=joboet
BTreeMap: Don't leak allocators when initializing nodes

Memory was allocated via `Box::leak` and thence intended to be tracked and deallocated manually, but the allocator was also leaked, not tracked, and never dropped.  Now it is dropped immediately.

According to my reading of the `Allocator` trait, if a copy of the allocator remains live, then its allocations must remain live.  Since the B-tree has a copy of the allocator that will only be dropped after the nodes, it's safe to not store the allocator in each node (which would be a much more intrusive change).

Fixes: rust-lang/rust#106203
2025-09-25 18:15:09 +02:00
Matthias Krüger
fea9196e52 Rollup merge of #146293 - BenjaminBrienen:try_remove, r=joboet
feat: non-panicking `Vec::try_remove`

`if index < my_vector.len() { Some(my_vector.remove(index)) } else { None }` is annoying to write and non-panicking functions are broadly useful.

APC: https://github.com/rust-lang/libs-team/issues/649

Tracking issue: https://github.com/rust-lang/rust/issues/146954
2025-09-25 18:15:09 +02:00
Matthias Krüger
e3f7626732 Rollup merge of #141032 - petrosagg:extract-if-ub, r=joboet
avoid violating `slice::from_raw_parts` safety contract in `Vec::extract_if`

The implementation of the `Vec::extract_if` iterator violates the safety contract adverized by `slice::from_raw_parts` by always constructing a mutable slice for the entire length of the vector even though that span of memory can contain holes from items already drained. The safety contract of `slice::from_raw_parts` requires that all elements must be properly
initialized.

As an example we can look at the following code:

```rust
let mut v = vec![Box::new(0u64), Box::new(1u64)];
for item in v.extract_if(.., |x| **x == 0) {
    drop(item);
}
```

In the second iteration a `&mut [Box<u64>]` slice of length 2 will be constructed. The first slot of the slice contains the bitpattern of an already deallocated box, which is invalid.

This fixes the issue by only creating references to valid items and using pointer manipulation for the rest. I have also taken the liberty to remove the big `unsafe` blocks in place of targetted ones with a SAFETY comment. The approach closely mirrors the implementation of `Vec::retain_mut`.

**Note to reviewers:** The diff is easier to follow with whitespace hidden.
2025-09-25 18:15:07 +02:00
bors
6f34f4ee07 Auto merge of #147019 - Zalathar:rollup-boxzbmo, r=Zalathar
Rollup of 14 pull requests

Successful merges:

 - rust-lang/rust#145067 (RawVecInner: add missing `unsafe` to unsafe fns)
 - rust-lang/rust#145277 (Do not materialise X in [X; 0] when X is unsizing a const)
 - rust-lang/rust#145973 (Add `std` support for `armv7a-vex-v5`)
 - rust-lang/rust#146667 (Add an attribute to check the number of lanes in a SIMD vector after monomorphization)
 - rust-lang/rust#146735 (unstably constify float mul_add methods)
 - rust-lang/rust#146737 (f16_f128: enable some more tests in Miri)
 - rust-lang/rust#146766 (Add attributes for #[global_allocator] functions)
 - rust-lang/rust#146905 (llvm: update remarks support on LLVM 22)
 - rust-lang/rust#146982 (Remove erroneous normalization step in `tests/run-make/linker-warning`)
 - rust-lang/rust#147005 (Small string formatting cleanup)
 - rust-lang/rust#147007 (Explicitly note `&[SocketAddr]` impl of `ToSocketAddrs`)
 - rust-lang/rust#147008 (bootstrap.py: Respect build.jobs while building bootstrap tool)
 - rust-lang/rust#147013 (rustdoc: Fix documentation for `--doctest-build-arg`)
 - rust-lang/rust#147015 (Use `LLVMDisposeTargetMachine`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-09-25 14:03:21 +00:00
Stuart Cook
2acd80cfa9 Rollup merge of #145067 - btj:patch-3, r=tgross35
RawVecInner: add missing `unsafe` to unsafe fns

Some (module-private) functions in `library/alloc/src/raw_vec/mod.rs` are unsafe (i.e. may cause UB when called from safe code) but are not marked `unsafe`. Specifically:
- `RawVecInner::grow_exact` causes UB if called with `len` and `additional` arguments such that `len + additional` is less than the current capacity. Indeed, in that case it calls [Allocator::grow](https://doc.rust-lang.org/std/alloc/trait.Allocator.html#method.grow) with a `new_layout` that is smaller than `old_layout`, which violates a safety precondition.
- The RawVecInner methods for resizing the buffer cause UB if called with an `elem_layout` different from the one used to initially allocate the buffer, because in that case `Allocator::grow` or `Allocator::shrink` are called with an `old_layout` that does not *fit* the allocated block, which violates a safety precondition.
- `RawVecInner::current_memory` might cause UB if called with an `elem_layout` different from the one used to initially allocate the buffer, because the `unchecked_mul` might overflow.
- Furthermore, these methods cause UB if called with an `elem_layout` where the size is not a multiple of the alignment. This is because `Layout::repeat` is used (in `layout_array`) to compute the allocation's layout when allocating, which includes padding to ensure alignment of array elements, but simple multiplication is used (in `current_memory`) to compute the old allocation's layout when resizing or deallocating, which would cause the layout used to resize or deallocate to not *fit* the allocated block, which violates a safety precondition.

I discovered these issues while performing formal verification of `library/alloc/src/raw_vec/mod.rs` per [Challenge 19](https://model-checking.github.io/verify-rust-std/challenges/0019-rawvec.html) of the [AWS Rust Standard Library Verification Contest](https://aws.amazon.com/blogs/opensource/verify-the-safety-of-the-rust-standard-library/).
2025-09-25 20:31:51 +10:00
Sidney Cammeresi
137d4eaf12 BTreeMap: Don't leak allocators when initializing nodes
Memory was allocated via `Box::leak` and thence intended to be tracked
and deallocated manually, but the allocator was also leaked, not
tracked, and never dropped.  Now it is dropped immediately.

According to my reading of the `Allocator` trait, if a copy of the
allocator remains live, then its allocations must remain live.  Since
the B-tree has a copy of the allocator that will only be dropped after
the nodes, it's safe to not store the allocator in each node (which
would be a much more intrusive change).
2025-09-24 18:08:32 -07:00
BenjaminBrienen
56734495e2 feature: Implement vec_try_remove
Vec::try_remove is a non-panicking version of Vec::remove
2025-09-24 15:29:09 +02:00
joboet
a875f7779e alloc: simplify Default for Box<CStr> and Rc<CStr> 2025-09-24 14:13:34 +02:00
bors
4056082360 Auto merge of #146317 - saethlin:panic=immediate-abort, r=nnethercote
Add panic=immediate-abort

MCP: https://github.com/rust-lang/compiler-team/issues/909

This adds a new panic strategy, `-Cpanic=immediate-abort`. This panic strategy essentially just codifies use of `-Zbuild-std-features=panic_immediate_abort`. This PR is intended to just set up infrastructure, and while it will change how the compiler is invoked for users of the feature, there should be no other impacts.

In many parts of the compiler, `PanicStrategy::ImmediateAbort` behaves just like `PanicStrategy::Abort`, because actually most parts of the compiler just mean to ask "can this unwind?" so I've added a helper function so we can say `sess.panic_strategy().unwinds()`.

The panic and unwind strategies have some level of compatibility, which mostly means that we can pre-compile the sysroot with unwinding panics then the sysroot can be linked with aborting panics later. The immediate-abort strategy is all-or-nothing, enforced by `compiler/rustc_metadata/src/dependency_format.rs` and this is tested for in `tests/ui/panic-runtime/`. We could _technically_ be more compatible with the other panic strategies, but immediately-aborting panics primarily exist for users who want to eliminate all the code size responsible for the panic runtime. I'm open to other use cases if people want to present them, but not right now. This PR is already large.

`-Cpanic=immediate-abort` sets both `cfg(panic = "immediate-abort")` _and_ `cfg(panic = "abort")`. bjorn3 pointed out that people may be checking for the abort cfg to ask if panics will unwind, and also the sysroot feature this is replacing used to require `-Cpanic=abort` so this seems like a good back-compat step. At least for the moment. Unclear if this is a good idea indefinitely. I can imagine this being confusing.

The changes to the standard library attributes are purely mechanical. Apart from that, I removed an `unsafe` we haven't needed for a while since the `abort` intrinsic became safe, and I've added a helpful diagnostic for people trying to use the old feature.

To test that `-Cpanic=immediate-abort` conflicts with other panic strategies, I've beefed up the core-stubs infrastructure a bit. There is now a separate attribute to set flags on it.

I've added a test that this produces the desired codegen, called `tests/run-make-cargo/panic-immediate-abort-codegen/` and also a separate run-make-cargo test that checks that we can build a binary.
2025-09-23 06:37:03 +00:00
Guillaume Gomez
9814d08545 Rollup merge of #146887 - taiki-e:rc-doc-feature, r=joboet
Remove unused #![feature(get_mut_unchecked)] in Rc and Arc examples

https://github.com/rust-lang/rust/pull/93109 removed the use of APIs enabled by this feature in these examples, but the `#![feature]` attributes ware not removed.
2025-09-22 17:17:46 +02:00
Taiki Endo
823337a4ad Remove unused #![feature(get_mut_unchecked)] in Rc and Arc examples 2025-09-22 22:15:25 +09:00
Petros Angelatos
e9b2c4f395 avoid violating slice::from_raw_parts safety contract in Vec::extract_if
The implementation of the `Vec::extract_if` iterator violates the safety
contract adverized by `slice::from_raw_parts` by always constructing a
mutable slice for the entire length of the vector even though that span
of memory can contain holes from items already drained. The safety
contract of `slice::from_raw_parts` requires that all elements must be
properly initialized.

As an example we can look at the following code:

```rust
let mut v = vec![Box::new(0u64), Box::new(1u64)];
for item in v.extract_if(.., |x| **x == 0) {
    drop(item);
}
```

In the second iteration a `&mut [Box<u64>]` slice of length 2 will be
constructed. The first slot of the slice contains the bitpattern of an
already deallocated box, which is invalid.

This fixes the issue by only creating references to valid items and
using pointer manipulation for the rest. I have also taken the liberty
to remove the big `unsafe` blocks in place of targetted ones with a
SAFETY comment. The approach closely mirrors the implementation of
`Vec::retain_mut`.

Signed-off-by: Petros Angelatos <petrosagg@gmail.com>
2025-09-22 10:59:52 +03:00
Ben Kimock
df58fd8cf7 Change the cfg to a dash 2025-09-21 13:12:20 -04:00
Ben Kimock
888679013d Add panic=immediate-abort 2025-09-21 13:12:18 -04:00
Marijn Schouten
2dfcd0948e btree InternalNode::new safety comments 2025-09-21 12:05:09 +00:00
Stuart Cook
be395723b5 Rollup merge of #146820 - cammeresi:alloc-20250919, r=tgross35
Add unstable attribute to BTreeMap-related allocator generics

Although these types aren't directly constructable externally, since they're pub, I think this omission was an oversight.

r? libs-api
2025-09-21 14:42:36 +10:00
Stuart Cook
7a5819d154 Rollup merge of #144091 - thaliaarchi:stabilize-new-zeroed, r=Mark-Simulacrum
Stabilize `new_zeroed_alloc`

The corresponding `new_uninit` and `new_uninit_slice` functions were stabilized in rust-lang/rust#129401, but the zeroed counterparts were left for later out of a [desire](https://github.com/rust-lang/rust/issues/63291#issuecomment-2161039756) to stabilize only the minimal set. These functions are straightforward mirrors of the uninit functions and well-established. Since no blockers or design questions have surfaced in the past year, I think it's time to stabilize them.

Tracking issue: rust-lang/rust#129396
2025-09-21 14:42:33 +10:00
tk
ac3c480388 docs: improve doc of some methods w/ ranges 2025-09-20 10:17:56 +00:00
bors
e4b521903b Auto merge of #146621 - cammeresi:peek-20250915, r=Amanieu
Make `PeekMut` generic over the allocator

- plumb in allocator generic
- additional testing

Related: rust-lang/rust#122742
2025-09-20 04:43:19 +00:00
Sidney Cammeresi
42b38e3781 Add unstable attribute to BTreeMap-related allocator generics
Although these types aren't directly constructable externally, since
they're pub, I think this omission was an oversight.
2025-09-19 21:32:15 -07:00
Marijn Schouten
e2de670558 btree: safety comments for init and new 2025-09-19 17:21:55 +00:00
Sidney Cammeresi
934ee043fe Plumb Allocator generic into std::vec::PeekMut 2025-09-18 17:29:23 -07:00
Alan Wu
b2b43b25a8 Add space after brace in Box<[T]>::new_uninit_slice example 2025-09-17 12:59:07 -04:00
Stuart Cook
feeb68eb5e Rollup merge of #144871 - Kivooeo:btree_entry_insert-stabilize, r=jhpratt
Stabilize `btree_entry_insert` feature

This stabilises `btree_map::VacantEntry::insert_entry` and `btree_map::Entry::insert_entry`, following the FCP in [tracking issue](https://github.com/rust-lang/rust/issues/65225).

New stable API:

```rust
impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> {
    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, A>;
}

impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> {
    pub fn insert_entry(mut self, value: V) -> OccupiedEntry<'a, K, V, A>;
}
```

(FCP ended almost a year ago, so if it's needed for process we could rerun it)

Closes: https://github.com/rust-lang/rust/issues/65225
2025-09-17 14:56:42 +10:00
Sidney Cammeresi
ce859d7713 Switch std::vec::PeekMut::pop from self to this parameter.
Since PeekMut implements Deref, it shouldn't have any methods of its
own.

See also: `std::collections::binary_heap::PeekMut::pop`
2025-09-14 08:16:05 -07:00
Jacob Pratt
5b37a1e4ae Rollup merge of #145471 - rs-sac:extr, r=the8472
Stabilize BTree{Map,Set}::extract_if

Tracking issue: rust-lang/rust#70530
FCP completed: https://github.com/rust-lang/rust/issues/70530#issuecomment-3191454465
Closes: rust-lang/rust#70530
2025-09-13 03:26:02 -04:00
Karl Meakin
a8c669461f optimization: Don't include ASCII characters in Unicode tables
The ASCII subset of Unicode is fixed and will never change, so we don't
need to generate tables for it with every new Unicode version. This
saves a few bytes of static data and speeds up `char::is_control` and
`char::is_grapheme_extended` on ASCII inputs.

Since the table lookup functions exported from the `unicode` module will
give nonsensical errors on ASCII input (and in fact will panic in debug
mode), I had to add some private wrapper methods to `char` which check
for ASCII-ness first.
2025-09-07 15:21:24 +02:00
Bart Jacobs
96f385b20a RawVecInner: add missing unsafe to unsafe fns
- RawVecInner::grow_exact causes UB if called with len and additional
  arguments such that len + additional is less than the current
  capacity.  Indeed, in that case it calls Allocator::grow with a
  new_layout that is smaller than old_layout, which violates a safety
  precondition.

- All RawVecInner methods for resizing the buffer cause UB
  if called with an elem_layout different from the one used to initially
  allocate the buffer, because in that case Allocator::grow/shrink is called with
  an old_layout that does not fit the allocated block, which violates a
  safety precondition.

- RawVecInner::current_memory might cause UB if called with an elem_layout
  different from the one used to initially allocate the buffer, because
  the unchecked_mul might overflow.

- Furthermore, these methods cause UB if called with an elem_layout
  where the size is not a multiple of the alignment. This is because
  Layout::repeat is used (in layout_array) to compute the allocation's
  layout when allocating, which includes padding to ensure alignment of
  array elements, but simple multiplication is used (in current_memory) to
  compute the old allocation's layout when resizing or deallocating, which
  would cause the layout used to resize or deallocate to not fit the
  allocated block, which violates a safety precondition.
2025-09-05 10:21:21 +02:00
Stuart Cook
d71a9b6bcf Rollup merge of #145750 - btj:drop-alloc-guard, r=tgross35
raw_vec.rs: Remove superfluous fn alloc_guard

`alloc_guard` checks that its argument is at most `isize::MAX`, but it is called only with layout sizes, which are already guaranteed to be at most `isize::MAX`.
2025-09-04 10:01:53 +10:00
Stuart Cook
f4b946a147 Rollup merge of #145279 - clarfonthey:const-convert-initial, r=tgross35
Constify conversion traits (part 1)

This is the first part of rust-lang/rust#144289 being split into smaller pieces. It adds/moves constness of several traits under the `const_convert` feature:

* `From`
* `Into`
* `TryFrom`
* `TryInto`
* `FromStr`
* `AsRef`
* `AsMut`
* `Borrow`
* `BorrowMut`
* `Deref`
* `DerefMut`

There are a few methods that are intrinsically tied to these traits which I've included in the feature. Particularly, those which are wrappers over `AsRef`:

* `ByteStr::new` (unstable under `bstr` feature)
* `OsStr::new`
* `Path::new`

Those which directly use `Into`:

* `Result::into_ok`
* `Result::into_err`

And those which use `Deref` and `DerefMut`:

* `Pin::as_ref`
* `Pin::as_mut`
* `Pin::as_deref_mut`
* `Option::as_deref`
* `Option::as_deref_mut`
* `Result::as_deref`
* `Result::as_deref_mut`

(note: the `Option` and `Result` methods were suggested by ``@npmccallum`` initially as rust-lang/rust#146101)

The parts which are missing from this PR are:

* Anything that involves heap-allocated types
* Making any method const than the ones listed above
* Anything that could rely on the above, *or* could rely on system-specific code for `OsStr` or `Path` (note: this mostly makes these methods useless since `str` doesn't implement `AsRef<OsStr>` yet, but it's better to track the method for now and add impls later, IMHO)

r? ``@tgross35`` (who mostly already reviewed this)
2025-09-03 23:08:06 +10:00
Bart Jacobs
d9dc20c752 raw_vec.rs: Remove superfluous fn alloc_guard
It checks that its argument is at most isize::MAX, but it is called
only with layout sizes, which are already guaranteed to be at most
isize::MAX.
2025-09-03 07:34:32 +02:00
ltdk
1c64d3e6d1 Constify conversion traits 2025-09-01 21:38:26 -04:00
Matthias Krüger
e5f96e3b43 Rollup merge of #145592 - nilotpal-n7:fix-format-alignment, r=lcnr
Fix format string grammar in docs and improve alignment error message for #144023

This PR improves error messages and documentation for format strings involving alignment and formatting traits.

Highlights:

- Clearer error messages for invalid alignment specifiers (e.g., `{0:#X>18}`), showing the expected `<`, `^`, or `>` and a working example:

    println!("{0:>#18X}", value);

- Updated UI test `format-alignment-hash.rs` to reflect the improved error output.
- Documentation clarification: ensures examples correctly show how width, alignment, and traits like `x`, `X`, `#` combine.

Motivation:
Previously, using `#` with alignment and width produced confusing errors. This PR guides users on the correct syntax and provides actionable examples.

Testing:
- Built the compiler (`./x build`)
- Blessed and ran UI tests (`./x. test src/test/ui/fmt/format-alignment-hash.rs --bless`)
- Verified full test suite passes (`./x test`)

Issue: rust-lang/rust#144023
2025-08-31 13:40:35 +02:00
Sidney Cammeresi
f8a7f82bda Stabilize BTree{Map,Set}::extract_if 2025-08-27 11:34:31 -07:00
Nilotpal Gupta
fdbaaac245 Fix format string grammar in docs and improve alignment error message 2025-08-27 20:45:41 +05:30