Commit Graph

7718 Commits

Author SHA1 Message Date
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
Eric Huss
1bc58979a2 Stabilize the Rust 2024 prelude 2024-12-11 13:09:57 -08:00
bors
21fe748be1 Auto merge of #134177 - matthiaskrgr:rollup-hgp8q60, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #132975 (De-duplicate and improve definition of core::ffi::c_char)
 - #133598 (Change `GetManyMutError` to match T-libs-api decision)
 - #134148 (add comments in check_expr_field)
 - #134163 (coverage: Rearrange the code for embedding per-function coverage metadata)
 - #134165 (wasm(32|64): update alignment string)
 - #134170 (Subtree update of `rust-analyzer`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-11 19:06:46 +00:00
Matthias Krüger
2e60288ce0
Rollup merge of #133598 - ChayimFriedman2:get-many-mut-detailed-err, r=scottmcm
Change `GetManyMutError` to match T-libs-api decision

That is, differentiate between out-of-bounds and overlapping indices, and remove the generic parameter `N`.

I also exported `GetManyMutError` from `alloc` (and `std`), which was apparently forgotten.

Changing the error to carry additional details means LLVM no longer generates separate short-circuiting branches for the checks, instead it generates one branch at the end. I therefore changed the  code to use early returns to make LLVM generate jumps. Benchmark results between the approaches are somewhat mixed, but I chose this approach because it is significantly faster with ranges and also faster with `unwrap()`.

Benchmark (`jumps` refer to short-circuiting, `acc` is not short-circuiting):
```rust
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use my_crate::{get_many_check_valid_acc, get_many_check_valid_jumps, GetManyMutError};

mod externs {
    #[unsafe(no_mangle)]
    fn foo() {}
    #[unsafe(no_mangle)]
    fn bar() {}
    #[unsafe(no_mangle)]
    fn baz() {}
}

unsafe extern "C" {
    safe fn foo();
    safe fn bar();
    safe fn baz();
}

fn bench_method(c: &mut Criterion) {
    c.bench_function("jumps two usize", |b| {
        b.iter(|| get_many_check_valid_jumps(&[black_box(1), black_box(5)], black_box(10)))
    });
    c.bench_function("jumps two usize unwrap", |b| {
        b.iter(|| get_many_check_valid_jumps(&[black_box(1), black_box(5)], black_box(10)).unwrap())
    });
    c.bench_function("jumps two usize ok", |b| {
        b.iter(|| get_many_check_valid_jumps(&[black_box(1), black_box(5)], black_box(10)).ok())
    });
    c.bench_function("jumps three usize", |b| {
        b.iter(|| {
            get_many_check_valid_jumps(&[black_box(1), black_box(5), black_box(7)], black_box(10))
        })
    });
    c.bench_function("jumps three usize match", |b| {
        b.iter(|| {
            match get_many_check_valid_jumps(
                &[black_box(1), black_box(5), black_box(7)],
                black_box(10),
            ) {
                Err(GetManyMutError::IndexOutOfBounds) => foo(),
                Err(GetManyMutError::OverlappingIndices) => bar(),
                Ok(()) => baz(),
            }
        })
    });
    c.bench_function("jumps two Range", |b| {
        b.iter(|| {
            get_many_check_valid_jumps(
                &[black_box(1)..black_box(5), black_box(7)..black_box(8)],
                black_box(10),
            )
        })
    });
    c.bench_function("jumps two RangeInclusive", |b| {
        b.iter(|| {
            get_many_check_valid_jumps(
                &[black_box(1)..=black_box(5), black_box(7)..=black_box(8)],
                black_box(10),
            )
        })
    });

    c.bench_function("acc two usize", |b| {
        b.iter(|| get_many_check_valid_acc(&[black_box(1), black_box(5)], black_box(10)))
    });
    c.bench_function("acc two usize unwrap", |b| {
        b.iter(|| get_many_check_valid_acc(&[black_box(1), black_box(5)], black_box(10)).unwrap())
    });
    c.bench_function("acc two usize ok", |b| {
        b.iter(|| get_many_check_valid_acc(&[black_box(1), black_box(5)], black_box(10)).ok())
    });
    c.bench_function("acc three usize", |b| {
        b.iter(|| {
            get_many_check_valid_acc(&[black_box(1), black_box(5), black_box(7)], black_box(10))
        })
    });
    c.bench_function("acc three usize match", |b| {
        b.iter(|| {
            match get_many_check_valid_jumps(
                &[black_box(1), black_box(5), black_box(7)],
                black_box(10),
            ) {
                Err(GetManyMutError::IndexOutOfBounds) => foo(),
                Err(GetManyMutError::OverlappingIndices) => bar(),
                Ok(()) => baz(),
            }
        })
    });
    c.bench_function("acc two Range", |b| {
        b.iter(|| {
            get_many_check_valid_acc(
                &[black_box(1)..black_box(5), black_box(7)..black_box(8)],
                black_box(10),
            )
        })
    });
    c.bench_function("acc two RangeInclusive", |b| {
        b.iter(|| {
            get_many_check_valid_acc(
                &[black_box(1)..=black_box(5), black_box(7)..=black_box(8)],
                black_box(10),
            )
        })
    });
}

criterion_group!(benches, bench_method);
criterion_main!(benches);
```
Benchmark results:
```none
jumps two usize          time:   [586.44 ps 590.20 ps 594.50 ps]
jumps two usize unwrap   time:   [390.44 ps 393.63 ps 397.44 ps]
jumps two usize ok       time:   [585.52 ps 591.74 ps 599.38 ps]
jumps three usize        time:   [976.51 ps 983.79 ps 991.51 ps]
jumps three usize match  time:   [390.82 ps 393.80 ps 397.07 ps]
jumps two Range          time:   [1.2583 ns 1.2640 ns 1.2695 ns]
jumps two RangeInclusive time:   [1.2673 ns 1.2770 ns 1.2877 ns]
acc two usize            time:   [592.63 ps 596.44 ps 600.52 ps]
acc two usize unwrap     time:   [582.65 ps 587.07 ps 591.90 ps]
acc two usize ok         time:   [581.59 ps 587.82 ps 595.71 ps]
acc three usize          time:   [894.69 ps 901.23 ps 908.24 ps]
acc three usize match    time:   [392.68 ps 395.73 ps 399.17 ps]
acc two Range            time:   [1.5531 ns 1.5617 ns 1.5711 ns]
acc two RangeInclusive   time:   [1.5746 ns 1.5840 ns 1.5939 ns]
```
2024-12-11 20:00:14 +01:00
Matthias Krüger
fe516ef9f4
Rollup merge of #132975 - arichardson:ffi-c-char, r=tgross35
De-duplicate and improve definition of core::ffi::c_char

Instead of having a list of unsigned char targets for each OS, follow the logic Clang uses and instead set the value based on architecture with a special case for Darwin and Windows operating systems. This makes it easier to support new operating systems targeting Arm/AArch64 without having to modify this config statement for each new OS. The new list does not quite match Clang since I noticed a few bugs in the Clang implementation (https://github.com/llvm/llvm-project/issues/115957).

Fixes https://github.com/rust-lang/rust/issues/129945
Closes https://github.com/rust-lang/rust/pull/131319
2024-12-11 20:00:12 +01:00
Zachary S
6a8bc4bc6b Remove consteval note from <*mut T>::align_offset docs. 2024-12-11 12:56:12 -06:00
Jacob Pratt
43b4af5b77
Rollup merge of #134079 - tbu-:pr_doc_x8_to_from_xe_bytes, r=jhpratt
Add a note saying that `{u8,i8}::from_{be,le,ne}_bytes` is meaningless
2024-12-11 03:30:40 -05:00
Tobias Bucher
e37d7c0f15 Add a note saying that {u8,i8}::from_{be,le,ne}_bytes is meaningless 2024-12-11 02:18:17 +01:00
León Orell Valerian Liehr
e822dfc415
Rollup merge of #134116 - RalfJung:const_nonnull_new, r=jhpratt
stabilize const_nonnull_new

FCP passed in https://github.com/rust-lang/rust/issues/93235

Closes #93235
2024-12-10 20:16:06 +01:00
León Orell Valerian Liehr
f621be4ecc
Rollup merge of #134100 - eholk:noop-rustc-const-stable, r=dtolnay
Remove rustc_const_stable attribute on const NOOP

This was accidentally reintroduced while editing #133089.

r? dtolnay
2024-12-10 20:16:03 +01:00
Alex Richardson
dd3e98c58b Add references to the specific ABI documents
Expcept for L4RE and Xtensa these were obtained from #131319

I could not find an open link to the Xtensa documentation, but the
signedness was confirmed by on of the Xtensa developers in
https://github.com/llvm/llvm-project/pull/115967#issuecomment-2506292323

Co-authored-by: Taiki Endo <te316e89@gmail.com>
2024-12-10 08:33:29 -08:00
Alex Richardson
e8bcce77bb Remove l4re from the unsigned char operating system list
As noted in https://github.com/rust-lang/rust/pull/132975#issuecomment-2484645240,
the default for userland apps is to follow the architecture defaults, the
-funsigned-char flag only applies to kernel builds.
2024-12-10 08:33:29 -08:00
Alex Richardson
028ca8e616 De-duplicate and improve definition of core::ffi::c_char
Instead of having a list of unsigned char targets for each OS, follow the
logic Clang uses and instead set the value based on architecture with
a special case for Darwin and Windows operating systems. This makes it
easier to support new operating systems targeting Arm/AArch64 without
having to modify this config statement for each new OS. The new list does
not quite match Clang since I noticed a few bugs in the Clang
implementation (https://github.com/llvm/llvm-project/issues/115957).

Fixes: https://github.com/rust-lang/rust/issues/129945
2024-12-10 08:33:29 -08:00
Ralf Jung
a8d11ea20e stabilize const_nonnull_new 2024-12-10 11:29:01 +01:00
Eric Holk
b9afc78585
Remove rustc_const_stable attribute on const NOOP
This was accidentally reintroduced while editing #133089.
2024-12-09 15:08:30 -08:00
León Orell Valerian Liehr
e0f3db0056
Rollup merge of #134032 - snprajwal:fix-docs, r=joboet
docs: better examples for `std::ops::ControlFlow`

Fixes #133963. Lesson learnt, never force-push from a bare clone of a repo 💀
2024-12-09 23:39:04 +01:00
joboet
49d76b8d0e
core: use public method instead of instrinsic 2024-12-09 13:27:06 +01:00
Jonas Böttiger
13c77ba34d
core: improve comments
Co-authored-by: Yotam Ofek <yotam.ofek@gmail.com>
Co-authored-by: Hanna Kruppe <hanna.kruppe@gmail.com>
2024-12-09 13:22:39 +01:00
bors
1b3fb31675 Auto merge of #134052 - matthiaskrgr:rollup-puxwqrk, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #133567 (A bunch of cleanups)
 - #133789 (Add doc alias 'then_with' for `then` method on `bool`)
 - #133880 (Expand home_dir docs)
 - #134036 (crash tests: use individual mir opts instead of mir-opt-level where easily possible)
 - #134045 (Fix some triagebot mentions paths)
 - #134046 (Remove ignored tests for hangs w/ new solver)
 - #134050 (Miri subtree update)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-09 03:24:24 +00:00
Matthias Krüger
38cc868e21
Rollup merge of #133789 - rossmacarthur:then-with-doc-alias, r=Mark-Simulacrum
Add doc alias 'then_with' for `then` method on `bool`

I think its logical to search for this name since `Ordering::then_with` exists as well.
2024-12-09 01:56:32 +01:00
Ben Kimock
5f68526b31 Switch inline(always) in core/src/fmt/rt.rs to plain inline 2024-12-08 15:41:00 -05:00
aaishwarymishra@gmail.com
292fd0ffed Adds new intrinsic declaration
changes old intrinsic to new declaration
2024-12-08 19:46:45 +05:30
Prajwal S N
477b722fe1
docs: better examples for std::ops::ControlFlow
Signed-off-by: Prajwal S N <prajwalnadig21@gmail.com>
2024-12-08 18:21:15 +05:30
bors
9c707a8b76 Auto merge of #133978 - matthiaskrgr:rollup-6gh1iho, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #130209 (Stabilize `std::io::ErrorKind::CrossesDevices`)
 - #130254 (Stabilize `std::io::ErrorKind::QuotaExceeded`)
 - #132187 (Add Extend impls for tuples of arity 1 through 12)
 - #133875 (handle `--json-output` properly)
 - #133934 (Do not implement unsafe auto traits for types with unsafe fields)
 - #133954 (Hide errors whose suggestions would contain error constants or types)
 - #133960 (rustdoc: remove eq for clean::Attributes)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-07 09:38:00 +00:00
bors
75716b4510 Auto merge of #118159 - EliasHolzmann:formatting_options, r=m-ou-se
Implementation of `fmt::FormattingOptions`

Tracking issue: #118117

Public API:
```rust
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct FormattingOptions { … }
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Sign {
    Plus,
    Minus
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DebugAsHex {
    Lower,
    Upper
}

impl FormattingOptions {
    pub fn new() -> Self;
    pub fn sign(&mut self, sign: Option<Sign>) -> &mut Self;
    pub fn sign_aware_zero_pad(&mut self, sign_aware_zero_pad: bool) -> &mut Self;
    pub fn alternate(&mut self, alternate: bool) -> &mut Self;
    pub fn fill(&mut self, fill: char) -> &mut Self;
    pub fn align(&mut self, alignment: Option<Alignment>) -> &mut Self;
    pub fn width(&mut self, width: Option<usize>) -> &mut Self;
    pub fn precision(&mut self, precision: Option<usize>) -> &mut Self;
    pub fn debug_as_hex(&mut self, debug_as_hex: Option<DebugAsHex>) -> &mut Self;

    pub fn get_sign(&self) -> Option<Sign>;
    pub fn get_sign_aware_zero_pad(&self) -> bool;
    pub fn get_alternate(&self) -> bool;
    pub fn get_fill(&self) -> char;
    pub fn get_align(&self) -> Option<Alignment>;
    pub fn get_width(&self) -> Option<usize>;
    pub fn get_precision(&self) -> Option<usize>;
    pub fn get_debug_as_hex(&self) -> Option<DebugAsHex>;

    pub fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a>;
    }

impl<'a> Formatter<'a> {
    pub fn new(write: &'a mut (dyn Write + 'a), options: FormattingOptions) -> Self;
    pub fn with_options<'b>(&'b mut self, options: FormattingOptions) -> Formatter<'b>;
    pub fn sign(&self) -> Option<Sign>;

    pub fn options(&self) -> FormattingOptions;
}
```

Relevant changes from the public API in the tracking issue (I'm leaving out some stuff I consider obvious mistakes, like missing `#[derive(..)]`s and `pub` specifiers):

- `enum DebugAsHex`/`FormattingOptions::debug_as_hex`/`FormattingOptions::get_debug_as_hex`: To support `{:x?}` as well as `{:X?}`. I had completely missed these options in the ACP. I'm open for any and all bikeshedding, not married to the name.
- `fill`/`get_fill` now takes/returns `char` instead of `Option<char>`. This simply mirrors what `Formatter::fill` returns (with default being `' '`).
- Changed `zero_pad`/`get_zero_pad` to `sign_aware_zero_pad`/`get_sign_aware_zero_pad`. This also mirrors `Formatter::sign_aware_zero_pad`. While I'm not a fan of this quite verbose name, I do believe that having the interface of `Formatter` and `FormattingOptions` be compatible is more important.
- For the same reason, renamed `alignment`/`get_alignment` to `aling`/`get_align`.
- Deviating from my initial idea, `Formatter::with_options` returns a `Formatter` which has the lifetime of the `self` reference as its generic lifetime parameter (in the original API spec, the generic lifetime of the returned `Formatter` was the generic lifetime used by `self` instead). Otherwise, one could construct two `Formatter`s that both mutably borrow the same underlying buffer, which would be unsound. This solution still has performance benefits over simply using `Formatter::new`, so I believe it is worthwhile to keep this method.
2024-12-06 22:28:42 +00:00
Matthias Krüger
bfbbe95502
Rollup merge of #132187 - shahn:extend_more_tuples, r=dtolnay
Add Extend impls for tuples of arity 1 through 12
2024-12-06 21:21:05 +01:00
bors
8dc83770f7 Auto merge of #133089 - eholk:stabilize-noop-waker, r=dtolnay
Stabilize noop_waker

Tracking Issue: #98286

This is a handy feature that's been used widely in tests and example async code and it'd be nice to make it available to users.

cc `@rust-lang/wg-async`
2024-12-06 18:34:16 +00:00
joboet
69942f0132
core: implement bool::select_unpredictable 2024-12-06 15:07:50 +01:00
Guillaume Gomez
5a9c9ef541
Rollup merge of #133821 - Kobzol:replace-black-with-ruff, r=onur-ozkan
Replace black with ruff in `tidy`

`ruff` can both lint and format Python code (in fact, it should be a mostly drop-in replacement for `black` in terms of formatting), so it's not needed to use `black` anymore. This PR removes `black` and replaces it with `ruff`, to get rid of one Python dependency, and also to make Python formatting faster (although that's a small thing).

If we decide to merge this, we'll need to "reformat the world" - `ruff` is not perfectly compatible with `black`, and it also looks like `black` was actually ignoring some files before. I tried it locally (`./x test tidy --extra-checks=py:fmt --bless`) and it also reformatted some code in subtrees (e.g. `clippy` or `rustc_codegen_gcc`) - I'm not sure how to handle that.
2024-12-05 23:47:11 +01:00
Eric Holk
72ce1ab42f
Stabilize noop_waker
Co-authored-by: zachs18 <8355914+zachs18@users.noreply.github.com>
2024-12-05 14:14:17 -08:00
Elias Holzmann
31a5657109 Access members of FormattingOptions directly instead of via getters/setters 2024-12-05 21:48:36 +01:00
Elias Holzmann
2f9e0c984b Removed constness for methods receiving a &mut parameter
See https://github.com/rust-lang/rust/pull/118159#discussion_r1495760867
for context.
2024-12-05 21:48:36 +01:00
Elias Holzmann
245acf819d Added better reason for exposing flags and get_flags as unstable 2024-12-05 21:48:36 +01:00
Elias Holzmann
2fc260802c Formatted 2024-12-05 21:48:35 +01:00
Elias Holzmann
832a5f292f Refactored FormattingOptions to use a bitmask for storing flags 2024-12-05 21:48:35 +01:00
Elias Holzmann
5b236555d2 Revert "Turned public+unstable+hidden functions into private functions"
See https://github.com/rust-lang/rust/pull/118159#discussion_r1491842170 for
context.

This reverts commit 62078dffcc1aefd4d678df94bca06e7b864065bd.
2024-12-05 21:48:35 +01:00
Elias Holzmann
7eac57a395 Turned public+unstable+hidden functions into private functions 2024-12-05 21:48:35 +01:00
Elias Holzmann
b8b50aecc4 Made all fns const 2024-12-05 21:48:35 +01:00
Elias Holzmann
de073f42a8 impl Default for fmt::FormattingOptions 2024-12-05 21:48:35 +01:00
Elias Holzmann
a5a6d40791 Fixed copy+paste error in comment
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
2024-12-05 21:48:35 +01:00
Elias Holzmann
ecdf48e2b1 fmt::FormattingOptions: Renamed alignment to align
Likewise for `get_alignment`. This is how the method is named on `Formatter`, I
want to keep it consistent.
2024-12-05 21:48:35 +01:00
Elias Holzmann
b0d3958e00 Formatter::with_options: Use different lifetimes
Formatter::with_options takes self as a mutable reference (`&'a mut
Formatter<'b>`). `'a` and `'b` need to be different lifetimes. Just taking `&'a
mut Formatter<'a>` and trusting in Rust being able to implicitely convert from
`&'a mut Formatter<'b>` if necessary (after all, `'a` must be smaller than `'b`
anyway) fails because `'b` is behind a *mutable* reference. For background on
on this behavior, see https://doc.rust-lang.org/nomicon/subtyping.html#variance.
2024-12-05 21:48:35 +01:00
Elias Holzmann
f17d13285c Added struct fmt::FormattingOptions
This allows to build custom `std::Formatter`s at runtime.

Also added some related enums and two related methods on `std::Formatter`.
2024-12-05 21:48:01 +01:00
Elias Holzmann
1d7984a132 Formatter: Access members via getter methods wherever possible
The idea behind this is to make implementing `fmt::FormattingOptions` (as well
as any future changes to `std::Formatter`) easier.

In theory, this might have a negative performance impact because of the
additional function calls. However, I strongly believe that those will be
inlined anyway, thereby producing assembly code that has comparable performance.
2024-12-05 21:47:13 +01:00
Jacob Pratt
f5f8a1f8ce
Rollup merge of #133844 - RalfJung:simd_relaxed_fma-nondet, r=workingjubilee
clarify simd_relaxed_fma non-determinism

This is the safer spec in the sense that it is more likely to be satisfied by the backend -- and if people are okay with a non-deterministic result, I assume they don't care whether it's the same choice across all lanes or not?

Cc ``@calebzulawski`` ``@workingjubilee``
2024-12-05 05:50:51 -05:00
Jacob Pratt
b5a7f41a87
Rollup merge of #127565 - esp-rs:xtensa-vaargs, r=workingjubilee
Teach rustc about the Xtensa VaListImpl

Following on from the target Xtensa target PRs (https://github.com/rust-lang/rust/pull/125141, https://github.com/rust-lang/rust/pull/126380), this PR teaches rustc about the structure of the VA list on the Xtensa arch, as well as adding the required lowering to be able to actually use it.
2024-12-05 05:50:50 -05:00
Jakub Beránek
536516f949
Reformat Python code with ruff 2024-12-04 23:03:44 +01:00
Oli Scherer
f613636ae8 Rename core_pattern_type and core_pattern_types lib feature gates to pattern_type_macro
That's what the gates are actually gating, and the single char difference in naming was not helpful either
2024-12-04 16:16:24 +00:00
Ralf Jung
f4217f4296 clarify simd_relaxed_fma non-determinism 2024-12-04 08:39:19 +01:00
Matthias Krüger
68f8a53f12
Rollup merge of #133651 - scottmcm:nonnull-nonzero-no-field-projection, r=oli-obk
Update `NonZero` and `NonNull` to not field-project (per MCP#807)

https://github.com/rust-lang/compiler-team/issues/807#issuecomment-2506098540 was accepted, so this is the first PR towards moving the library to not using field projections into `[rustc_layout_scalar_valid_range_*]` types.

`NonZero` was already using `transmute` nearly everywhere, so there are very few changes to it.

`NonNull` needed more changes, but they're mostly simple, changing `.pointer` to `.as_ptr()`.

r? libs

cc #133324, which will tidy up some of the MIR from this a bit more, but isn't a blocker.
2024-12-04 05:42:07 +01:00
bors
3b382642ab Auto merge of #133818 - matthiaskrgr:rollup-iav1wq7, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #132937 (a release operation synchronizes with an acquire operation)
 - #133681 (improve TagEncoding::Niche docs, sanity check, and UB checks)
 - #133726 (Add `core::arch::breakpoint` and test)
 - #133768 (Remove `generic_associated_types_extended` feature gate)
 - #133811 ([AIX] change AIX default codemodel=large)
 - #133812 (Update wasm-component-ld to 0.5.11)
 - #133813 (compiletest: explain that UI tests are expected not to compile by default)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-04 00:47:09 +00:00
Matthias Krüger
e66e632479
Rollup merge of #133726 - joshtriplett:breakpoint, r=oli-obk
Add `core::arch::breakpoint` and test

Approved in [ACP 491](https://github.com/rust-lang/libs-team/issues/491).
2024-12-03 21:55:27 +01:00