Commit Graph

8076 Commits

Author SHA1 Message Date
Matthias Krüger
695da5b782
Rollup merge of #133964 - joboet:select_unpredictable, r=tgross35
core: implement `bool::select_unpredictable`

Tracking issue: #133962
ACP: https://github.com/rust-lang/libs-team/issues/468
2025-01-04 09:54:36 +01:00
Matthias Krüger
fac31a1398
Rollup merge of #134985 - mgsloan:remove-unnecessary-qualification-in-Ord-trait-docs, r=Noratrieb
Remove qualification of `std::cmp::Ordering` in `Ord` doc
2025-01-01 22:04:17 +01:00
bors
eeeff9a66c Auto merge of #134969 - Marcondiro:master, r=jhpratt,programmerjake
char to_digit: avoid unnecessary casts to u64

Hello,
in the `char::to_digit` method there are a few `as u64` casts that are not strictly necessary.
I assume that the reason behind these casts is to avoid possible overflows in the `+ 10` add.

This PR removes the aforementioned casts, avoiding the overflow issue by slightly modifying the ASCII letter to int mapping.

Thanks,
Happy new year.
2025-01-01 10:54:12 +00:00
Michael Sloan
cdd55bfda2 Remove qualification of std::cmp::Ordering in Ord doc 2024-12-31 14:29:03 -07:00
bors
d117b7f211 Auto merge of #132195 - clarfonthey:bigint-mul, r=scottmcm
Tidy up bigint multiplication methods

This tidies up the library version of the bigint multiplication methods after the addition of the intrinsics in #133663. It follows [this summary](https://github.com/rust-lang/rust/issues/85532#issuecomment-2403442775) of what's desired for these methods.

Note that, if `2H = N`, then `uH::MAX * uH::MAX + uH::MAX + uH::MAX` is `uN::MAX`, and that we can effectively add two "carry" values without overflowing.

For ease of terminology, the "low-order" or "least significant" or "wrapping" half of multiplication will be called the low part, and the "high-order" or "most significant" or "overflowing" half of multiplication will be called the high part. In all cases, the return convention is `(low, high)` and left unchanged by this PR, to be litigated later.

## API Changes

The original API:

```rust
impl uN {
    // computes self * rhs
    pub const fn widening_mul(self, rhs: uN) -> (uN, uN);

    // computes self * rhs + carry
    pub const fn carrying_mul(self, rhs: uN, carry: uN) -> (uN, uN);
}
```

The added API:

```rust
impl uN {
    // computes self * rhs + carry1 + carry2
    pub const fn carrying2_mul(self, rhs: uN, carry: uN, add: uN) -> (uN, uN);
}
impl iN {
    // note that the low part is unsigned
    pub const fn widening_mul(self, rhs: iN) -> (uN, iN);
    pub const fn carrying_mul(self, rhs: iN, carry: iN) -> (uN, iN);
    pub const fn carrying_mul_add(self, rhs: iN, carry: iN, add: iN) -> (uN, iN);
}
```

Additionally, a naive implementation has been added for `u128` and `i128` since there are no double-wide types for those. Eventually, an intrinsic will be added to make these more efficient, but rather than doing this all at once, the library changes are added first.

## Justifications for API

The unsigned parts are done to ensure consistency with overflowing addition: for a two's complement integer, you want to have unsigned overflow semantics for all parts of the integer except the highest one. This is because overflow for unsigned integers happens on the highest bit (from `MAX` to zero), whereas overflow for signed integers happens on the second highest bit (from `MAX` to `MIN`). Since the sign information only matters in the highest part, we use unsigned overflow for everything but that part.

There is still discussion on the merits of signed bigint *addition* methods, since getting the behaviour right is very subtle, but at least for signed bigint *multiplication*, the sign of the operands does make a difference. So, it feels appropriate that at least until we've nailed down the final API, there should be an option to do signed versions of these methods.

Additionally, while it's unclear whether we need all three versions of bigint multiplication (widening, carrying-1, and carrying-2), since it's possible to have up to two carries without overflow, there should at least be a method to allow that. We could potentially only offer the carry-2 method and expect that adding zero carries afterword will optimise correctly, but again, this can be litigated before stabilisation.

## Note on documentation

While a lot of care was put into the documentation for the `widening_mul` and `carrying_mul` methods on unsigned integers, I have not taken this same care for `carrying_mul_add` or the signed versions. While I have updated the doc tests to be more appropriate, there will likely be many documentation changes done before stabilisation.

## Note on tests

Alongside this change, I've added several tests to ensure that these methods work as expected. These are alongside the codegen tests for the intrinsics.
2024-12-31 18:49:36 +00:00
Marcondiro
aa685bccca
char to_digit: avoid unnecessary casts to u64 2024-12-31 16:17:10 +01:00
Matthias Krüger
852440ba5f
Rollup merge of #134953 - DiuDiu777:unaligned-doc, r=RalfJung
Fix doc for read&write unaligned in zst operation

### PR Description
This PR addresses an inconsistency in the Rust documentation regarding `read_unaligned ` and `write_unaligned` on zero-sized types (ZSTs). The current documentation for [pointer validity](https://doc.rust-lang.org/nightly/std/ptr/index.html#safety) states that for zero-sized types (ZSTs), null pointers are valid:
> For zero-sized types (ZSTs), every pointer is valid, including the null pointer.

However, there is an inconsistency in the documentation for the unaligned read operation in the function [ptr::read_unaligned](https://doc.rust-lang.org/nightly/std/ptr/fn.read_unaligned.html)(as well as `write_unaligned`), which states:
> Note that even if T has size 0, the pointer must be non-null.

This change is also supported by [PR #134912](https://github.com/rust-lang/rust/pull/134912)
> the _unaligned method docs should be fixed.
2024-12-31 14:30:43 +01:00
Stuart Cook
fa6990c16e
Rollup merge of #134930 - RalfJung:ptr-docs-valid-access, r=jhpratt
ptr docs: make it clear that we are talking only about memory accesses

This should make it harder to take this sentence out of context and misunderstand it.
2024-12-31 14:12:46 +11:00
Stuart Cook
1200d3d733
Rollup merge of #134927 - DaniPopes:const-as_flattened_mut, r=scottmcm
Make slice::as_flattened_mut unstably const

Tracking issue: https://github.com/rust-lang/rust/issues/95629

Unblocked by const_mut_refs being stabilized: https://github.com/rust-lang/rust/pull/129195
2024-12-31 14:12:46 +11:00
LemonJ
d9ef419c90 fix doc for read write unaligned in zst operation 2024-12-31 10:59:13 +08:00
bors
4e5fec2f1e Auto merge of #134757 - RalfJung:const_swap, r=scottmcm
stabilize const_swap

libs-api FCP passed in https://github.com/rust-lang/rust/issues/83163.

However, I only just realized that this actually involves an intrinsic. The intrinsic could be implemented entirely with existing stable const functionality, but we choose to make it a primitive to be able to detect more UB. So nominating for `@rust-lang/lang`  to make sure they are aware; I leave it up to them whether they want to FCP this.

While at it I also renamed the intrinsic to make the "nonoverlapping" constraint more clear.

Fixes #83163
2024-12-30 23:46:42 +00:00
Ralf Jung
e36b4c95f4 ptr docs: make it clear that we are talking only about memory accesses 2024-12-30 19:28:03 +01:00
DaniPopes
26f523edfc
Make slice::as_flattened_mut unstably const
Tracking issue: https://github.com/rust-lang/rust/issues/95629

Unblocked by const_mut_refs being stabilized: https://github.com/rust-lang/rust/pull/129195
2024-12-30 18:16:49 +01:00
Geoffrey Thomas
0c2f4359fd
Fix sentence fragment in pin module docs
Looks like this was inadvertently dropped in 8241ca60. Restore the words from before that commit.
2024-12-28 22:21:04 -05:00
ltdk
f228458e30 Tidy up bigint mul methods 2024-12-27 22:01:51 -05:00
David Tolnay
9aebd28ca7
Rollup merge of #134823 - chloefeal:fix, r=tgross35,dtolnay
Fix typos

This PR focuses on correcting typos and improving clarity in documentation files. Thank you.
2024-12-27 18:43:03 -08:00
Matthias Krüger
95e66ff8b4
Rollup merge of #133663 - scottmcm:carrying_mul_add, r=Amanieu
Add a compiler intrinsic to back `bigint_helper_methods`

cc https://github.com/rust-lang/rust/issues/85532

This adds a new `carrying_mul_add` intrinsic, to implement `wide_mul` and `carrying_mul`.

It has fallback MIR for all types -- including `u128`, which isn't currently supported on nightly -- so that it'll continue to work on all backends, including CTFE.

Then it's overridden in `cg_llvm` to use wider intermediate types, including `i256` for `u128::carrying_mul`.
2024-12-27 19:47:09 +01:00
Scott McMurray
4669c0d756 Override carrying_mul_add in cg_llvm 2024-12-27 08:17:40 -08:00
Scott McMurray
2c0c9123fc Move {widening, carrying}_mul to an intrinsic with fallback MIR
Including implementing it for `u128`, so it can be defined in `uint_impl!`.

This way it works for all backends, including CTFE.
2024-12-27 08:17:40 -08:00
chloefeal
e1b65be417
Fix typos
Signed-off-by: chloefeal <188809157+chloefeal@users.noreply.github.com>
2024-12-27 21:35:57 +08:00
许杰友 Jieyou Xu (Joe)
b9df376189
Rollup merge of #134606 - RalfJung:ptr-copy-docs, r=Mark-Simulacrum
ptr::copy: fix docs for the overlapping case

Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/549

As discussed in that issue, it doesn't make any sense for `copy` to read a byte via `src` after it was already written via `dst`. The entire point of this method is that is copies correctly even if they overlap, and that requires always reading any given location before writing it.

Cc `@rust-lang/opsem`
2024-12-27 20:44:11 +08:00
Jacob Pratt
c1447e3449
Rollup merge of #134791 - notriddle:notriddle/inline-ffi-error-types, r=tgross35
docs: inline `std::ffi::c_str` types to `std::ffi`

Rustdoc has no way to show that an item is stable, but only at a different path. `std::ffi::c_str::NulError` is not stable, but `std::ffi::NulError` is.

To avoid marking these types as unstable when someone just wants to follow a link from `CString`, inline them into their stable paths.

Fixes #134702

r? `@tgross35`
2024-12-26 21:56:51 -05:00
Jacob Pratt
0bfd367612
Rollup merge of #134782 - wtlin1228:docs/iter-rposition, r=Mark-Simulacrum
Update Code Example for `Iterator::rposition`

Added an additional assertion to the example to show the behavior of `iter.next_back` after using `iter.rposition`.
2024-12-26 21:56:50 -05:00
Michael Howell
fc8a541eaa docs: inline core::ffi::c_str types to core::ffi 2024-12-26 15:51:45 -07:00
Sebastian Hahn
10b23518c1 Impl FromIterator for tuples with arity 1-12 2024-12-26 08:47:49 +01:00
Sebastian Hahn
87e641a2a5 Fix formatting 2024-12-26 08:47:49 +01:00
wtlin1228
d0c1975e4b docs: update code example for Iterator#rposition 2024-12-26 13:56:45 +08:00
Ralf Jung
88b88f336b stabilize const_alloc_layout 2024-12-25 19:28:52 +01:00
Ralf Jung
7291b1eaf7 rename typed_swap → typed_swap_nonoverlapping 2024-12-25 10:53:03 +01:00
Ralf Jung
6de3a2e3a9 stabilize const_swap 2024-12-25 10:36:32 +01:00
oliveredget
be1d5dd494
chore: fix typos 2024-12-24 23:37:30 +08:00
Stuart Cook
bbd30b5476
Rollup merge of #134689 - RalfJung:ptr-swap-test, r=oli-obk
core: fix const ptr::swap_nonoverlapping when there are pointers at odd offsets

Ensure that the pointer gets swapped correctly even if it is not stored at an aligned offset. This rules out implementations that copy things in a `usize` loop -- so our implementation needs to be adjusted to avoid such a loop when running in const context.

Part of https://github.com/rust-lang/rust/issues/133668
2024-12-24 14:05:22 +11:00
Stuart Cook
0c93b279ea
Rollup merge of #134662 - ionicmc-rs:any-safety-docs, r=Amanieu
Fix safety docs for `dyn Any + Send {+ Sync}`

Fixes the `# Safety` docs for `dyn Any + Send`'s `downcast_{mut/ref}_unchecked` to show the direct instructions , where previously the would tell the user to find the docs on `dyn Any` themselves.

This also adds them for `downcast_{mut/ref}_unchecked` on `dyn Any + Send + Sync`
2024-12-24 14:05:22 +11:00
Ralf Jung
af1c8da172 core: fix const ptr::swap_nonoverlapping when there are pointers at odd offsets in the type 2024-12-23 16:24:45 +01:00
Matthias Krüger
95c33e303b
Rollup merge of #134363 - estebank:derive-default, r=SparrowLii
Use `#[derive(Default)]` instead of manual `impl` when possible

While working on #134175 I noticed a few manual `Default` `impl`s that could be `derive`d instead. These likely predate the existence of the `#[default]` attribute for `enum`s.
2024-12-23 14:44:20 +01:00
Trevor Gross
8fc4ba2ac1
Rollup merge of #134672 - Zalathar:revert-coverage-attr, r=wesleywiser
Revert stabilization of the `#[coverage(..)]` attribute

Due to a process mixup, the PR to stabilize the `#[coverage(..)]` attribute (#130766) was merged while there are still outstanding concerns. The default action in that situation is to revert, and the feature is not sufficiently urgent or uncontroversial to justify special treatment, so this PR reverts that stabilization.

---

- A key point that came up in offline discussions is that unlike most user-facing features, this one never had a proper RFC, so parts of the normal stabilization process that implicitly rely on an RFC break down in this case.
- As the implementor and de-facto owner of the feature in its current form, I would like to think that I made good choices in designing and implementing it, but I don't feel comfortable proceeding to stabilization without further scrutiny.
- There hasn't been a clear opportunity for T-compiler to weigh in or express concerns prior to stabilization.
- The stabilization PR cites a T-lang FCP that occurred in the tracking issue, but due to the messy design and implementation history (and lack of a clear RFC), it's unclear what that FCP approval actually represents in this case.
  - At the very least, we should not proceed without a clear statement from T-lang or the relevant members about the team's stance on this feature, especially in light of the other concerns listed here.
- The existing user-facing documentation doesn't clearly reflect which parts of the feature are stable commitments, and which parts are subject to change. And there doesn't appear to be a clear consensus anywhere about where that line is actually drawn, or whether the chosen boundary is acceptable to the relevant teams and individuals.
  - For example, the [stabilization report comment](https://github.com/rust-lang/rust/issues/84605#issuecomment-2166514660) mentions that some aspects are subject to change, but that text isn't consistent with my earlier comments, and there doesn't appear to have been any explicit discussion or approval process.
  - [The current reference text](https://github.com/rust-lang/reference/blob/4dfaa4f/src/attributes/coverage-instrumentation.md) doesn't mention this distinction at all, and instead simply describes the current implementation behaviour.
- When the implementation was changed to its current form, the associated user-facing error messages were not updated, so they still refer to the attribute only being allowed on functions and closures.
  - On its own, this might have been reasonable to fix-forward in the absence of other concerns, but the fact that it never came up earlier highlights the breakdown in process that has occurred here.

---

Apologies to everyone who was excited for this stabilization to land, but unfortunately it simply isn't ready yet.
2024-12-23 02:07:32 -05:00
Esteban Küber
1f82b45b6a Use #[derive(Default)] instead of manually implementing it 2024-12-23 03:01:29 +00:00
Zalathar
87c2f9a5be Revert "Auto merge of #130766 - clarfonthey:stable-coverage-attribute, r=wesleywiser"
This reverts commit 1d35638dc3, reversing
changes made to f23a80a4c2.
2024-12-23 12:30:37 +11:00
bors
908af5ba4a Auto merge of #134666 - matthiaskrgr:rollup-whe0chp, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #130289 (docs: Permissions.readonly() also ignores root user special permissions)
 - #134583 (docs: `transmute<&mut T, &mut MaybeUninit<T>>` is unsound when exposed to safe code)
 - #134611 (Align `{i686,x86_64}-win7-windows-msvc` to their parent targets)
 - #134629 (compiletest: Allow using a specific debugger when running debuginfo tests)
 - #134642 (Implement `PointerLike` for `isize`, `NonNull`, `Cell`, `UnsafeCell`, and `SyncUnsafeCell`.)
 - #134660 (Fix spacing of markdown code block fences in compiler rustdoc)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-23 01:18:40 +00:00
Matthias Krüger
c16f00cff6
Rollup merge of #134642 - kpreid:pointerlike-cell, r=compiler-errors
Implement `PointerLike` for `isize`, `NonNull`, `Cell`, `UnsafeCell`, and `SyncUnsafeCell`.

* Implementing `PointerLike` for `UnsafeCell` enables the possibility of interior mutable `dyn*` values. Since this means potentially exercising new codegen behavior, I added a test for it in `tests/ui/dyn-star/cell.rs`. Please let me know if there are further sorts of tests that should be written, or other care that should be taken with this change.

  It is unfortunately not possible without compiler changes to implement `PointerLike` for `Atomic*` types, since they are not `repr(transparent)` (and, in theory if not in practice, `AtomicUsize`'s alignment may be greater than that of an ordinary pointer or `usize`).

* Implementing `PointerLike` for `NonNull` is useful for pointer types which wrap `NonNull`.

* Implementing `PointerLike` for `isize` is just for completeness; I have no use cases in mind, but I cannot think of any reason not to do this.

* Tracking issue: #102425

`@rustbot` label +F-dyn_star
(there is no label or tracking issue for F-pointer_like_trait)
2024-12-22 21:59:27 +01:00
Matthias Krüger
6ade237b6c
Rollup merge of #134583 - Enselic:maybe-uninit-transmute, r=workingjubilee
docs: `transmute<&mut T, &mut MaybeUninit<T>>` is unsound when exposed to safe code

Closes #66699

On my system (Edit: And also in the [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=90529e2a9900599cb759e4bfaa5b5efe)) the example program terminates with an unpredictable exit code:
```console
$ cargo +nightly build && target/debug/bin ; echo $?
255
$ cargo +nightly build && target/debug/bin ; echo $?
253
```

And miri considers the code to have undefined behavior:
```console
$ cargo +nightly miri run
error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory
  --> src/main.rs:12:24
   |
12 |     std::process::exit(*code); // UB! Accessing uninitialized memory
   |                        ^^^^^ using uninitialized data, but this operation requires initialized memory
   |
error: aborting due to 1 previous error
```
2024-12-22 21:59:24 +01:00
Mostafa Khaled
5a8d970e4f Fixes safety docs for dyn Any + Send {+ Sync} 2024-12-22 21:38:23 +02:00
Kevin Reid
5c04151c6c Implement PointerLike for isize, NonNull, Cell, UnsafeCell, and SyncUnsafeCell.
Implementing `PointerLike` for `UnsafeCell` enables the possibility of
interior mutable `dyn*` values. Since this means potentially exercising
new codegen behavior, I added a test for it in `tests/ui/dyn-star/cell.rs`.

Also updated UI tests to account for the `isize` implementation changing
error messages.
2024-12-22 11:18:56 -08:00
bors
e108481f74 Auto merge of #134330 - scottmcm:no-more-rvalue-len, r=matthewjasper
Delete `Rvalue::Len` 🎉

Everything's moved to `PtrMetadata`, so we can get rid of the `Len` variant now.

~~Depends on #134326, so draft until that lands~~ Ready!

r? mir
2024-12-22 18:49:18 +00:00
bors
303e8bd768 Auto merge of #131193 - EFanZh:asserts-vec-len, r=the8472
Asserts the maximum value that can be returned from `Vec::len`

Currently, casting `Vec<i32>` to `Vec<u32>` takes O(1) time:

```rust
// See <https://godbolt.org/z/hxq3hnYKG> for assembly output.
pub fn cast(vec: Vec<i32>) -> Vec<u32> {
    vec.into_iter().map(|e| e as _).collect()
}
```

But the generated assembly is not the same as the identity function, which prevents us from casting `Vec<Vec<i32>>` to `Vec<Vec<u32>>` within O(1) time:

```rust
// See <https://godbolt.org/z/7n48bxd9f> for assembly output.
pub fn cast(vec: Vec<Vec<i32>>) -> Vec<Vec<u32>> {
    vec.into_iter()
        .map(|e| e.into_iter().map(|e| e as _).collect())
        .collect()
}
```

This change tries to fix the problem. You can see the comparison here: <https://godbolt.org/z/jdManrKvx>.
2024-12-22 16:09:16 +00:00
Scott McMurray
5ba54c9e31 Delete Rvalue::Len
Everything's moved to `PtrMetadata` instead.
2024-12-22 06:12:39 -08:00
Martin Nordholts
2305012e6a docs: transmute<&mut T, &mut MaybeUninit<T>> is unsound when exposed to safe code
In the playground the example program terminates with an unpredictable exit
code. The undefined behavior is also detected by miri:

    error: Undefined Behavior: using uninitialized data
2024-12-22 14:21:10 +01:00
Matthias Krüger
7f36ae400c
Rollup merge of #134602 - kpreid:pointerlike-doc, r=tgross35
Document `PointerLike` implementation restrictions.

Since <https://github.com/rust-lang/rust/pull/133226>, it is no longer automatically implemented, but must be manually implemented, with special restrictions. The documentation now (roughly) explains those special restrictions.

cc `@compiler-errors` (author of the previous PR)
2024-12-22 09:12:11 +01:00
bors
a2bcfae5c5 Auto merge of #134640 - matthiaskrgr:rollup-xlstm3o, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #134364 (Use E0665 for missing `#[default]` on enum and update doc)
 - #134601 (Support pretty-printing `dyn*` trait objects)
 - #134603 (Explain why a type is not eligible for `impl PointerLike`.)
 - #134618 (coroutine_clone: add comments)
 - #134630 (Use `&raw` for `ptr` primitive docs)
 - #134637 (Flatten effects directory now that it doesn't really test anything specific)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-22 05:29:45 +00:00
Matthias Krüger
9b4e40dcb8
Rollup merge of #134630 - fifty-six:master, r=workingjubilee
Use `&raw` for `ptr` primitive docs

Fixes the first item in #133024
2024-12-22 03:49:45 +01:00