Commit Graph

8223 Commits

Author SHA1 Message Date
Trevor Gross
366cecacdd Stabilize float_next_up_down
FCP completed at [1].

Closes https://github.com/rust-lang/rust/issues/91399

[1]: https://github.com/rust-lang/rust/issues/91399#issuecomment-2598734570
2025-01-17 23:01:10 +00:00
Matthias Krüger
fca148185e
Rollup merge of #133720 - c410-f3r:cfg-match-foo-bar-baz, r=joshtriplett
[cfg_match] Adjust syntax

A year has passed since the creation of #115585 and the feature, as expected, is not moving forward. Let's change that.

This PR proposes changing the arm's syntax from  `cfg(SOME_CONDITION) => { ... }` to `SOME_CODITION => {}`.

```rust
match_cfg! {
   unix => {
        fn foo() { /* unix specific functionality */ }
    }
    target_pointer_width = "32" => {
        fn foo() { /* non-unix, 32-bit functionality */ }
    }
    _ => {
        fn foo() { /* fallback implementation */ }
    }
}
```

Why? Because after several manual migrations in https://github.com/rust-lang/rust/pull/116342 it became clear,  at least for me, that `cfg` prefixes are unnecessary, verbose and redundant.

Again, everything is just a proposal to move things forward. If the shown syntax isn't ideal, feel free to close this PR or suggest other alternatives.
2025-01-16 17:00:44 +01:00
Scott McMurray
c18718c9c2 Less unsafe in dangling/without_provenance 2025-01-15 22:17:57 -08:00
bors
6fc8a27931 Auto merge of #135555 - matthiaskrgr:rollup-jnqdbuu, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #135497 (fix typo in typenames of pin documentation)
 - #135522 (add incremental test for issue 135514)
 - #135523 (const traits: remove some known-bug that do not seem to make sense)
 - #135535 (Add GUI test for #135499)
 - #135541 (Methods of const traits are const)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-15 22:22:48 +00:00
Matthias Krüger
85d2b2af15
Rollup merge of #135497 - DJMrTV:master, r=jhpratt
fix typo in typenames of pin documentation

I noticed this whilst reading the documentation for pin.

Basically there was just one to many closing angle brackets on the type parameters in the documentation where instead of being `Pin<&mut T>` it was `Pin<&mut T>>`
2025-01-15 22:06:11 +01:00
Jiri Bobek
c656f879c9 Export likely(), unlikely() and cold_path() in std::hint 2025-01-15 21:42:47 +01:00
DJMrTV
b535a1dd65 fix typo in typenames of pin documentation 2025-01-15 19:18:17 +01:00
Guillaume Gomez
369d135733
Rollup merge of #135003 - RalfJung:deprecate-allowed-through-unstable, r=davidtwco
deprecate `std::intrinsics::transmute` etc, use `std::mem::*` instead

The `rustc_allowed_through_unstable_modules` attribute lets users call `std::mem::transmute` as `std::intrinsics::transmute`. The former is a reexport of the latter, and for a long time we didn't properly check stability for reexports, so making this a hard error now would be a breaking change for little gain. But at the same time, `std::intrinsics::transmute` is not the intended path for this function, so I think it is a good idea to show a deprecation warning when that path is used. This PR implements that, for all the functions in `std::intrinsics` that carry the attribute.

I assume this will need ``@rust-lang/libs-api`` FCP.
2025-01-15 16:30:11 +01:00
bors
2776bdfe42 Auto merge of #135525 - jhpratt:rollup-4gu2wpm, r=jhpratt
Rollup of 7 pull requests

Successful merges:

 - #132397 (Make missing_abi lint warn-by-default.)
 - #133807 (ci: Enable opt-dist for dist-aarch64-linux builds)
 - #134143 (Convert `struct FromBytesWithNulError` into enum)
 - #134338 (Use a C-safe return type for `__rust_[ui]128_*` overflowing intrinsics)
 - #134678 (Update `ReadDir::next` in `std::sys::pal::unix::fs` to use `&raw const (*p).field` instead of `p.byte_offset().cast()`)
 - #135424 (Detect unstable lint docs that dont enable their feature)
 - #135520 (Make sure we actually use the right trivial lifetime substs when eagerly monomorphizing drop for ADTs)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-15 09:20:25 +00:00
Jacob Pratt
229c91bc31
Rollup merge of #134143 - nyurik:err-nul, r=dtolnay
Convert `struct FromBytesWithNulError` into enum

This PR renames the former `kind` enum from `FromBytesWithNulErrorKind` to `FromBytesWithNulError`, and removes the original struct.

See https://github.com/rust-lang/libs-team/issues/493

## Possible Changes - TBD
* [x] should the new `enum FromBytesWithNulError` derive `Copy`?
* [ ] should there be any new/changed attributes?
* [x] add some more tests

## Problem

One of `CStr` constructors, `CStr::from_bytes_with_nul(bytes: &[u8])` handles 3 cases:
1. `bytes` has one NULL as the last value - creates CStr
2. `bytes` has no NULL - error
3. `bytes` has a NULL in some other position - error

The 3rd case is error that may require lossy conversion, but the 2nd case can easily be handled by the user code. Unfortunately, this function returns an opaque `FromBytesWithNulError` error in both 2nd and 3rd case, so the user cannot detect just the 2nd case - having to re-implement the entire function and bring in the `memchr` dependency.

## Motivating examples or use cases

In [this code](f86d7a8768/varnish-sys/src/vcl/ws.rs (L158)), my FFI code needs to copy user's `&[u8]` into a C-allocated memory blob in a NUL-terminated `CStr` format.  My code must first validate if `&[u8]` has a trailing NUL (case 1), no NUL (adds one on the fly - case 2), or NUL in the middle (3rd case - error). I had to re-implement `from_bytes_with_nul` and add `memchr`dependency just to handle the 2nd case.

r? `@Amanieu`
2025-01-15 04:08:11 -05:00
Ralf Jung
f1c95c9000 intrinsics: deprecate calling them via the unstable std::intrinsics path 2025-01-15 09:41:33 +01:00
Michael Goulet
2743df848b Enforce syntactical stability of const traits in HIR 2025-01-14 19:12:08 +00:00
Ralf Jung
5c2006b79a remove pointless allowed_through_unstable_modules on TryFromSliceError 2025-01-14 16:54:28 +01:00
Ralf Jung
9ac62f972f remove Rustc{En,De}codable from library and compiler 2025-01-14 16:16:38 +01:00
Ralf Jung
4df78a07e5 make rustc_encodable_decodable feature properly unstable 2025-01-14 16:16:38 +01:00
bors
48a426eca9 Auto merge of #135384 - saethlin:inline-copy-from-slice, r=joboet
Add #[inline] to copy_from_slice

I'm doing cooked things to CGU partitioning for compiler-builtins (https://github.com/rust-lang/rust/pull/135395) and this was the lone symbol in my compiler-builtins rlib that wasn't an intrinsic. Adding `#[inline]` makes it go away.

Perf report indicates a marginal but chaotic effect on compile time, marginal improvement in codegen. As expected.
2025-01-12 20:16:25 +00:00
Josh Triplett
22a4ec39fb Omit some more From impls to avoid inference failures 2025-01-12 12:27:24 +02:00
ltdk
e37daf0c86 Add inherent versions of MaybeUninit methods for slices 2025-01-11 23:57:00 -05:00
Ben Kimock
cda566e226 Add #[inline] to copy_from_slice 2025-01-11 18:00:44 -05:00
bors
12445e0b2c Auto merge of #135360 - RalfJung:structural-partial-eq, r=compiler-errors
update and clarify StructuralPartialEq docs

This apparently hasn't been updated when we finalized the current const pattern matching behavior.

Fixes https://github.com/rust-lang/rust/issues/92454 by providing rationale and context in the docs linked from that error message.
2025-01-11 21:46:43 +00:00
Ralf Jung
41857a3d42 update and clarify StructuralPartialEq docs 2025-01-11 11:00:41 +01:00
Yuri Astrakhan
86b86fa8fb Rename pos to position 2025-01-11 02:56:58 -05:00
Yuri Astrakhan
2f5a3d4b06 Convert struct FromBytesWithNulError into enum
One of `CStr` constructors, `CStr::from_bytes_with_nul(bytes: &[u8])` handles 3 cases:
1. `bytes` has one NULL as the last value - creates CStr
2. `bytes` has no NULL - error
3. `bytes` has a NULL in some other position - error

The 3rd case is error that may require lossy conversion, but the 2nd case can easily be handled by the user code. Unfortunately, this function returns an opaque `FromBytesWithNulError` error in both 2nd and 3rd case, so the user cannot detect just the 2nd case - having to re-implement the entire function and bring in the `memchr` dependency.

In [this code](f86d7a8768/varnish-sys/src/vcl/ws.rs (L158)), my FFI code needs to copy user's `&[u8]` into a C-allocated memory blob in a NUL-terminated `CStr` format.  My code must first validate if `&[u8]` has a trailing NUL (case 1), no NUL (adds one on the fly - case 2), or NUL in the middle (3rd case - error). I had to re-implement `from_bytes_with_nul` and add `memchr`dependency just to handle the 2nd case.

This PR renames the former `kind` enum from `FromBytesWithNulErrorKind` to `FromBytesWithNulError`, and removes the original struct.
2025-01-11 02:47:55 -05:00
Jacob Pratt
46222ce6f8
Rollup merge of #135347 - samueltardieu:push-qvyxtxsqyxyr, r=jhpratt
Use `NonNull::without_provenance` within the standard library

This API removes the need for several `unsafe` blocks, and leads to clearer code. It uses feature `nonnull_provenance` (#135243).

Close #135343
2025-01-11 01:55:09 -05:00
Jacob Pratt
351e6188a8
Rollup merge of #135236 - scottmcm:more-mcp807-library-updates, r=ChrisDenton
Update a bunch of library types for MCP807

This greatly reduces the number of places that actually use the `rustc_layout_scalar_valid_range_*` attributes down to just 3:
```
library/core\src\ptr\non_null.rs
68:#[rustc_layout_scalar_valid_range_start(1)]

library/core\src\num\niche_types.rs
19:        #[rustc_layout_scalar_valid_range_start($low)]
20:        #[rustc_layout_scalar_valid_range_end($high)]
```

Everything else -- PAL Nanoseconds, alloc's `Cap`, niched FDs, etc -- all just wrap those `niche_types` types.

r? ghost
2025-01-11 01:55:05 -05:00
Josh Triplett
2808977e05 Implement ByteStr and ByteString types
Approved ACP: https://github.com/rust-lang/libs-team/issues/502
Tracking issue: https://github.com/rust-lang/rust/issues/134915

These types represent human-readable strings that are conventionally,
but not always, UTF-8. The `Debug` impl prints non-UTF-8 bytes using
escape sequences, and the `Display` impl uses the Unicode replacement
character.

This is a minimal implementation of these types and associated trait
impls. It does not add any helper methods to other types such as `[u8]`
or `Vec<u8>`.

I've omitted a few implementations of `AsRef`, `AsMut`, `Borrow`,
`From`, and `PartialOrd`, when those would be the second implementation
for a type (counting the `T` impl) or otherwise may cause inference
failures. These impls are important, but we can attempt to add them
later in standalone commits, and run them through crater.

In addition to the `bstr` feature, I've added a `bstr_internals` feature
for APIs provided by `core` for use by `alloc` but not currently
intended for stabilization.

This API and its implementation are based *heavily* on the `bstr` crate
by Andrew Gallant (@BurntSushi).
2025-01-11 06:35:21 +02:00
Scott McMurray
ebd6d3f225 Improve the safety documentation on new_unchecked 2025-01-10 18:52:22 -08:00
Samuel Tardieu
9ab77f1ccb Use NonNull::without_provenance within the standard library
This API removes the need for several `unsafe` blocks, and leads to
clearer code.
2025-01-10 23:23:10 +01:00
Scott McMurray
6f2a78345e Update a bunch of library types for MCP807
This greatly reduces the number of places that actually use the `rustc_layout_scalar_valid_range_*` attributes down to just 3:
```
library/core\src\ptr\non_null.rs
68:#[rustc_layout_scalar_valid_range_start(1)]

library/core\src\num\niche_types.rs
19:        #[rustc_layout_scalar_valid_range_start($low)]
20:        #[rustc_layout_scalar_valid_range_end($high)]
```

Everything else -- PAL Nanoseconds, alloc's `Cap`, niched FDs, etc -- all just wrap those `niche_types` types.
2025-01-09 23:47:11 -08:00
Matthias Krüger
6a40d50edc
Rollup merge of #134908 - madsmtm:ptr-from_ref-docs, r=ibraheemdev
Fix `ptr::from_ref` documentation example comment

The comment says that the expression involves no function call, but that was only true for the example above, the example here _does_ contain a function call.

``@rustbot`` label A-docs
2025-01-10 06:28:39 +01:00
Matthias Krüger
380612737a
Rollup merge of #134619 - hkBst:patch-7, r=jhpratt
Improve prose around `as_slice` example of IterMut

I've removed the cryptic message about not being able to call `&mut self` methods while retaining a shared borrow of the iterator, such as `as_slice` produces. This is just normal borrowing rules and does not seem especially relevant here. I can whip up a replacement if someone thinks it has value.
2025-01-10 06:28:38 +01:00
bors
251206c27b Auto merge of #135268 - pietroalbini:pa-bump-stage0, r=Mark-Simulacrum
Master bootstrap update

Part of the release process.

r? `@Mark-Simulacrum`
2025-01-09 13:33:16 +00:00
Pietro Albini
d894ce8827
fmt 2025-01-08 22:11:33 +01:00
Pietro Albini
2af3ba9a8a
update cfg(bootstrap) 2025-01-08 21:26:39 +01:00
Pietro Albini
4ae92b7adb
update version placeholders 2025-01-08 20:02:18 +01:00
Ralf Jung
2d23601541 add missing provenance APIs on NonNull 2025-01-08 12:49:36 +01:00
Jacob Pratt
e78b1321e5
Rollup merge of #135139 - c410-f3r:8-years-rfc, r=jhpratt
[generic_assert] Constify methods used by the formatting system

cc #44838

Starts the "constification" of all the elements required to allow the execution of the formatting system in constant environments.

```rust
const _: () = { panic!("{:?}", 1i32); };
```

Further stuff is blocked by #133999.
2025-01-06 22:04:17 -05:00
Caio
db17be84fe [generic_assert] Constify methods used by the formatting system 2025-01-05 20:49:04 -03:00
Jacob Pratt
0f9f91cccf
Rollup merge of #135121 - okaneco:const_slice_reverse, r=jhpratt
Mark `slice::reverse` unstably const

Tracking issue #135120

This is unblocked by the stabilization of `const_swap`
2025-01-05 18:35:05 -05:00
okaneco
03c2ac248f Mark slice::reverse unstably const 2025-01-05 08:01:50 -05:00
ranger-ross
6243c0f818
Clarified the documentation on core::iter::from_fn and core::iter::successors 2025-01-05 19:25:24 +09:00
The 8472
3d871b3ced do not in-place-iterate over flatmap/flatten
The implementation is unsound when a partially consumed iterator has
some elements buffered in the front/back parts and cloning the Iterator
removes the capacity from the backing vec::IntoIter.
2025-01-04 19:26:58 +01:00
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
217e10a70c Improve select_nth_unstable documentation clarity
* Instead uses `before` and `after` variable names in the example
where `greater` and `lesser` are flipped.

* Uses `<=` and `>=` instead of "less than or equal to" and "greater
than or equal to" to make the docs more concise.

* General attempt to remove unnecessary words and be more precise. For
example it seems slightly wrong to say "its final sorted position",
since this implies there is only one sorted position for this element.
2024-12-31 15:59:28 -07: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
Mads Marquart
5966ba0424 Fix ptr::from_ref documentation example comment
The comment says that the expression involves no function call, but
that was only true for the example above, the example here _does_
contain a function call.
2024-12-30 00:26:47 +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
Niklas Fiekas
7d0518c380
Implement int_from_ascii (#134821)
Provides unstable `T::from_ascii()` and `T::from_ascii_radix()` for integer
types `T`, as drafted in tracking issue #134821.

To deduplicate documentation without additional macros, implementations of
`isize` and `usize` no longer delegate to equivalent integer types.
After #132870 they are inlined anyway.
2024-12-27 20:05:09 +01: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
Caio
c89f0dc01d Adjust syntax 2024-12-22 17:12:42 -03: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
Marijn Schouten
5065a91d7f Improve prose around as_slice example of IterMut
I've removed the cryptic message about not being able to call `&mut self` methods while retaining a shared borrow of the iterator, such as `as_slice` produces. This is just normal borrowing rules and does not seem especially relevant here. I can whip up a replacement if someone thinks it has value.
2024-12-22 18:29:27 +01: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
bors
c1132470a6 Auto merge of #130733 - okaneco:is_ascii, r=scottmcm
Optimize `is_ascii` for `str` and `[u8]` further

Replace the existing optimized function with one that enables auto-vectorization.

This is especially beneficial on x86-64 as `pmovmskb` can be emitted with careful structuring of the code. The instruction can detect non-ASCII characters one vector register width at a time instead of the current `usize` at a time check.

The resulting implementation is completely safe.

`case00_libcore` is the current implementation, `case04_while_loop` is this PR.
```
benchmarks:
    ascii::is_ascii_slice::long::case00_libcore                             22.25/iter  +/- 1.09
    ascii::is_ascii_slice::long::case04_while_loop                           6.78/iter  +/- 0.92
    ascii::is_ascii_slice::medium::case00_libcore                            2.81/iter  +/- 0.39
    ascii::is_ascii_slice::medium::case04_while_loop                         1.56/iter  +/- 0.78
    ascii::is_ascii_slice::short::case00_libcore                             5.55/iter  +/- 0.85
    ascii::is_ascii_slice::short::case04_while_loop                          3.75/iter  +/- 0.22
    ascii::is_ascii_slice::unaligned_both_long::case00_libcore              26.59/iter  +/- 0.66
    ascii::is_ascii_slice::unaligned_both_long::case04_while_loop            5.78/iter  +/- 0.16
    ascii::is_ascii_slice::unaligned_both_medium::case00_libcore             2.97/iter  +/- 0.32
    ascii::is_ascii_slice::unaligned_both_medium::case04_while_loop          2.41/iter  +/- 0.10
    ascii::is_ascii_slice::unaligned_head_long::case00_libcore              23.71/iter  +/- 0.79
    ascii::is_ascii_slice::unaligned_head_long::case04_while_loop            7.83/iter  +/- 1.31
    ascii::is_ascii_slice::unaligned_head_medium::case00_libcore             3.69/iter  +/- 0.54
    ascii::is_ascii_slice::unaligned_head_medium::case04_while_loop          7.05/iter  +/- 0.32
    ascii::is_ascii_slice::unaligned_tail_long::case00_libcore              24.44/iter  +/- 1.41
    ascii::is_ascii_slice::unaligned_tail_long::case04_while_loop            5.12/iter  +/- 0.18
    ascii::is_ascii_slice::unaligned_tail_medium::case00_libcore             3.24/iter  +/- 0.40
    ascii::is_ascii_slice::unaligned_tail_medium::case04_while_loop          2.86/iter  +/- 0.14

```

`unaligned_head_medium` is the main regression in the benchmarks. It is a 32 byte string being sliced `bytes[1..]`.

The first commit can be used to run the benchmarks against the current core implementation.

Previous implementation was done in #74066

---

Two potential drawbacks of this implementation are that it increases instruction count and may regress other platforms/architectures. The benches here may also be too artificial to glean much insight from.
https://rust.godbolt.org/z/G9znGfY36
2024-12-22 02:44:13 +00:00
Matthias Krüger
3aedae24a2
Rollup merge of #134325 - theemathas:is_null-docs, r=RalfJung
Correctly document CTFE behavior of is_null and methods that call is_null.

The "panic in const if CTFE doesn't know the answer" behavior was discussed to be the desired behavior in #74939, and is currently how the function actually behaves.

I intentionally wrote this documentation to allow for the possibility that a panic might not occur even if the pointer is out of bounds, because of #133700 and other potential changes in the future.

This is beta-nominated since `const fn is_null` stabilization is in beta already but the docs there are wrong, and it seems better to have the docs be correct at the time of stabilization.
2024-12-21 22:16:02 +01:00
Yusuf Bham
466335205f Use &raw for ptr primitive docs 2024-12-21 15:47:44 -05:00
Tim (Theemathas) Chirananthavat
e6efbb210b Document CTFE behavior of methods that call is_null 2024-12-21 16:32:47 +07:00
Tim (Theemathas) Chirananthavat
93889172bc Correctly document is_null CTFE behavior.
The "panic in const if CTFE doesn't know the answer" behavior was discussed to be the desired behavior in #74939, and is currently how the function actually behaves.

I intentionally wrote this documentation to allow for the possibility that a panic might not occur even if the pointer is out of bounds, because of #133700 and other potential changes in the future.
2024-12-21 15:36:16 +07:00
Ralf Jung
526d29865c ptr::copy: fix docs for the overlapping case 2024-12-21 08:34:55 +01:00
Jacob Pratt
cc27e3f08b
Rollup merge of #134593 - kornelski:less-unwrap, r=jhpratt
Less unwrap() in documentation

I think the common use of `.unwrap()` in examples makes it overrepresented, looking like a more typical way of error handling than it really is in real programs.

Therefore, this PR changes a bunch of examples to use different error handling methods, primarily the `?` operator. Additionally, `unwrap()` docs warn that it might abort the program.
2024-12-21 01:18:43 -05:00
Jacob Pratt
c682d30337
Rollup merge of #134579 - hkBst:patch-6, r=jhpratt
Improve prose around into_slice example of IterMut

Having a part without modification and one with seems redundant, since `into_slice` is only called for the part without. I have brought the modification into the remaining part, although it perhaps does not add much (or only distracts?).
2024-12-21 01:18:42 -05:00
Jacob Pratt
91320f6eb8
Rollup merge of #134577 - hkBst:patch-5, r=jhpratt
Improve prose around `as_slice` example of Iter
2024-12-21 01:18:41 -05:00
Jacob Pratt
ba4f4f6a4f
Rollup merge of #134576 - hkBst:patch-4, r=jhpratt
Improve prose around basic examples of Iter and IterMut
2024-12-21 01:18:41 -05:00
Kevin Reid
da6616c54f Document PointerLike implementation restrictions. 2024-12-20 20:47:03 -08:00
Kornel
7b42bc0c79
Less unwrap() in documentation 2024-12-21 01:26:47 +00:00
Matthias Krüger
0b1834d66b
Rollup merge of #134573 - lukas-code:unimpl-dyn-pointerlike, r=compiler-errors
unimplement `PointerLike` for trait objects

Values of type `dyn* PointerLike` or `dyn PointerLike` are not pointer-like so these types should not implement `PointerLike`.

After https://github.com/rust-lang/rust/pull/133226, `PointerLike` allows user implementations, so we can't just mark it with `#[rustc_deny_explicit_impl(implement_via_object = false)]`. Instead, this PR splits the `#[rustc_deny_explicit_impl(implement_via_object = ...)]` attribute into two separate attributes `#[rustc_deny_explicit_impl]` and `#[rustc_do_not_implement_via_object]` so that we opt out of the automatic `impl PointerLike for dyn PointerLike` and still allow user implementations.

For traits that are marked with `#[do_not_implement_via_object]` but not `#[rustc_deny_explicit_impl]` I've also made it possible to add a manual `impl Trait for dyn Trait`. There is no immediate need for this, but it was one line to implement and seems nice to have.

fixes https://github.com/rust-lang/rust/issues/134545
fixes https://github.com/rust-lang/rust/issues/134543

r? `@compiler-errors`
2024-12-20 21:32:33 +01:00
Marijn Schouten
07ab203f34
Improve prose around into_slice example of IterMut 2024-12-20 19:57:20 +01:00
Marijn Schouten
3cfe66ab65
Improve prose around as_slice example of Iter 2024-12-20 19:19:34 +01:00
Marijn Schouten
a8e7a6c1d8
Improve prose around basic examples of Iter and IterMut 2024-12-20 18:55:48 +01:00
Marijn Schouten
496adcf36c
remove reference to dangling from slice::Iter
This aligns the comment with reality and with IterMut. Also dangling does not seem to take any arguments.
2024-12-20 18:20:40 +01:00
Lukas Markeffsky
159dba89ef fix PointerLike docs 2024-12-20 17:37:34 +01:00
Lukas Markeffsky
971a4f2d3b unimplement PointerLike for trait objects 2024-12-20 17:35:29 +01:00
Lukas Markeffsky
42c00cb647 split up #[rustc_deny_explicit_impl] attribute
This commit splits the `#[rustc_deny_explicit_impl(implement_via_object = ...)]` attribute
into two attributes `#[rustc_deny_explicit_impl]` and `#[rustc_do_not_implement_via_object]`.

This allows us to have special traits that can have user-defined impls but do not have the
automatic trait impl for trait objects (`impl Trait for dyn Trait`).
2024-12-20 16:57:14 +01:00
Jacob Pratt
ef47ba091d
Rollup merge of #134518 - hltj:typo-fix, r=tgross35
fix typos in the example code in the doc comments of `Ipv4Addr::from_bits()`, `Ipv6Addr::from_bits()` & `Ipv6Addr::to_bits()`
2024-12-20 01:36:48 -05:00
Jacob Pratt
1ec6d093b7
Rollup merge of #132830 - wr7:substr_range_documentation, r=tgross35
Rename `elem_offset` to `element_offset`

Tracking issue: #126769

Renames `slice::elem_offset` to `slice::element_offset` and improves the documentation of it and its related methods.

The current documentation can be misinterpreted (as explained [here](https://github.com/rust-lang/rust/issues/126769#issuecomment-2453363897)).
2024-12-20 01:36:46 -05:00
hltj
eef749819b fix typos in the example code in the doc comments of Ipv4Addr::from_bits(), Ipv6Addr::from_bits() & Ipv6Addr::to_bits() 2024-12-20 11:47:02 +08:00
Jacob Pratt
80cf85d584
Rollup merge of #134490 - hong9lol:typo, r=jhpratt
Fix typo in ptr/mod.rs

- Type: Document
- Description: I found a typo and want to fix it.
2024-12-18 21:38:12 -05:00
Jacob Pratt
e018796012
Rollup merge of #132056 - weiznich:diagnostic_do_not_recommend_final_tests, r=compiler-errors
Stabilize `#[diagnostic::do_not_recommend]`

This PR seeks to stabilize the `#[diagnostic::do_not_recommend]`attribute.

This attribute was first proposed as `#[do_not_recommend`] attribute in RFC 2397 (https://github.com/rust-lang/rfcs/pull/2397). It gives the crate authors the ability to not suggest to the compiler to not show certain traits in its error messages.

With the presence of the `#[diagnostic]` tool attribute namespace it was decided to move the attribute there, as that lowers the amount of guarantees the compiler needs to give about the exact way this influences error messages. It turns the attribute into a hint which can be ignored. In addition to the original proposed functionality this attribute now also hides the marked trait in help messages ("This trait is implemented by: ").

The attribute does not accept any argument and can only be placed on trait implementations. If it is placed somewhere else a lint warning is emitted and the attribute is otherwise ignored. If an argument is detected a lint warning is emitted and the argument is ignored. This follows the rules outlined by the diagnostic namespace.

This attribute allows crates like diesel to improve their error messages drastically. The most common example here is the following error message:

```
error[E0277]: the trait bound `&str: Expression` is not satisfied
  --> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:53:15
   |
LL |     SelectInt.check("bar");
   |               ^^^^^ the trait `Expression` is not implemented for `&str`, which is required by `&str: AsExpression<Integer>`
   |
   = help: the following other types implement trait `Expression`:
             Bound<T>
             SelectInt
note: required for `&str` to implement `AsExpression<Integer>`
  --> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:26:13
   |
LL | impl<T, ST> AsExpression<ST> for T
   |             ^^^^^^^^^^^^^^^^     ^
LL | where
LL |     T: Expression<SqlType = ST>,
   |        ------------------------ unsatisfied trait bound introduced here
```

By applying the new attribute to the wild card trait implementation of
`AsExpression` for `T: Expression` the error message becomes:

```
error[E0277]: the trait bound `&str: AsExpression<Integer>` is not satisfied
  --> $DIR/as_expression.rs:55:15
   |
LL |     SelectInt.check("bar");
   |               ^^^^^ the trait `AsExpression<Integer>` is not implemented for `&str`
   |
   = help: the trait `AsExpression<Text>` is implemented for `&str`
   = help: for that trait implementation, expected `Text`, found `Integer`
```

which makes it much easier for users to understand that they are facing a type mismatch.

Other explored example usages include:

* This standard library error message: https://github.com/rust-lang/rust/pull/128008
* That bevy derived example:
e1f3068995/tests/ui/diagnostic_namespace/do_not_recommend/supress_suggestions_in_help.rs (No
more tuple pyramids)

Fixes #51992

r? ``@compiler-errors``

This PR also adds a few more tests, makes sure that all the tests are run for the old and new trait solver and adds a check that the attribute does not contain arguments.
2024-12-18 21:38:08 -05:00
leejaehong
f8cd8c1c37 fix typo in ptr/mod.rs
Signed-off-by: leejaehong <jaehong2.lee@samsung.com>
2024-12-19 10:37:19 +09:00
bors
4ba4ac612d Auto merge of #134443 - joshtriplett:use-field-init-shorthand, r=lqd,tgross35,nnethercote
Use field init shorthand where possible

Field init shorthand allows writing initializers like `tcx: tcx` as
`tcx`. The compiler already uses it extensively. Fix the last few places
where it isn't yet used.

EDIT: this PR also updates `rustfmt.toml` to set
`use_field_init_shorthand = true`.
2024-12-18 19:16:15 +00:00
Jalil David Salamé Messina
20bff638bf
fix(LazyCell): documentation of get[_mut] was wrong
- `LazyCell::get`: said it was returning a **mutable** reference.
- `LazyCell::get_mut`: said it was returning a reference (the mutable
  was missing).
2024-12-18 09:43:02 +01:00
Georg Semmler
dd31713c53
Stabilize #[diagnostic::do_not_recommend]
This commit seeks to stabilize the `#[diagnostic::do_not_recommend]`
attribute.
This attribute was first proposed as `#[do_not_recommend`] attribute in
RFC 2397 (https://github.com/rust-lang/rfcs/pull/2397). It gives the
crate authors the ability to not suggest to the compiler to not show
certain traits in it's error messages. With the presence of the
`#[diagnostic]` tool attribute namespace it was decided to move the
attribute there, as that lowers the amount of guarantees the compiler
needs to give about the exact way this influences error messages. It
turns the attribute into a hint which can be ignored. In addition to the
original proposed functionality this attribute now also hides the marked
trait in help messages ("This trait is implemented by: ").
The attribute does not accept any argument and can only be placed on
trait implementations. If it is placed somewhere else a lint warning is
emitted and the attribute is otherwise ignored. If an argument is
detected a lint warning is emitted and the argument is ignored. This
follows the rules outlined by the diagnostic namespace.

This attribute allows crates like diesel to improve their error messages
drastically. The most common example here is the following error
message:

```
error[E0277]: the trait bound `&str: Expression` is not satisfied
  --> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:53:15
   |
LL |     SelectInt.check("bar");
   |               ^^^^^ the trait `Expression` is not implemented for `&str`, which is required by `&str: AsExpression<Integer>`
   |
   = help: the following other types implement trait `Expression`:
             Bound<T>
             SelectInt
note: required for `&str` to implement `AsExpression<Integer>`
  --> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:26:13
   |
LL | impl<T, ST> AsExpression<ST> for T
   |             ^^^^^^^^^^^^^^^^     ^
LL | where
LL |     T: Expression<SqlType = ST>,
   |        ------------------------ unsatisfied trait bound introduced here
```

By applying the new attribute to the wild card trait implementation of
`AsExpression` for `T: Expression` the error message becomes:

```
error[E0277]: the trait bound `&str: AsExpression<Integer>` is not satisfied
  --> $DIR/as_expression.rs:55:15
   |
LL |     SelectInt.check("bar");
   |               ^^^^^ the trait `AsExpression<Integer>` is not implemented for `&str`
   |
   = help: the trait `AsExpression<Text>` is implemented for `&str`
   = help: for that trait implementation, expected `Text`, found `Integer`
```

which makes it much easier for users to understand that they are facing
a type mismatch.

Other explored example usages included

* This standard library error message: https://github.com/rust-lang/rust/pull/128008
* That bevy derived example:
e1f3068995/tests/ui/diagnostic_namespace/do_not_recommend/supress_suggestions_in_help.rs (No
more tuple pyramids)

Fixes #51992
2024-12-18 07:10:53 +01:00
Josh Triplett
a105cd6066 Use field init shorthand where possible
Field init shorthand allows writing initializers like `tcx: tcx` as
`tcx`. The compiler already uses it extensively. Fix the last few places
where it isn't yet used.
2024-12-17 14:33:10 -08:00
Matthias Krüger
3b0df8c59f
Rollup merge of #134426 - hkBst:patch-3, r=lqd
Fix typo in uint_macros.rs
2024-12-17 22:34:44 +01:00
Marijn Schouten
c482b31195
Fix typo in uint_macros.rs 2024-12-17 14:43:22 +01:00
ltdk
cb487cc2fa Stabilize #[coverage] attribute 2024-12-16 21:07:06 -05:00
Matthias Krüger
d9ba4bf6fe
Rollup merge of #134277 - notriddle:notriddle/inline-into, r=GuillaumeGomez
rustdoc-search: handle `impl Into<X>` better

This PR fixes two bugs I ran into while searching the compiler docs:

- It omitted an `impl Trait` entry in the type signature field, producing `TyCtxt, , Symbol -> bool`
- It didn't let me search for `TyCtxt, DefId, Symbol -> bool` even though that's a perfectly good description of the function I was looking for (the function actually used `impl Into<DefId>`

r? ``@GuillaumeGomez`` cc ``@lolbinarycat``
2024-12-16 20:00:20 +01:00
Stuart Cook
b974187950
Rollup merge of #134310 - tkr-sh:master, r=Noratrieb
Add clarity to the examples of some `Vec` & `VecDeque` methods

In some `Vec` and `VecDeque` examples where elements are `i32`, examples can seem a bit confusing at first glance if a parameter of the method is an `usize`.

In this case, I think it's better to use `char` rather than `i32`.

> [!NOTE]
> It's already done in the implementation of `VecDeque::insert`

#### Difference

- `i32`
```rs
let mut v = vec![1, 2, 3];
assert_eq!(v.remove(1), 2);
assert_eq!(v, [1, 3]);
```
- `char`
```rs
let mut v = vec!['a', 'b', 'c'];
assert_eq!(v.remove(1), 'b');
assert_eq!(v, ['a', 'c']);
```

Even tho it's pretty minor, it's a nice to have.
2024-12-15 20:01:38 +11:00
EFanZh
b5ea631fbd Asserts the maximum value that can be returned from Vec::len 2024-12-15 15:44:56 +08:00
Matthias Krüger
9b9905593f
Rollup merge of #134022 - shahn:doc_clarify_extend_for_tuple_version, r=tgross35
Doc: Extend for tuples to be stabilized in 1.85.0

I assumed the RUSTC_CURRENT_VERSION would be replaced automatically, but it doesn't look like it on the nightly docs page. Sorry!
2024-12-14 23:56:31 +01:00
Sebastian Hahn
7717df2286 Correct spelling of CURRENT_RUSTC_VERSION
I mixed it up with RUSTC_CURRENT_VERSION unfortunately. Also improve the
formatting of the macro invocation slightly.
2024-12-14 21:40:11 +01:00
tkirishima
6d5c591405 Replace i32 by char in split_at & _unchecked 2024-12-14 14:25:55 +00:00
bors
f1ec5d64b3 Auto merge of #134296 - matthiaskrgr:rollup-o0sxozj, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #132150 (Fix powerpc64 big-endian FreeBSD ABI)
 - #133942 (Clarify how to use `black_box()`)
 - #134081 (Try to evaluate constants in legacy mangling)
 - #134192 (Remove `Lexer`'s dependency on `Parser`.)
 - #134208 (coverage: Tidy up creation of covmap and covfun records)
 - #134211 (On Neutrino QNX, reduce the need to set archiver via environment variables)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-14 13:06:18 +00:00
Matthias Krüger
8abb823520
Rollup merge of #133942 - BD103:black-box-docs, r=saethlin
Clarify how to use `black_box()`

Closes #133923.

r? libs
^ (I think that's the right group, this is my first time!)

This PR adds further clarification on the [`black_box()`](https://doc.rust-lang.org/stable/std/hint/fn.black_box.html) documentation. Specifically, it teaches _how_ to use it, instead of just _when_ to use it.

I tried my best to make it clear and accurate, but a lot of my information is sourced from https://github.com/rust-lang/rust-clippy/issues/12707 and [manually inspecting assembly](https://godbolt.org/). Please tell me if I got anything wrong!
2024-12-14 05:01:05 +01:00
Matthias Krüger
0b5003eaf0
Rollup merge of #134255 - bjoernager:master, r=Noratrieb
Update includes in `/library/core/src/error.rs`.

This PR removes the `crate::fmt::Result` include in `/library/core/src/error.rs`.

The main issue with this `use` statement is that it shadows the `Result` type from the prelude (i.e. `crate::result::Result`). This indirectly makes all docs references to `Result` in this module point to the wrong type (but only in `core::error` - not `std::error`, wherein this include isn't present to begin with).

Fixes: #134169
2024-12-14 04:09:34 +01:00
Michael Howell
246835eda4 rustdoc-search: let From and Into be unboxed 2024-12-13 11:05:30 -07:00
Matthias Krüger
8cce32ae2b
Rollup merge of #134229 - purplesyringa:provenance-docs, r=saethlin
Fix typos in docs on provenance

This is related to [strict provenance](https://github.com/rust-lang/rust/issues/95228).

Added a couple cross-refs, also replaced

> Create a pointer without provenance from just an address (see [`ptr::dangling`]).

with

> Create a pointer without provenance from just an address (see [`without_provenance`]).

as this method actually takes an address.
2024-12-13 17:25:31 +01:00
Matthias Krüger
5c9b227a3d
Rollup merge of #134140 - compiler-errors:unsafe-binders-ast, r=oli-obk
Add AST support for unsafe binders

I'm splitting up #130514 into pieces. It's impossible for me to keep up with a huge PR like that. I'll land type system support for this next, probably w/o MIR lowering, which will come later.

r? `@oli-obk`
cc `@BoxyUwU` and `@lcnr` who also may want to look at this, though this PR doesn't do too much yet
2024-12-13 17:25:31 +01:00
bors
4847d6a9d0 Auto merge of #134047 - saethlin:inline-fmt-rt, r=m-ou-se
Switch inline(always) in core/src/fmt/rt.rs to plain inline

I have a vague memory of these being instantiated a lot. Let's ask perf.

Looks like this is an improvement!
2024-12-13 12:04:04 +00:00
Gabriel Bjørnager Jensen
38eb608a43 Update includes in '/library/core/src/error.rs'; 2024-12-13 12:46:20 +01:00
Michael Goulet
c605c84be8 Stabilize async closures 2024-12-13 00:04:56 +00:00
Alisa Sireneva
6ce7ba4300 Fix typos in docs on provenance 2024-12-12 22:52:12 +03:00
BD103
7fb2fc01a5 feat: clarify how to use black_box()
Co-authored-by: Ben Kimock <kimockb@gmail.com>
2024-12-12 13:54:17 -05:00
Michael Goulet
3f97c6be8d Add unwrap_unsafe_binder and wrap_unsafe_binder macro operators 2024-12-12 16:29:40 +00:00
Matthias Krüger
10556598e5
Rollup merge of #134179 - zachs18:align_offset_mut_ptr_doc, r=workingjubilee
Remove outdated consteval note from `<*mut T>::align_offset` docs.
2024-12-12 08:07:04 +01:00
Matthias Krüger
90f6b27a93
Rollup merge of #134178 - ehuss:stabilize-2024-prelude, r=amanieu,traviscross,tgross35
Stabilize the Rust 2024 prelude

This stabilizes the `core::prelude::rust_2024` and `std::prelude::rust_2024` modules. I missed these in the #133349 stabilization.
2024-12-12 08:07:04 +01:00