Commit graph

786 commits

Author SHA1 Message Date
The 8472 0d7aef9738 regression test for leaks in the the Filter::next_chunk implementation
previously next_chunk would forget items rejected by the filter
2024-06-25 23:22:27 +02:00
Kevin Reid 13fca73f49 Replace MaybeUninit::uninit_array() with array repeat expression.
This is possible now that inline const blocks are stable; the idea was
even mentioned as an alternative when `uninit_array()` was added:
<https://github.com/rust-lang/rust/pull/65580#issuecomment-544200681>

> if it’s stabilized soon enough maybe it’s not worth having a
> standard library method that will be replaceable with
> `let buffer = [MaybeUninit::<T>::uninit(); $N];`

Const array repetition and inline const blocks are now stable (in the
next release), so that circumstance has come to pass, and we no longer
have reason to want `uninit_array()` other than convenience. Therefore,
let’s evaluate the inconvenience by not using `uninit_array()` in
the standard library, before potentially deleting it entirely.
2024-06-24 10:23:50 -07:00
bors f944afe380 Auto merge of #116113 - kpreid:arcmut, r=dtolnay
Generalize `{Rc,Arc}::make_mut()` to unsized types.

* `{Rc,Arc}::make_mut()` now accept any type implementing the new unstable trait `core::clone::CloneToUninit`.
* `CloneToUninit` is implemented for `T: Clone` and for `[T] where T: Clone`.
* `CloneToUninit` is a generalization of the existing internal trait `alloc::alloc::WriteCloneIntoRaw`.
* New feature gate: `clone_to_uninit`

This allows performing `make_mut()` on `Rc<[T]>` and `Arc<[T]>`, which was not previously possible.

---

Previous PR description, now obsolete:

>  Add `{Rc, Arc}::make_mut_slice()`
>
> These functions behave identically to `make_mut()`, but operate on `Arc<[T]>` instead of `Arc<T>`.
>
> This allows performing the operation on slices, which was not previously possible because `make_mut()` requires `T: Clone` (and slices, being `!Sized`, do not and currently cannot implement `Clone`).
>
> Feature gate: `make_mut_slice`

try-job: test-various
2024-06-22 16:35:29 +00:00
Kevin Reid ec201b8650 Add core::clone::CloneToUninit.
This trait allows cloning DSTs, but is unsafe to implement and use
because it writes to possibly-uninitialized memory which must be of the
correct size, and must initialize that memory.

It is only implemented for `T: Clone` and `[T] where T: Clone`, but
additional implementations could be provided for specific `dyn Trait`
or custom-DST types.
2024-06-22 08:08:00 -07:00
Matthias Krüger 7a827d349f
Rollup merge of #126613 - tgross35:log-test-update, r=cuviper
Print the tested value in int_log tests

Tiny change - from the failures in https://github.com/rust-lang/rust/pull/125016, it would have been nice to see what the tested values were. Update the assertion messages.
2024-06-21 09:12:35 +02:00
bors 684b3553f7 Auto merge of #124032 - Voultapher:a-new-sort, r=thomcc
Replace sort implementations

This PR replaces the sort implementations with tailor-made ones that strike a balance of run-time, compile-time and binary-size, yielding run-time and compile-time improvements. Regressing binary-size for `slice::sort` while improving it for `slice::sort_unstable`. All while upholding the existing soft and hard safety guarantees, and even extending the soft guarantees, detecting strict weak ordering violations with a high chance and reporting it to users via a panic.

* `slice::sort` -> driftsort [design document](https://github.com/Voultapher/sort-research-rs/blob/main/writeup/driftsort_introduction/text.md), includes detailed benchmarks and analysis.

* `slice::sort_unstable` -> ipnsort [design document](https://github.com/Voultapher/sort-research-rs/blob/main/writeup/ipnsort_introduction/text.md), includes detailed benchmarks and analysis.

#### Why should we change the sort implementations?

In the [2023 Rust survey](https://blog.rust-lang.org/2024/02/19/2023-Rust-Annual-Survey-2023-results.html#challenges), one of the questions was: "In your opinion, how should work on the following aspects of Rust be prioritized?". The second place was "Runtime performance" and the third one "Compile Times". This PR aims to improve both.

#### Why is this one big PR and not multiple?

* The current documentation gives performance recommendations for `slice::sort` and `slice::sort_unstable`. If for example only one of them were to be changed, this advice would be misleading for some Rust versions. By replacing them atomically, the advice remains largely unchanged, and users don't have to change their code.
* driftsort and ipnsort share a substantial part of their implementations.
* The implementation of `select_nth_unstable` uses internals of `slice::sort_unstable`, which makes it impractical to split changes.

---

This PR is a collaboration with `@orlp.`
2024-06-20 20:40:43 +00:00
Matthias Krüger ef2e8bfcbf
Rollup merge of #126717 - nnethercote:rustfmt-use-pre-cleanups, r=jieyouxu
Clean up some comments near `use` declarations

#125443 will reformat all `use` declarations in the repository. There are a few edge cases involving comments on `use` declarations that require care. This PR cleans up some clumsy comment cases, taking us a step closer to #125443 being able to merge.

r? ``@lqd``
2024-06-20 14:07:04 +02:00
Nicholas Nethercote b104fbec85 Add blank lines after module-level // comments.
Similar to the previous commit.
2024-06-20 09:23:20 +10:00
Nicholas Nethercote 665821cb60 Add blank lines after module-level //! comments.
Most modules have such a blank line, but some don't. Inserting the blank
line makes it clearer that the `//!` comments are describing the entire
module, rather than the `use` declaration(s) that immediately follows.
2024-06-20 09:23:20 +10:00
George Bateman 35c65a8c0c
Make Option::as_[mut_]slice const 2024-06-19 21:44:47 +01:00
Trevor Gross c4ddc863ae Print the tested value in int_log tests 2024-06-17 19:19:41 -05:00
Slanterns 76065f5b27
Stabilize error_in_core 2024-06-07 08:30:00 +08:00
Ross MacArthur 6a84995fae
Add function core::iter::chain
The addition of `core::iter::zip` (#82917) set a precedent for adding
plain functions for iterator adaptors. Adding `chain` makes it a little
easier to `chain` two iterators.

```
for (x, y) in chain(xs, ys) {}
// vs.
for (x, y) in xs.into_iter().chain(ys) {}
```
2024-06-04 10:51:05 +02:00
Jubilee 713cdcd803
Rollup merge of #121062 - RustyYato:f32-midpoint, r=the8472
Change f32::midpoint to upcast to f64

This has been verified by kani as a correct optimization

see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398

The new implementation is branchless and only differs in which NaN values are produced (if any are produced at all), which is fine to change. Aside from NaN handling, this implementation produces bitwise identical results to the original implementation.

Question: do we need a codegen test for this? I didn't add one, since the original PR #92048 didn't have any codegen tests.
2024-06-02 12:58:07 -07:00
RustyYato 849c5254af Change f32::midpoint to upcast to f64
This has been verified by kani as a correct optimization

see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398

The new implementation is branchless, and only differs in which NaN
values are produced (if any are produced at all). Which is fine to change.
Aside from NaN handling, this implementation produces bitwise identical
results to the original implementation.

The new implementation is gated on targets that have a fast 64-bit
floating point implementation in hardware, and on WASM.
2024-06-01 17:29:31 -07:00
Scott McMurray 0d63e6b608 [ACP 362] genericize ptr::from_raw_parts 2024-05-29 09:34:16 -07:00
Scott McMurray 459ce3f6bb Add an intrinsic for ptr::metadata 2024-05-28 09:28:51 -07:00
Matthias Krüger f775fffac5
Rollup merge of #125561 - Cyborus04:stabilize-slice-flatten, r=scottmcm
Stabilize `slice_flatten`
2024-05-26 13:43:07 +02:00
Cyborus 824ffd29ee
Stabilize slice_flatten 2024-05-26 01:26:24 -04:00
Matthias Krüger 80aea305d3
Rollup merge of #124667 - newpavlov:stabilize_div_duration, r=jhpratt
Stabilize `div_duration`

Closes #63139
2024-05-25 22:15:18 +02:00
Matthias Krüger 4af1c31fcf
Rollup merge of #125156 - zachs18:for_loops_over_fallibles_behind_refs, r=Nilstrieb
Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.

Extends the scope of the (warn-by-default) lint `for_loops_over_fallibles` from just `for _ in x` where `x: Option<_>/Result<_, _>` to also cover `x: &(mut) Option<_>/Result<_>`

```rs
fn main() {
    // Current lints
    for _ in Some(42) {}
    for _ in Ok::<_, i32>(42) {}

    // New lints
    for _ in &Some(42) {}
    for _ in &mut Some(42) {}
    for _ in &Ok::<_, i32>(42) {}
    for _ in &mut Ok::<_, i32>(42) {}

    // Should not lint
    for _ in Some(42).into_iter() {}
    for _ in Some(42).iter() {}
    for _ in Some(42).iter_mut() {}
    for _ in Ok::<_, i32>(42).into_iter() {}
    for _ in Ok::<_, i32>(42).iter() {}
    for _ in Ok::<_, i32>(42).iter_mut() {}
}
```

<details><summary><code>cargo build</code> diff</summary>

```diff
diff --git a/old.out b/new.out
index 84215aa..ca195a7 100644
--- a/old.out
+++ b/new.out
`@@` -1,33 +1,93 `@@`
 warning: for loop over an `Option`. This is more readably written as an `if let` statement
  --> src/main.rs:3:14
   |
 3 |     for _ in Some(42) {}
   |              ^^^^^^^^
   |
   = note: `#[warn(for_loops_over_fallibles)]` on by default
 help: to check pattern in a loop use `while let`
   |
 3 |     while let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 3 |     if let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~ ~~~

 warning: for loop over a `Result`. This is more readably written as an `if let` statement
  --> src/main.rs:4:14
   |
 4 |     for _ in Ok::<_, i32>(42) {}
   |              ^^^^^^^^^^^^^^^^
   |
 help: to check pattern in a loop use `while let`
   |
 4 |     while let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 4 |     if let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~ ~~~

-warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 2 warnings
-    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.04s
+warning: for loop over a `&Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:7:14
+  |
+7 |     for _ in &Some(42) {}
+  |              ^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+7 |     while let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+7 |     if let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:8:14
+  |
+8 |     for _ in &mut Some(42) {}
+  |              ^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+8 |     while let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+8 |     if let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&Result`. This is more readably written as an `if let` statement
+ --> src/main.rs:9:14
+  |
+9 |     for _ in &Ok::<_, i32>(42) {}
+  |              ^^^^^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+9 |     while let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+9 |     if let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Result`. This is more readably written as an `if let` statement
+  --> src/main.rs:10:14
+   |
+10 |     for _ in &mut Ok::<_, i32>(42) {}
+   |              ^^^^^^^^^^^^^^^^^^^^^
+   |
+help: to check pattern in a loop use `while let`
+   |
+10 |     while let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+   |
+10 |     if let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~ ~~~
+
+warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 6 warnings
+    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

```

</details>

-----

Question:

* ~~Currently, the article `an` is used for `&Option`, and `&mut Option` in the lint diagnostic, since that's what `Option` uses. Is this okay or should it be changed? (likewise, `a` is used for `&Result` and `&mut Result`)~~ The article `a` is used for `&Option`, `&mut Option`, `&Result`, `&mut Result` and (as before) `Result`. Only `Option` uses `an` (as before).

`@rustbot` label +A-lint
2024-05-23 07:41:17 +02:00
Lukas Bergdoll 1a6b0e410e Fix tidy errors 2024-05-16 17:08:55 +02:00
Lukas Bergdoll e49be415cd Replace sort implementations
- `slice::sort` -> driftsort
  https://github.com/Voultapher/sort-research-rs/blob/main/writeup/driftsort_introduction/text.md

- `slice::sort_unstable` -> ipnsort
  https://github.com/Voultapher/sort-research-rs/blob/main/writeup/ipnsort_introduction/text.md

Replaces the sort implementations with tailor made ones that strike a
balance of run-time, compile-time and binary-size, yielding run-time and
compile-time improvements. Regressing binary-size for `slice::sort`
while improving it for `slice::sort_unstable`. All while upholding the
existing soft and hard safety guarantees, and even extending the soft
guarantees, detecting strict weak ordering violations with a high chance
and reporting it to users via a panic.

In addition the implementation of `select_nth_unstable` is also adapted
as it uses `slice::sort_unstable` internals.
2024-05-16 17:08:55 +02:00
Scott McMurray facc0bb78e Rename flatten(_mut)as_flattened(_mut) 2024-05-15 23:39:33 -07:00
Zachary S 376a8c0ae5 Allow for_loops_over_fallibles in test that tests &mut Result as IntoIterator. 2024-05-15 13:51:16 -05:00
Артём Павлов [Artyom Pavlov] 1f1653c328 Stabilize div_duration 2024-05-03 17:31:55 +03:00
Mark Rousskov a64f941611 Step bootstrap cfgs 2024-05-01 22:19:11 -04:00
bors 4d570eea02 Auto merge of #123909 - dtolnay:utf8chunks, r=joboet
Stabilize `Utf8Chunks`

Pending FCP in https://github.com/rust-lang/rust/issues/99543.

This PR includes the proposed modification in https://github.com/rust-lang/libs-team/issues/190 as agreed in https://github.com/rust-lang/rust/issues/99543#issuecomment-2050406568.
2024-04-26 17:41:24 +00:00
David Tolnay 61cf00464e
Stabilize Utf8Chunks 2024-04-24 15:27:47 -07:00
Gary Guo 94c1920497 Stabilise inline_const 2024-04-24 13:12:25 +01:00
Guillaume Gomez 6a326d889a
Rollup merge of #124230 - reitermarkus:generic-nonzero-stable, r=dtolnay
Stabilize generic `NonZero`.

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

r? `@dtolnay`
2024-04-22 20:26:00 +02:00
Markus Reiter 33e68aadc9
Stabilize generic NonZero. 2024-04-22 18:48:47 +02:00
Scott McMurray de64ff76f8 Use it in the library, and InstSimplify it away in the easy places 2024-04-21 11:08:37 -07:00
Eduardo Sánchez Muñoz fb9e1f73b3 Stabilize (const_)slice_ptr_len and (const_)slice_ptr_is_empty_nonnull 2024-04-12 21:23:20 +02:00
Matthias Krüger cb7f1eec04
Rollup merge of #122291 - lilasta:stabilize_const_location_fields, r=dtolnay
Stabilize `const_caller_location` and `const_location_fields`

Closes #102911. Closes #76156.

tests: [library/core/tests/panic/location.rs](3521a2f2f3/library/core/tests/panic/location.rs)

API:
```rust
// core::panic::location
impl Location {
    pub const fn caller() -> &'static Location<'static>;
    pub const fn file(&self) -> &str;
    pub const fn line(&self) -> u32;
    pub const fn column(&self) -> u32;
}
```
2024-04-06 13:00:05 +02:00
Jacob Pratt de2cb0d76c
Rollup merge of #123206 - stepancheg:pointee-metadata-freeze, r=Amanieu
Require Pointee::Metadata to be Freeze

So pointee metadata can be used in anonymous statics.

This is prerequisite for implementing ThinBox without allocation for ZST.

See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488

r? joboet
2024-04-04 21:16:55 -04:00
bors a77322c16f Auto merge of #118310 - scottmcm:three-way-compare, r=davidtwco
Add `Ord::cmp` for primitives as a `BinOp` in MIR

Update: most of this OP was written months ago.  See https://github.com/rust-lang/rust/pull/118310#issuecomment-2016940014 below for where we got to recently that made it ready for review.

---

There are dozens of reasonable ways to implement `Ord::cmp` for integers using comparison, bit-ops, and branches.  Those differences are irrelevant at the rust level, however, so we can make things better by adding `BinOp::Cmp` at the MIR level:

1. Exactly how to implement it is left up to the backends, so LLVM can use whatever pattern its optimizer best recognizes and cranelift can use whichever pattern codegens the fastest.
2. By not inlining those details for every use of `cmp`, we drastically reduce the amount of MIR generated for `derive`d `PartialOrd`, while also making it more amenable to MIR-level optimizations.

Having extremely careful `if` ordering to μoptimize resource usage on broadwell (#63767) is great, but it really feels to me like libcore is the wrong place to put that logic.  Similarly, using subtraction [tricks](https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign) (#105840) is arguably even nicer, but depends on the optimizer understanding it (https://github.com/llvm/llvm-project/issues/73417) to be practical.  Or maybe [bitor is better than add](https://discourse.llvm.org/t/representing-in-ir/67369/2?u=scottmcm)?  But maybe only on a future version that [has `or disjoint` support](https://discourse.llvm.org/t/rfc-add-or-disjoint-flag/75036?u=scottmcm)?  And just because one of those forms happens to be good for LLVM, there's no guarantee that it'd be the same form that GCC or Cranelift would rather see -- especially given their very different optimizers.  Not to mention that if LLVM gets a spaceship intrinsic -- [which it should](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Suboptimal.20inlining.20in.20std.20function.20.60binary_search.60/near/404250586) -- we'll need at least a rustc intrinsic to be able to call it.

As for simplifying it in Rust, we now regularly inline `{integer}::partial_cmp`, but it's quite a large amount of IR.  The best way to see that is with 8811efa88b (diff-d134c32d028fbe2bf835fef2df9aca9d13332dd82284ff21ee7ebf717bfa4765R113) -- I added a new pre-codegen MIR test for a simple 3-tuple struct, and this PR change it from 36 locals and 26 basic blocks down to 24 locals and 8 basic blocks.  Even better, as soon as the construct-`Some`-then-match-it-in-same-BB noise is cleaned up, this'll expose the `Cmp == 0` branches clearly in MIR, so that an InstCombine (#105808) can simplify that to just a `BinOp::Eq` and thus fix some of our generated code perf issues.  (Tracking that through today's `if a < b { Less } else if a == b { Equal } else { Greater }` would be *much* harder.)

---

r? `@ghost`
But first I should check that perf is ok with this
~~...and my true nemesis, tidy.~~
2024-04-02 19:21:44 +00:00
Stepan Koltsov 8f5a28e0aa Require Pointee::Metadata to be Freeze
So pointee metadata can be used in anonymous statics.

This is prerequisite for implementing ThinBox without allocation for
ZST.

See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488
2024-03-31 03:35:17 +01:00
bors 1aedc9640c Auto merge of #123181 - stepancheg:pointee-metadata-debug, r=the8472,Amanieu
Require Debug for Pointee::Metadata

Useful for debugging.
2024-03-31 00:09:41 +00:00
George Bateman 3855b8bb60
Make {integer}::from_str_radix constant 2024-03-30 12:43:58 +00:00
Aria Beingessner ea92faec49 stabilize ptr.is_aligned, move ptr.is_aligned_to to a new feature gate
This is an alternative to #121920
2024-03-29 19:59:46 -04:00
Stepan Koltsov b110cb3dc6 Require Debug for Pointee::Metadata
Useful for debugging
2024-03-29 03:53:29 +00:00
Scott McMurray c59e93c753 Address PR feedback 2024-03-24 17:42:35 -07:00
Scott McMurray 3da115a93b Add+Use mir::BinOp::Cmp 2024-03-23 23:23:41 -07:00
lilasta d324d6de0e Stabilize const_caller_location and const_location_fields 2024-03-21 22:19:57 +09:00
Mark Rousskov 02f1930595 step cfgs 2024-03-20 08:49:13 -04:00
Yotam Ofek d0c0887498 Add as_(mut_)ptr and as_(mut_)slice to raw array pointers 2024-03-16 20:15:30 +00:00
The 8472 be33586adc fix unsoundness in Step::forward_unchecked for signed integers 2024-03-14 00:57:02 +01:00
Andrew Wock 0a0074980f Implement MaybeUninit::fill{,_with,_from}
ACP: rust-lang/libs-team#156

Signed-off-by: Andrew Wock <ajwock@gmail.com>
2024-03-05 15:27:35 -05:00
bors b0d3e04ca9 Auto merge of #120393 - Urgau:rfc3373-non-local-defs, r=WaffleLapkin
Implement RFC 3373: Avoid non-local definitions in functions

This PR implements [RFC 3373: Avoid non-local definitions in functions](https://github.com/rust-lang/rust/issues/120363).
2024-02-25 19:11:06 +00:00