Commit Graph

3720 Commits

Author SHA1 Message Date
Dylan DPC 3c35da224b
Rollup merge of #99070 - tamird:update-tracking-issue, r=RalfJung
Update integer_atomics tracking issue

Updates #32976.
Updates #99069.

r? ``@RalfJung``
2022-07-09 11:28:09 +05:30
Tamir Duberstein a491d4582d
Update integer_atomics tracking issue
Updates #32976.
Updates #99069.
2022-07-08 17:52:04 -04:00
Jane Lusby 0715616b51 add rt flag to allowed internal unstable for RustcEncodable/Decodable 2022-07-08 21:18:15 +00:00
Jane Lusby b55453dbad add opt in attribute for stable-in-unstable items 2022-07-08 21:18:15 +00:00
Jane Losare-Lusby d68cb1f9a3 revert changes to unicode stability 2022-07-08 21:18:15 +00:00
Jane Lusby e7fe5456c5 Support unstable moves via stable in unstable items 2022-07-08 21:18:13 +00:00
Matthias Krüger 9c6bcb60f3
Rollup merge of #98718 - yoshuawuyts:stabilize-into-future, r=yaahc
Stabilize `into_future`

https://github.com/rust-lang/rust/issues/67644 has been labeled with [S-tracking-ready-to-stabilize](https://github.com/rust-lang/rust/labels/S-tracking-ready-to-stabilize) - which mentions someone needs to file a stabilization PR. So hence this PR!  Thanks!

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

r? ``@joshtriplett``
2022-07-08 08:00:37 +02:00
Oli Scherer 2a899dc1cf `UnsafeCell` now has no niches, ever. 2022-07-07 10:46:22 +00:00
Guillaume Gomez 77ec591727
Rollup merge of #98939 - GuillaumeGomez:rustdoc-disamb-impls, r=notriddle
rustdoc: Add more semantic information to impl IDs

Take over of #92745.

I fixed the last remaining issue for the links in the sidebar (mentioned by `@jsha)` and fixed the few links broken in the std/core docs.

cc `@camelid`
r? `@notriddle`
2022-07-06 20:43:27 +02:00
Guillaume Gomez 4755173cf6
Rollup merge of #96935 - thomcc:atomicptr-strict-prov, r=dtolnay
Allow arithmetic and certain bitwise ops on AtomicPtr

This is mainly to support migrating from `AtomicUsize`, for the strict provenance experiment.

This is a pretty dubious set of APIs, but it should be sufficient to allow code that's using `AtomicUsize` to manipulate a tagged pointer atomically. It's under a new feature gate, `#![feature(strict_provenance_atomic_ptr)]`, but I'm not sure if it needs its own tracking issue. I'm happy to make one, but it's not clear that it's needed.

I'm unsure if it needs changes in the various non-LLVM backends. Because we just cast things to integers anyway (and were already doing so), I doubt it.

API change proposal: https://github.com/rust-lang/libs-team/issues/60

Fixes #95492
2022-07-06 20:43:23 +02:00
Guillaume Gomez 53db831d62 Fix links in std/core documentation 2022-07-05 21:33:39 +02:00
Nick Cameron 0c72be3e1a core::any: replace some unstable generic types with impl Trait
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-07-05 15:06:31 +01:00
Dylan DPC 8fa1ed8f12
Rollup merge of #97712 - RalfJung:untyped, r=scottmcm
ptr::copy and ptr::swap are doing untyped copies

The consensus in https://github.com/rust-lang/rust/issues/63159 seemed to be that these operations should be "untyped", i.e., they should treat the data as raw bytes, should work when these bytes violate the validity invariant of `T`, and should exactly preserve the initialization state of the bytes that are being copied. This is already somewhat implied by the description of "copying/swapping size*N bytes" (rather than "N instances of `T`").

The implementations mostly already work that way (well, for LLVM's intrinsics the documentation is not precise enough to say what exactly happens to poison, but if this ever gets clarified to something that would *not* perfectly preserve poison, then I strongly assume there will be some way to make a copy that *does* perfectly preserve poison). However, I had to adjust `swap_nonoverlapping`; after ``@scottmcm's`` [recent changes](https://github.com/rust-lang/rust/pull/94212), that one (sometimes) made a typed copy. (Note that `mem::swap`, which works on mutable references, is unchanged. It is documented as "swapping the values at two mutable locations", which to me strongly indicates that it is indeed typed. It is also safe and can rely on `&mut T` pointing to a valid `T` as part of its safety invariant.)

On top of adding a test (that will be run by Miri), this PR then also adjusts the documentation to indeed stably promise the untyped semantics. I assume this means the PR has to go through t-libs (and maybe t-lang?) FCP.

Fixes https://github.com/rust-lang/rust/issues/63159
2022-07-05 16:04:31 +05:30
5225225 5f5ca88958 Add size assert in transmute_copy 2022-07-03 10:46:20 +01:00
bors ada8c80bed Auto merge of #98673 - pietroalbini:pa-bootstrap-update, r=Mark-Simulacrum
Bump bootstrap compiler

r? `@Mark-Simulacrum`
2022-07-03 06:55:50 +00:00
Ben Kimock 7919e4208b Fix slice::ChunksMut aliasing 2022-07-03 00:15:15 -04:00
Pietro Albini 6b2d3d5f3c
update cfg(bootstrap)s 2022-07-01 15:48:23 +02:00
Thom Chiovoloni e65ecee90e
Rename AtomicPtr::fetch_{add,sub}{,_bytes} 2022-07-01 06:21:19 -07:00
Thom Chiovoloni 2f872afdb5
Allow arithmetic and certain bitwise ops on AtomicPtr
This is mainly to support migrating from AtomicUsize, for the strict
provenance experiment.

Fixes #95492
2022-07-01 06:21:18 -07:00
bors ca1e68b322 Auto merge of #98730 - matthiaskrgr:rollup-2c4d4x5, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #97629 ([core] add `Exclusive` to sync)
 - #98503 (fix data race in thread::scope)
 - #98670 (llvm-wrapper: adapt for LLVMConstExtractValue removal)
 - #98671 (Fix source sidebar bugs)
 - #98677 (For diagnostic information of Boolean, remind it as use the type: 'bool')
 - #98684 (add test for 72793)
 - #98688 (interpret: add From<&MplaceTy> for PlaceTy)
 - #98695 (use "or pattern")
 - #98709 (Remove unneeded methods declaration for old web browsers)
 - #98717 (get rid of tidy 'unnecessarily ignored' warnings)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-07-01 11:09:35 +00:00
Matthias Krüger 0e71d1f237
Rollup merge of #97629 - guswynn:exclusive_struct, r=m-ou-se
[core] add `Exclusive` to sync

(discussed here: https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Adding.20.60SyncWrapper.60.20to.20std)

`Exclusive` is a wrapper that exclusively allows mutable access to the inner value if you have exclusive access to the wrapper. It acts like a compile time mutex, and hold an unconditional `Sync` implementation.

## Justification for inclusion into std
- This wrapper unblocks actual problems:
  - The example that I hit was a vector of `futures::future::BoxFuture`'s causing a central struct in a script to be non-`Sync`. To work around it, you either write really difficult code, or wrap the futures in a needless mutex.
- Easy to maintain: this struct is as simple as a wrapper can get, and its `Sync` implementation has very clear reasoning
- Fills a gap: `&/&mut` are to `RwLock` as `Exclusive` is to `Mutex`

## Public Api
```rust
// core::sync
#[derive(Default)]
struct Exclusive<T: ?Sized> { ... }

impl<T: ?Sized> Sync for Exclusive {}

impl<T> Exclusive<T> {
    pub const fn new(t: T) -> Self;
    pub const fn into_inner(self) -> T;
}

impl<T: ?Sized> Exclusive<T> {
    pub const fn get_mut(&mut self) -> &mut T;
    pub const fn get_pin_mut(Pin<&mut self>) -> Pin<&mut T>;
    pub const fn from_mut(&mut T) -> &mut Exclusive<T>;
    pub const fn from_pin_mut(Pin<&mut T>) -> Pin<&mut Exclusive<T>>;
}

impl<T: Future> Future for Exclusive { ... }

impl<T> From<T> for Exclusive<T> { ... }
impl<T: ?Sized> Debug for Exclusive { ... }
```

## Naming
This is a big bikeshed, but I felt that `Exclusive` captured its general purpose quite well.

## Stability and location
As this is so simple, it can be in `core`. I feel that it can be stabilized quite soon after it is merged, if the libs teams feels its reasonable to add. Also, I don't really know how unstable feature work in std/core's codebases, so I might need help fixing them

## Tips for review
The docs probably are the thing that needs to be reviewed! I tried my best, but I'm sure people have more experience than me writing docs for `Core`

### Implementation:
The API is mostly pulled from https://docs.rs/sync_wrapper/latest/sync_wrapper/struct.SyncWrapper.html (which is apache 2.0 licenesed), and the implementation is trivial:
- its an unsafe justification for pinning
- its an unsafe justification for the `Sync` impl (mostly reasoned about by ````@danielhenrymantilla```` here: https://github.com/Actyx/sync_wrapper/pull/2)
- and forwarding impls, starting with derivable ones and `Future`
2022-06-30 19:55:50 +02:00
The 8472 3fcf84a68e clarify that ExactSizeIterator::len returns the remaining length 2022-06-30 19:45:36 +02:00
Yoshua Wuyts 992cfc1683 Stabilize `into_future` 2022-06-30 17:22:41 +02:00
Christopher Durham 344b99bd9f
nit
Co-authored-by: scottmcm <scottmcm@users.noreply.github.com>
2022-06-30 00:17:21 -04:00
Christopher Durham c4b4c64804 Revert isize::MAX changes to Layout helpers
The isize::MAX is enforced by the constructor; let it handle it.
2022-06-29 23:17:15 -04:00
Dylan DPC 375ab3e44f
Rollup merge of #98516 - dlrobertson:uefi_va_list, r=joshtriplett
library: fix uefi va_list type definition

For uefi the `va_list` should always be the void pointer variant.

Related to: https://github.com/rust-lang/rust/issues/44930
2022-06-29 17:59:34 +05:30
Dylan DPC 3f2ba25159
Rollup merge of #98479 - leocth:atomic-bool-fetch-not, r=joshtriplett
Add `fetch_not` method on `AtomicBool`

This PR adds a `fetch_not` method on `AtomicBool` performs the NOT operation on the inner value.
Internally, this just calls the `fetch_xor` method with the value `true`.

[See this IRLO discussion](https://internals.rust-lang.org/t/could-we-have-fetch-not-for-atomicbool-s/16881)
2022-06-29 17:59:32 +05:30
Mara Bos a898f41379 Only enable new cmpxchg memory orderings in cfg(not(bootstrap)).
(The bootstrap/beta compiler doesn't support them yet.)
2022-06-29 12:00:06 +02:00
Mara Bos a7434da9be Remove restrictions on compare-exchange memory ordering. 2022-06-29 12:00:06 +02:00
Dylan DPC 45740acd34
Rollup merge of #97423 - m-ou-se:memory-ordering-intrinsics, r=tmiasko
Simplify memory ordering intrinsics

This changes the names of the atomic intrinsics to always fully include their memory ordering arguments.

```diff
- atomic_cxchg
+ atomic_cxchg_seqcst_seqcst

- atomic_cxchg_acqrel
+ atomic_cxchg_acqrel_release

- atomic_cxchg_acqrel_failrelaxed
+ atomic_cxchg_acqrel_relaxed

// And so on.
```

- `seqcst` is no longer implied
- The failure ordering on chxchg is no longer implied in some cases, but now always explicitly part of the name.
- `release` is no longer shortened to just `rel`. That was especially confusing, since `relaxed` also starts with `rel`.
- `acquire` is no longer shortened to just `acq`, such that the names now all match the `std::sync::atomic::Ordering` variants exactly.
- This now allows for more combinations on the compare exchange operations, such as `atomic_cxchg_acquire_release`, which is necessary for #68464.
- This PR only exposes the new possibilities through unstable intrinsics, but not yet through the stable API. That's for [a separate PR](https://github.com/rust-lang/rust/pull/98383) that requires an FCP.

Suffixes for operations with a single memory order:

| Order   | Before       | After      |
|---------|--------------|------------|
| Relaxed | `_relaxed`   | `_relaxed` |
| Acquire | `_acq`       | `_acquire` |
| Release | `_rel`       | `_release` |
| AcqRel  | `_acqrel`    | `_acqrel`  |
| SeqCst  | (none)       | `_seqcst`  |

Suffixes for compare-and-exchange operations with two memory orderings:

| Success | Failure | Before                   | After              |
|---------|---------|--------------------------|--------------------|
| Relaxed | Relaxed | `_relaxed`               | `_relaxed_relaxed` |
| Relaxed | Acquire |                       | `_relaxed_acquire` |
| Relaxed | SeqCst  |                       | `_relaxed_seqcst`  |
| Acquire | Relaxed | `_acq_failrelaxed`       | `_acquire_relaxed` |
| Acquire | Acquire | `_acq`                   | `_acquire_acquire` |
| Acquire | SeqCst  |                       | `_acquire_seqcst`  |
| Release | Relaxed | `_rel`                   | `_release_relaxed` |
| Release | Acquire |                       | `_release_acquire` |
| Release | SeqCst  |                       | `_release_seqcst`  |
| AcqRel  | Relaxed | `_acqrel_failrelaxed`    | `_acqrel_relaxed`  |
| AcqRel  | Acquire | `_acqrel`                | `_acqrel_acquire`  |
| AcqRel  | SeqCst  |                       | `_acqrel_seqcst`   |
| SeqCst  | Relaxed | `_failrelaxed`           | `_seqcst_relaxed`  |
| SeqCst  | Acquire | `_failacq`               | `_seqcst_acquire`  |
| SeqCst  | SeqCst  | (none)                   | `_seqcst_seqcst`   |
2022-06-29 10:28:18 +05:30
Dylan DPC ff223ff297
Rollup merge of #98430 - camsteffen:flatten-refactor, r=joshtriplett
Refactor iter adapters with less macros

Just some code cleanup. Introduced a util `and_then_or_clear` for each of chain, flatten and fuse iter adapter impls. This reduces code nicely for flatten, but admittedly the other modules are more of a lateral move replacing macros with a function. But I think consistency across the modules and avoiding macros when possible is good.
2022-06-28 15:30:05 +05:30
Mara Bos 4982a59986 Rename/restructure memory ordering intrinsics. 2022-06-28 08:58:27 +02:00
Matthias Krüger f266821d8f
Rollup merge of #98587 - RalfJung:core-tests, r=thomcc
libcore tests: avoid int2ptr casts

We don't need any of these pointers to actually be dereferenceable so using `ptr::invalid` should be fine. And then we can run Miri with strict provenance enforcement on the tests.
2022-06-27 22:35:14 +02:00
Ralf Jung 8c977cfda8 libcore tests: avoid int2ptr casts 2022-06-27 13:30:44 -04:00
Wilfred Hughes 1c1ae78db7
Fix spelling in SAFETY comment
"can not" should be "cannot", and add punctuation.
2022-06-26 19:17:34 -07:00
Matthias Krüger e8a2e265b5
Rollup merge of #97908 - iago-lito:stabilize_nonzero_checked_ops_constness, r=scottmcm
Stabilize NonZero* checked operations constness.

Partial stabilization for #97547 (continued).
2022-06-26 19:47:02 +02:00
bors 788ddedb0d Auto merge of #98190 - nnethercote:optimize-derive-Debug-code, r=scottmcm
Improve `derive(Debug)`

r? `@ghost`
2022-06-26 15:00:04 +00:00
scottmcm 2339bb20a6
Update `since` to 1.64 (since we're after 1.63) 2022-06-26 08:45:53 +00:00
leocth 9c5ae20c59 forgot about the feature flag in the doctest 2022-06-26 10:49:05 +08:00
Dan Robertson 3b117c4823 library: fix uefi va_list type definition
For uefi the va_list should always be the void pointer variant.
2022-06-25 21:19:09 -04:00
leocth 0df7364cdf temporarily remove tests because I'm not sure if we need them 2022-06-26 00:06:50 +08:00
leocth 7d5f236c3d Add feature gate `#![atomic_bool_fetch_not]` 2022-06-25 18:31:01 +08:00
bors 1aabd8a4a6 Auto merge of #93700 - rossmacarthur:ft/iter-next-chunk, r=m-ou-se
Add `Iterator::next_chunk`

See also https://github.com/rust-lang/rust/pull/92393

### Prior art

-  [`Itertools::next_tuple()`](https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.next_tuple)

### Unresolved questions

- Should we also add `next_chunk_back` to `DoubleEndedIterator`?
- Should we rather call this `next_array()` or `next_array_chunk`?
2022-06-25 09:40:54 +00:00
leocth dcfe92e193 add `fetch_not` method on `AtomicBool` 2022-06-25 11:19:08 +08:00
Nicholas Nethercote 5b54363961 Optimize the code produced by `derive(Debug)`.
This commit adds new methods that combine sequences of existing
formatting methods.
- `Formatter::debug_{tuple,struct}_field[12345]_finish`, equivalent to a
  `Formatter::debug_{tuple,struct}` + N x `Debug{Tuple,Struct}::field` +
  `Debug{Tuple,Struct}::finish` call sequence.
- `Formatter::debug_{tuple,struct}_fields_finish` is similar, but can
  handle any number of fields by using arrays.

These new methods are all marked as `doc(hidden)` and unstable. They are
intended for the compiler's own use.

Special-casing up to 5 fields gives significantly better performance
results than always using arrays (as was tried in #95637).

The commit also changes the `Debug` deriving code to use these new methods. For
example, where the old `Debug` code for a struct with two fields would be like
this:
```
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
    match *self {
	Self {
	    f1: ref __self_0_0,
	    f2: ref __self_0_1,
	} => {
	    let debug_trait_builder = &mut ::core::fmt::Formatter::debug_struct(f, "S2");
	    let _ = ::core::fmt::DebugStruct::field(debug_trait_builder, "f1", &&(*__self_0_0));
	    let _ = ::core::fmt::DebugStruct::field(debug_trait_builder, "f2", &&(*__self_0_1));
	    ::core::fmt::DebugStruct::finish(debug_trait_builder)
	}
    }
}
```
the new code is like this:
```
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
    match *self {
	Self {
	    f1: ref __self_0_0,
	    f2: ref __self_0_1,
	} => ::core::fmt::Formatter::debug_struct_field2_finish(
	    f,
	    "S2",
	    "f1",
	    &&(*__self_0_0),
	    "f2",
	    &&(*__self_0_1),
	),
    }
}
```
This shrinks the code produced for `Debug` instances
considerably, reducing compile times and binary sizes.

Co-authored-by: Scott McMurray <scottmcm@users.noreply.github.com>
2022-06-24 09:40:15 +10:00
Gus Wynn 029f9aa3bf add tracking issue for exclusive 2022-06-23 08:52:13 -07:00
Cameron Steffen 6587dda39e Refactor iter adapters with less macros 2022-06-22 17:44:39 -05:00
Yuki Okushi 25b84491f7
Rollup merge of #97516 - RalfJung:atomics, r=joshtriplett
clarify how Rust atomics correspond to C++ atomics

``@cbeuw`` noted in https://github.com/rust-lang/miri/pull/1963 that the correspondence between C++ atomics and Rust atomics is not quite as obvious as one might think, since in Rust I can use `get_mut` to treat previously non-atomic data as atomic. However, I think using C++20 `atomic_ref`, we can establish a suitable relation between the two -- or do you see problems with that ``@cbeuw?`` (I recall you said there was some issue, but it was deep inside that PR and Github makes it impossible to find...)

Cc ``@thomcc;`` not sure whom else to ping for atomic memory model things.
2022-06-22 15:16:11 +09:00
Ralf Jung 4768bfc6ef
hedge our bets
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2022-06-21 16:54:54 -07:00
Yuki Okushi b20aff2b33
Rollup merge of #97269 - RalfJung:transmute, r=m-ou-se
adjust transmute const stabilization version

With 1.46, this became callable only in `const`/`static` items.

Only since 1.56 is this callable in `const fn`: [changelog](https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1560-2021-10-21)

Also see [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/transmute.20const.20fn.20stabilization).
2022-06-21 20:08:08 +09:00
Ross MacArthur bbdff1fff4
Add `Iterator::next_chunk` 2022-06-21 08:57:02 +02:00
bors 0887113991 Auto merge of #98307 - matthiaskrgr:rollup-rb3huha, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #98235 (Drop magic value 3 from code)
 - #98267 (Don't omit comma when suggesting wildcard arm after macro expr)
 - #98276 (Mention formatting macros when encountering `ArgumentV1` method in const)
 - #98296 (Add a link to the unstable book page on Generator doc comment)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-06-20 22:34:50 +00:00
Josh Triplett bded8fcfc0 Add `[f32]::sort_floats` and `[f64]::sort_floats`
It's inconvenient to sort a slice or Vec of floats, compared to sorting
integers. To simplify numeric code, add a convenience method to `[f32]`
and `[f64]` to sort them using `sort_unstable_by` with `total_cmp`.
2022-06-20 14:58:29 -07:00
Matthias Krüger dfa933d420
Rollup merge of #98296 - JohnTitor:generator-unstable-book-link, r=Dylan-DPC
Add a link to the unstable book page on Generator doc comment

This makes it easier to jump into the Generator section on the unstable book.

Signed-off-by: Yuki Okushi <jtitor@2k36.org>
2022-06-20 20:13:12 +02:00
Matthias Krüger 5eb7238928
Rollup merge of #98276 - compiler-errors:const-format-macro, r=oli-obk
Mention formatting macros when encountering `ArgumentV1` method in const

Also open to just closing this if it's overkill. There are a lot of other distracting error messages around, so maybe it's not worth fixing just this one.

Fixes #93665
2022-06-20 20:13:11 +02:00
bors 5750a6aa27 Auto merge of #93765 - zhangyunhao116:heapsort, r=m-ou-se
Optimize heapsort

The new implementation is about 10% faster than the previous one(sorting random 1000 items).
2022-06-20 18:09:30 +00:00
Yuki Okushi 51cc665b33
Add a link to the unstable book page on Generator doc comment
Signed-off-by: Yuki Okushi <jtitor@2k36.org>
2022-06-20 23:19:50 +09:00
Dylan DPC 625c929a9f
Rollup merge of #96719 - mbartlett21:patch-4, r=Dylan-DPC
Fix the generator example for `pin!()`

The previous generator example is not actually self-referential, since the reference is created after the yield.

CC #93178 (tracking issue)
2022-06-20 14:56:36 +02:00
Dylan DPC fd9ca0c25e
Rollup merge of #93080 - SkiFire13:itermut-as_mut_slice, r=m-ou-se
Implement `core::slice::IterMut::as_mut_slice` and `impl<T> AsMut<[T]> for IterMut<'_, T>`

As per [the zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/.60std.3A.3Aslice.3A.3AIterMut.3A.3Aas_mut_slice.60), the `AsMut` impl has been commented out, with a comment near the `#[unstable(...)]` to uncomment it when `as_mut_slice` gets stabilized.
2022-06-20 14:56:33 +02:00
zhangyunhao 98507f202d Optimize heapsort 2022-06-20 08:30:27 +00:00
Mara Bos c867529461
Show #![feature] in example. 2022-06-20 10:00:55 +02:00
Michael Goulet 5373d738e8 Mention formatting macros when encountering ArgumentV1::new in const 2022-06-19 20:18:08 -07:00
Yuki Okushi 761f83f683
Rollup merge of #98257 - kadiwa4:into_future_doc_typos, r=Dylan-DPC
Fix typos in `IntoFuture` docs
2022-06-20 07:37:43 +09:00
Yuki Okushi 9d4e08e725
Rollup merge of #95534 - jyn514:std-mem-copy, r=joshtriplett
Add `core::mem::copy` to complement `core::mem::drop`.

This is useful for combinators. I didn't add `clone` since you can already
use `Clone::clone` in its place; copy has no such corresponding function.
2022-06-20 07:37:40 +09:00
Joshua Nelson 9ac6277bad Add `core::mem::copy` to complement `core::mem::drop`.
This is useful for combinators. I didn't add `clone` since you can already
use `Clone::clone` in its place; copy has no such corresponding function.
2022-06-19 16:43:19 -05:00
KaDiWa4 f0144aea74
typos in `IntoFuture` docs 2022-06-19 17:13:48 +02:00
bors 5fb8a39266 Auto merge of #97367 - WaffleLapkin:stabilize_checked_slice_to_str_conv, r=dtolnay
Stabilize checked slice->str conversion functions

This PR stabilizes the following APIs as `const` functions in Rust 1.63:
```rust
// core::str

pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>;

impl Utf8Error {
    pub const fn valid_up_to(&self) -> usize;
    pub const fn error_len(&self) -> Option<usize>;
}
```

Note that the `from_utf8_mut` function is not stabilized as unique references (`&mut _`) are [unstable in const context].

FCP: https://github.com/rust-lang/rust/issues/91006#issuecomment-1134593095

[unstable in const context]: https://github.com/rust-lang/rust/issues/57349
2022-06-19 05:51:42 +00:00
Matthias Krüger f351f347b8
Rollup merge of #98165 - WaffleLapkin:once_things_renamings, r=m-ou-se
once cell renamings

This PR does the renamings proposed in https://github.com/rust-lang/rust/issues/74465#issuecomment-1153703128

- Move/rename `lazy::{OnceCell, Lazy}` to `cell::{OnceCell, LazyCell}`
- Move/rename `lazy::{SyncOnceCell, SyncLazy}` to `sync::{OnceLock, LazyLock}`

(I used `Lazy...` instead of `...Lazy` as it seems to be more consistent, easier to pronounce, etc)

```@rustbot``` label +T-libs-api -T-libs
2022-06-19 00:17:13 +02:00
Paolo Barbolini ce3b6f505e Expose iter::ByRefSized as unstable feature and use it 2022-06-18 00:03:54 +02:00
Yuki Okushi cf68fd7e8d
Rollup merge of #97675 - nvzqz:unsized-needs-drop, r=dtolnay
Make `std::mem::needs_drop` accept `?Sized`

This change attempts to make `needs_drop` work with types like `[u8]` and `str`.

This enables code in types like `Arc<T>` that was not possible before, such as https://github.com/rust-lang/rust/pull/97676.
2022-06-17 07:16:55 +09:00
Maybe Waffle 7c360dc117 Move/rename `lazy::{OnceCell, Lazy}` to `cell::{OnceCell, LazyCell}` 2022-06-16 19:53:59 +04:00
bors 6ec3993ef4 Auto merge of #97842 - notriddle:notriddle/tuple-docs, r=jsha,GuillaumeGomez
Improve the tuple and unit trait docs

* Reduce duplicate impls; show only the `(T,)` and include a sentence saying that there exists ones up to twelve of them.
* Show `Copy` and `Clone`.
* Show auto traits like `Send` and `Sync`, and blanket impls like `Any`.

Here's the new version:

* <https://notriddle.com/notriddle-rustdoc-test/std/primitive.tuple.html>
* <https://notriddle.com/notriddle-rustdoc-test/std/primitive.unit.html>
2022-06-16 11:13:30 +00:00
Yuki Okushi b91c4d5b45
Rollup merge of #98059 - tmiasko:inline-const-eval-select, r=Amanieu
Inline `const_eval_select`

To avoid circular link time dependency between core and compiler
builtins when building with `-Zshare-generics`.

r? ```@Amanieu```
2022-06-16 07:24:41 +09:00
Michael Howell 2bbf44f655 rustdoc: change "variadic tuple" notation to look less like real syntax 2022-06-14 12:21:38 -07:00
Meziu 4e808f87cc
Horizon OS STD support
Co-authored-by: Ian Chamberlain <ian.h.chamberlain@gmail.com>
Co-authored-by: Mark Drobnak <mark.drobnak@gmail.com>
2022-06-13 20:44:39 -07:00
Tomasz Miąsko 8a8404bc2b Inline `const_eval_select`
To avoid circular link time dependency between core and compiler
builtins when building with `-Zshare-generics`.
2022-06-13 17:10:40 +02:00
Imbolc acda8866cc
Document an edge case of `str::split_once` 2022-06-13 13:35:49 +03:00
Michael Goulet 5dccf4e5fc
Rollup merge of #97950 - eggyal:issue-97945, r=Dylan-DPC
Clarify `#[derive(PartialEq)]` on enums

Fixes #97945
2022-06-12 17:35:41 -07:00
Dylan DPC a24ca03660
Rollup merge of #97992 - m-ou-se:stabilize-scoped-threads, r=joshtriplett
Stabilize scoped threads.

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

FCP finished here: https://github.com/rust-lang/rust/issues/93203#issuecomment-1152249466
2022-06-12 12:14:29 +02:00
Michael Howell 36fb094d25 Add docs to `maybe_tuple_doc!` 2022-06-11 21:47:03 -07:00
Michael Howell 22c39aa835 Update library/core/src/primitive_docs.rs 2022-06-11 21:45:23 -07:00
bors c08b235a5c Auto merge of #97996 - matthiaskrgr:rollup-bvbjlid, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #97904 (Small grammar fix in the compile_error documentation)
 - #97943 (line 1352, change `self` to `*self`, other to `*other`)
 - #97969 (Make -Cpasses= only apply to pre-link optimization)
 - #97990 (Add more eslint checks)
 - #97994 (feat(fix): update some links in `hir.rs`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-06-11 17:49:22 +00:00
Michael Howell 28bd1a4847 docs: make all the variadic impls use `(T, ...)` exactly 2022-06-11 10:32:39 -07:00
Michael Howell c1487550ca Add test case for #trait-implementations-1 link 2022-06-11 09:54:23 -07:00
Michael Howell 3fd16648fe Re-add explicit list of traits to tuple docs, with limit notes 2022-06-11 09:54:23 -07:00
Michael Howell 090c68ba5c Use relative path for addressing things in rust-lang/rust
Co-authored-by: Jacob Hoffman-Andrews <github@hoffman-andrews.com>
2022-06-11 09:54:23 -07:00
Michael Howell 9b31323b8f Fix incorrectly spelled "variadic" 2022-06-11 09:54:20 -07:00
Matthias Krüger 39de4e4b6f
Rollup merge of #97943 - Warrenren:master, r=Dylan-DPC
line 1352, change `self` to `*self`, other to `*other`

The current code will not results bug, but it difficult to understand. These code result to call &f32::partial_cmp(), and the performance will be lower than the changed code. I'm not sure why the current code don't use (*self) (*other), if you have some idea, please let me know.
2022-06-11 18:05:33 +02:00
Matthias Krüger 4b7ec84c31
Rollup merge of #97904 - est31:master, r=Dylan-DPC
Small grammar fix in the compile_error documentation
2022-06-11 18:05:32 +02:00
Mara Bos ae0a533b0b Stabilize scoped threads. 2022-06-11 15:01:52 +02:00
Benjamin Herr 74ef14830f Fix typos in Provider API docs 2022-06-10 20:58:27 -07:00
Warrenren 9e1e476186
Update cmp.rs
line 1352, delete parentheses for reviewers asking for it.
2022-06-11 11:04:27 +08:00
Matthias Krüger 30a8903821
Rollup merge of #97940 - GuillaumeGomez:relative-link, r=Dylan-DPC
Use relative links instead of linking to doc.rust-lang.org when possible

Part of https://github.com/rust-lang/rust/issues/97918.
2022-06-10 22:32:31 +02:00
Alan Egerton 7bbf914078
Clarify `#[derive(PartialEq)]` on enums
Fixes #97945
2022-06-10 16:26:00 +01:00
Warrenren 5e9e73cc9f
line 1352, change self to (*self), other to (*other)
The current code will not results bug, but it difficult to understand. These code result to call &f32::partial_cmp(), and the performance will be lower than the changed code. I'm not sure why the current code don't use (*self) (*other), if you have some idea, please let me know.
2022-06-10 19:08:03 +08:00
Guillaume Gomez 28ca3bdeb2 Use relative links instead of linking to doc.rust-lang.org when possible 2022-06-10 11:57:53 +02:00
Yuki Okushi a652a4303f
Rollup merge of #97876 - yoshuawuyts:into-future-docs, r=JohnTitor,yaahc
update docs for `std::future::IntoFuture`

Ref https://github.com/rust-lang/rust/issues/67644.

This updates the docs for `IntoFuture` providing a bit more guidance on how to use it. Thanks!
2022-06-10 17:22:29 +09:00
bors e9aff9c42c Auto merge of #91970 - nrc:provide-any, r=scottmcm
Add the Provider api to core::any

This is an implementation of [RFC 3192](https://github.com/rust-lang/rfcs/pull/3192) ~~(which is yet to be merged, thus why this is a draft PR)~~. It adds an API for type-driven requests and provision of data from trait objects. A primary use case is for the `Error` trait, though that is not implemented in this PR. The only major difference to the RFC is that the functionality is added to the `any` module, rather than being in a sibling `provide_any` module (as discussed in the RFC thread).

~~Still todo: improve documentation on items, including adding examples.~~

cc `@yaahc`
2022-06-10 01:10:59 +00:00
est31 97519bd202 Grammar fix in the compile_error documentation 2022-06-09 12:40:10 +02:00
Iago-lito 69e8e7e73b Stabilize NonZero* checked operations constness. 2022-06-09 09:17:06 +02:00
Iago-lito 5823d7b563 Partial stabilization of "nonzero_unchecked_ops". 2022-06-09 09:13:57 +02:00
Michael Howell 9f6dcceef0 Fix bootstrap attr 2022-06-08 20:06:54 -07:00
Michael Howell 85b0c2ffbb rustdoc: fixed messed-up rustdoc auto trait impls
Before:

    impl<T, U> UnwindSafe for (T, ...) where
        T: UnwindSafe,
        U: UnwindSafe,

After:

    impl<T> UnwindSafe for (T, ...) where
        T: UnwindSafe,
2022-06-08 19:51:54 -07:00
Michael Howell 6950f144cf rustdoc: show tuple impls as `impl Trait for (T, ...)`
This commit adds a new unstable attribute, `#[doc(tuple_varadic)]`, that
shows a 1-tuple as `(T, ...)` instead of just `(T,)`, and links to a section
in the tuple primitive docs that talks about these.
2022-06-08 19:26:51 -07:00
Michael Goulet 1577838151
Rollup merge of #97871 - ChayimFriedman2:vec-iterator-unimplemented, r=compiler-errors
Suggest using `iter()` or `into_iter()` for `Vec`

We cannot do that for `&Vec` because `#[rustc_on_unimplemented]` is limited (it does not clean generic instantiation for references, only for ADTs).

`@rustbot` label +A-diagnostics
2022-06-08 13:32:22 -07:00
Yoshua Wuyts a4c455080c update docs for `std::future::IntoFuture` 2022-06-08 15:21:16 +02:00
Yuki Okushi 2b58e6314a
Stabilize `const_intrinsic_copy` 2022-06-08 20:17:28 +09:00
Chayim Refael Friedman 456f1ffe12 Suggest using `iter()` or `into_iter()` for `Vec`
We cannot do that for `&Vec` because `#[rustc_on_unimplemented]` is limited (it does not clean generic instantiation for references, only for ADTs).
2022-06-08 11:09:08 +00:00
Dylan DPC 1660b4b70c
Rollup merge of #97851 - saethlin:use-repr-c, r=thomcc
Use repr(C) when depending on struct layout in ptr tests

The test depends on the layout of this struct `Pair`, so it should use `repr(C)` instead of the default `repr(Rust)`.
2022-06-08 07:37:33 +02:00
Ben Kimock 5dd5244423 Use repr(C) when depending on struct layout in ptr tests 2022-06-07 19:24:09 -04:00
Gus Wynn 63d1c86230 [core] add Exclusive to sync 2022-06-07 13:10:50 -07:00
Michael Howell 7a93567005 docs: show Clone and Copy on () doc pages 2022-06-07 12:12:49 -07:00
Michael Howell 1e6a85789e rustdoc: show auto/blanket docs for tuple and unit 2022-06-07 11:25:00 -07:00
Michael Howell 9940ed0805 docs: clean up trait docs for tuples 2022-06-07 11:24:57 -07:00
Dylan DPC a9c4a7e1aa
Rollup merge of #95948 - Nilstrieb:improve-cstr-safety-docs, r=RalfJung
Improve the safety docs for `CStr`

Namely, the two functions `from_ptr` and `from_bytes_with_nul_unchecked`.
Before, these functions didn't state the requirements clearly enough,
and I was not immediately able to find them like for other functions.

This doesn't change the content of the docs, but simply rewords them for
clarity.

note: I'm not entirely sure about the '`ptr` must be valid for reads of `u8`.', there might be room for improvement for this (and maybe for the other docs as well 😄)
2022-06-07 17:25:42 +02:00
Nilstrieb 0dda42bc14 Improve the safety docs for `CStr`
Namely, the two functions `from_ptr` and `from_bytes_with_nul_unchecked`.
Before, this functions didn't state the requirements clearly enough,
and I was not immediately able to find them like for other functions.

This doesn't change the content of the docs, but simply rewords them for
clarity.
2022-06-07 16:42:26 +02:00
Nick Cameron 66290109bb Address reviewer comments
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:19:18 +01:00
Nick Cameron 843f90cbb7 Add some more tests
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:14 +01:00
Nick Cameron 2e0ca2537f Add tracking issue number
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:14 +01:00
Nick Cameron e82368d6fc Add examples to docs
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:13 +01:00
Nick Cameron 17730e66f6 Update docs
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:13 +01:00
Nick Cameron 57d027d23a Modify the signature of the request_* methods so that trait_upcasting is not required
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:13 +01:00
Nick Cameron bb5db85f74 Add the Provider api to core::any
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:13 +01:00
Matthias Krüger 1bf1932453
Rollup merge of #97764 - RalfJung:strict, r=dtolnay
use strict provenance APIs

The stdlib was adjusted to avoid bare int2ptr casts, but recently some casts of that sort have sneaked back in. Let's fix that. :)
2022-06-06 08:37:04 +02:00
bors 760237ff78 Auto merge of #97710 - RalfJung:ptr-addr, r=thomcc
implement ptr.addr() via transmute

As per the discussion in https://github.com/rust-lang/unsafe-code-guidelines/issues/286, the semantics for ptr-to-int transmutes that we are going with for now is to make them strip provenance without exposing it. That's exactly what `ptr.addr()` does! So we can implement `ptr.addr()` via `transmute`. This also means that once https://github.com/rust-lang/rust/pull/97684 lands, Miri can distinguish `ptr.addr()` from `ptr.expose_addr()`, and the following code will correctly be called out as having UB (if permissive provenance mode is enabled, which will become the default once the [implementation is complete](https://github.com/rust-lang/miri/issues/2133)):

```rust
fn main() {
    let x: i32 = 3;
    let x_ptr = &x as *const i32;

    let x_usize: usize = x_ptr.addr();
    // Cast back an address that did *not* get exposed.
    let ptr = std::ptr::from_exposed_addr::<i32>(x_usize);
    assert_eq!(unsafe { *ptr }, 3); //~ ERROR Undefined Behavior: dereferencing pointer failed
}
```

This completes the Miri implementation of the new distinctions introduced by strict provenance. :)

Cc `@Gankra` -- for now I left in your `FIXME(strict_provenance_magic)` saying these should be intrinsics, but I do not necessarily agree that they should be. Or if we have an intrinsic, I think it should behave exactly like the `transmute` does, which makes one wonder why the intrinsic should be needed.
2022-06-06 01:03:26 +00:00
Ralf Jung 4a41c35742 use strict provenance APIs 2022-06-05 11:50:48 -04:00
Ralf Jung cb7cd97641 promise that ptr::copy and ptr::swap are doing untyped copies 2022-06-05 10:09:42 -04:00
Ralf Jung b96d1e45f1 change ptr::swap methods to do untyped copies 2022-06-05 10:09:41 -04:00
Ralf Jung 4291332175 implement ptr.addr() via transmute 2022-06-03 16:45:35 -04:00
Ralf Jung 4990021082 test const_copy to make sure bytewise pointer copies are working 2022-06-03 09:20:42 -04:00
Dylan DPC 025cf96615
Rollup merge of #97366 - WaffleLapkin:stabilize_array_slice_from_ref, r=dtolnay
Stabilize `{slice,array}::from_ref`

This PR stabilizes the following APIs as `const` functions in Rust `1.63`:
```rust
// core::array
pub const fn from_ref<T>(s: &T) -> &[T; 1];

// core::slice
pub const fn from_ref<T>(s: &T) -> &[T];
```

Note that the `mut` versions are not stabilized as unique references (`&mut _`) are [unstable in const context].

FCP: https://github.com/rust-lang/rust/issues/90206#issuecomment-1134586665

r? rust-lang/libs-api `@rustbot` label +T-libs-api -T-libs

[unstable in const context]: https://github.com/rust-lang/rust/issues/57349
2022-06-03 11:18:23 +02:00
Nikolai Vazquez fd38f663cd Make `std::mem::needs_drop` accept `?Sized` 2022-06-03 03:28:19 -04:00
Dylan DPC 0b2d48e5af
Rollup merge of #97420 - WaffleLapkin:no_oxford_casts_qqq, r=Mark-Simulacrum
Be a little nicer with casts when formatting `fn` pointers

This removes a `fn(...) -> ...` -> `usize` -> `*const ()` -> `usize` cast. cc #95489.
2022-06-02 15:26:57 +02:00
Yuki Okushi 3ed9bbe970
Rollup merge of #95594 - the8472:raw_slice_methods, r=yaahc
Additional `*mut [T]` methods

Split out from #94247

This adds the following methods to raw slices that already exist on regular slices

* `*mut [T]::is_empty`
* `*mut [T]::split_at_mut`
* `*mut [T]::split_at_mut_unchecked`

These methods reduce the amount of unsafe code needed to migrate `ChunksMut` and related iterators
to raw slices (#94247)

r? `@m-ou-se`
2022-06-02 06:44:25 +09:00
Yuki Okushi e1d2e65463
Rollup merge of #97498 - ijchen:master, r=Mark-Simulacrum
Corrected EBNF grammar for from_str

Hello! This is my first time contributing to an open-source project. I'm excited to have the chance to contribute to the rust community 🥳

I noticed an issue with the documentation for `from_str` in `f32` and `f64`. It states that "All strings that adhere to the following [EBNF](https://www.w3.org/TR/REC-xml/#sec-notation) grammar when lowercased will result in an `Ok` being returned. I believe this is incorrect for the string `"."`, which is valid for the given EBNF grammar, but does not result in an `Ok` being returned ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=09f891aa87963a56d3b0d715d8cbc2b4)). I have simplified the grammar in a way which fixes that, but is otherwise identical.

Previously, the `Number` part of the EBNF grammar had an option for `'.' Digit*`, which would include the string `"."`. This is not valid, and does not return an Ok as stated. The corrected version removes this, and still allows for the `'.' Digit+` case with the already existing `Digit* '.' Digit+` case.
2022-06-01 23:36:49 +09:00
Maybe Waffle 2aef6c5436 Fixup feature name to be more consistent with others
`slice_from_mut_ptr_range_const` -> `const_slice_from_mut_ptr_range`,
we usually have `const` in the front.
2022-05-31 23:12:28 +04:00
bors 0a43923a86 Auto merge of #97419 - WaffleLapkin:const_from_ptr_range, r=oli-obk
Make `from{,_mut}_ptr_range` const

This PR makes the following APIs `const`:
```rust
// core::slice

pub const unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T];
pub const unsafe fn from_mut_ptr_range<'a, T>(range: Range<*mut T>) -> &'a mut [T];
```

Tracking issue: #89792.
Feature for `from_ptr_range` as a `const fn`: `slice_from_ptr_range_const`.
Feature for `from_mut_ptr_range` as a `const fn`: `slice_from_mut_ptr_range_const`.

r? `@oli-obk`
2022-05-31 14:55:33 +00:00
bors dcbd5f5134 Auto merge of #97526 - Nilstrieb:unicode-is-printable-fastpath, r=joshtriplett
Add unicode fast path to `is_printable`

Before, it would enter the full expensive check even for normal ascii characters. Now, it skips the check for the ascii characters in `32..127`. This range was checked manually from the current behavior.

I ran the `tracing` test suite in miri, and it was really slow. I looked at a profile, and miri spent most of the time in `core::char::methods::escape_debug_ext`, where half of that was dominated by `core::unicode::printable::is_printable`. So I optimized it here.

The tracing profile:
![The tracing profile](https://user-images.githubusercontent.com/48135649/170883650-23876e7b-3fd1-4e8b-9001-47672e06d914.svg)
2022-05-31 09:34:00 +00:00
Nilstrieb 3358a41acb Add unicode fast path to `is_printable`
Before, it would enter the full expensive check even for normal ascii
characters. Now, it skips the check for the ascii characters in
`32..127`. This range was checked manually from the current behavior.
2022-05-31 10:51:35 +02:00
Dylan DPC efd2519e10
Rollup merge of #97569 - thomcc:fill_with_isnt_memset, r=Amanieu
Remove `memset` alias from `fill_with`.

In https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Unsafe.20and.20Safe.20versions.20of.20APIs.20both.20getting.20the.20same.20alias/near/284413029 `@Amanieu` pointed out that we had this, which is not really right.

In our guidelines we say that we will "not add an alias for a function that's only somewhat similar or related", which applies here. Memset doesn't take a closure, not even conceptually.
2022-05-31 07:57:37 +02:00
Thom Chiovoloni de3ac3c3f8
Remove `memset` alias from `fill_with`. 2022-05-30 16:26:00 -07:00
Lukas e565bb0326 Update mut_ptr.rs 2022-05-31 00:41:39 +02:00
Lukas 7a9c13985e
Update intrinsics.rs 2022-05-30 22:38:29 +00:00
Dylan DPC a352ad500d
Rollup merge of #97545 - thomcc:sip-comment-safety, r=Dylan-DPC
Reword safety comments in core/hash/sip.rs

In https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/Is.20there.20any.20way.20to.20soundly.20do.20a.20masked.20out-of-bounds.20read.3F/near/284329248 it came up that this is using an atypical (and somewhat vague) phrasing of the safety requirement, so this slightly rewords it.
2022-05-30 14:33:53 +02:00
Dylan DPC 0ed320bdb9
Rollup merge of #97494 - est31:remove_box_alloc_tests, r=Dylan-DPC
Use Box::new() instead of box syntax in library tests

The tests inside `library/*` have no reason to use `box` syntax as they have 0 performance relevance. Therefore, we can safely remove them (instead of having to use alternatives like the one in #97293).
2022-05-30 14:33:48 +02:00
Maybe Waffle 10ee6f8e06 Rename slice_from_ptr_range_const -> const_slice_from_ptr_range
This is in line with other `const fn` features.
2022-05-30 15:44:56 +04:00
Maybe Waffle 19caa8c89b Make `from{,_mut}_ptr_range` const
- `from_ptr_range` uses `#![feature(slice_from_ptr_range_const)]`
- `from_mut_ptr_range` uses `#![feature(slice_from_mut_ptr_range_const)]`
2022-05-30 15:44:55 +04:00
bors 5c780b98d1 Auto merge of #96964 - oli-obk:const_trait_mvp, r=compiler-errors
Replace `#[default_method_body_is_const]` with `#[const_trait]`

pulled out of #96077

related issues:  #67792 and #92158

cc `@fee1-dead`

This is groundwork to only allowing `impl const Trait` for traits that are marked with `#[const_trait]`. This is necessary to prevent adding a new default method from becoming a breaking change (as it could be a non-const fn).
2022-05-30 09:19:03 +00:00
Deadbeef 257f06587c Remove `#[default..]` and add `#[const_trait]` 2022-05-30 08:52:24 +00:00
Thom Chiovoloni eeacb4403c
Reword safety comments in core/hash/sip.rs 2022-05-30 01:06:08 -07:00
bors bef2b7cd1c Auto merge of #97214 - Mark-Simulacrum:stage0-bump, r=pietroalbini
Finish bumping stage0

It looks like the last time had left some remaining cfg's -- which made me think
that the stage0 bump was actually successful. This brings us to a released 1.62
beta though.

This now brings us to cfg-clean, with the exception of check-cfg-features in bootstrap;
I'd prefer to leave that for a separate PR at this time since it's likely to be more tricky.

cc https://github.com/rust-lang/rust/pull/97147#issuecomment-1132845061

r? `@pietroalbini`
2022-05-29 16:28:21 +00:00
Ralf Jung f020fc08a5 clarify how Rust atomics correspond to C++ atomics 2022-05-29 13:29:36 +02:00
Maybe Waffle ac5c15d6be Remove `(fn(...) -> ...)` -> `usize` -> `*const ()` -> `usize` cast 2022-05-29 13:11:51 +04:00
est31 cdb8e64bc7 Use Box::new() instead of box syntax in core tests 2022-05-29 01:44:11 +02:00
Guillaume Gomez 774d7ced10
Rollup merge of #97482 - RalfJung:ptr-invalid, r=thomcc
ptr::invalid is not equivalent to a int2ptr cast

I just realized I forgot to update these docs when adding `from_exposed_addr`.
Right now the docs say `invalid` and `from_exposed_addr` are both equivalent to a cast, and that is clearly not what we want.

Cc ``@Gankra``
2022-05-29 01:12:33 +02:00
Isaac Chen 0484cfb6a9
Corrected EBNF grammar for from_str
Previously, the `Number` part of the EBNF grammar had an option for `'.' Digit*`, which would include the string "." (a single decimal point). This is not valid, and does not return an Ok as stated. The corrected version removes this, and still allows for the `'.' Digit+` case with the already existing `Digit* '.' Digit+` case.
2022-05-28 18:24:34 -04:00
Ralf Jung 852777eff1 note to future self 2022-05-28 18:15:04 +02:00
Ralf Jung ad33519455 ptr::invalid is not equivalent to a int2ptr cast 2022-05-28 12:39:36 +02:00
Dylan DPC 880d3ea3c2
Rollup merge of #97034 - fee1-dead-contrib:layout-hash, r=dtolnay
Implement `Hash` for `core::alloc::Layout`

This was brought up on [reddit](https://www.reddit.com/r/rust/comments/uoypui/the_standard_library_types_are_good_except_when/), and I don't see why Layout shouldn't implement `Hash`. Feel free to comment if I am wrong though :)
2022-05-28 08:45:51 +02:00
Dylan DPC 837cd9e26c
Rollup merge of #94640 - Pointerbender:issue-71146-partial-stabilization, r=yaahc
Partially stabilize `(const_)slice_ptr_len` feature by stabilizing `NonNull::len`

This PR partially stabilizes features `const_slice_ptr_len` and `slice_ptr_len` by only stabilizing `NonNull::len`. This partial stabilization is tracked under features `slice_ptr_len_nonnull` and `const_slice_ptr_len_nonnull`, for which this PR can serve as the tracking issue.

To summarize the discussion from #71146 leading up to this partial stabilization request:

It's currently a bit footgunny to obtain the length of a raw slice pointer, stabilization of `NonNull:len` will help with removing these footguns. Some example footguns are:

```rust
/// # Safety
/// The caller must ensure that `ptr`:
/// 1. does not point to memory that was previously allocated but is now deallocated;
/// 2. is within the bounds of a single allocated object;
/// 3. does not to point to a slice for which the length exceeds `isize::MAX` bytes;
/// 4. points to a properly aligned address;
/// 5. does not point to uninitialized memory;
/// 6. does not point to a mutably borrowed memory location.
pub unsafe fn ptr_len<T>(ptr: core::ptr::NonNull<[T]>) -> usize {
   (&*ptr.as_ptr()).len()
}
```

A slightly less complicated version (but still more complicated than it needs to be):

```rust
/// # Safety
/// The caller must ensure that the start of `ptr`:
/// 1. does not point to memory that was previously allocated but is now deallocated;
/// 2. must be within the bounds of a single allocated object.
pub unsafe fn ptr_len<T>(ptr: NonNull<[T]>) -> usize {
   (&*(ptr.as_ptr() as *const [()])).len()
}
```

This PR does not stabilize `<*const [T]>::len` and  `<*mut [T]>::len` because the tracking issue #71146 list a potential blocker for these methods, but this blocker [does not apply](https://github.com/rust-lang/rust/issues/71146#issuecomment-808735714) to `NonNull::len`.

We should probably also ping the [Constant Evaluation WG](https://github.com/rust-lang/const-eval) since this PR includes a `#[rustc_allow_const_fn_unstable(const_slice_ptr_len)]`. My instinct here is that this will probably be okay because the pointer is not actually dereferenced and `len()` does not touch the address component of the pointer, but would be best to double check :)

One potential down-side was raised that stabilizing `NonNull::len` could lead to encouragement of coding patterns like:

```
pub fn ptr_len<T>(ptr: *mut [T]) -> usize {
   NonNull::new(ptr).unwrap().len()
}
```

which unnecessarily assert non-nullness. However, these are much less of a footgun than the above examples and this should be resolved when `slice_ptr_len` fully stabilizes eventually.
2022-05-28 08:45:50 +02:00
Mark Rousskov b454991ac4 Finish bumping stage0
It looks like the last time had left some remaining cfg's -- which made me think
that the stage0 bump was actually successful. This brings us to a released 1.62
beta though.
2022-05-27 07:36:17 -04:00
bors 9a42c6509d Auto merge of #97444 - compiler-errors:rollup-2gvdav6, r=compiler-errors
Rollup of 3 pull requests

Successful merges:

 - #96051 (Use rounding in float to Duration conversion methods)
 - #97066 (rustdoc: Remove `ItemFragment(Kind)`)
 - #97436 (Update `triagebot.toml` for macos ping group)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-27 03:27:04 +00:00
Michael Goulet e3813e46a2
Rollup merge of #96051 - newpavlov:duration_rounding, r=nagisa,joshtriplett
Use rounding in float to Duration conversion methods

Closes #96045
2022-05-26 20:15:07 -07:00
Артём Павлов [Artyom Pavlov] 6495963d5a fmt 2022-05-27 05:15:22 +03:00
Артём Павлов [Artyom Pavlov] 38609cd8a9 fix nanos overflow for f64 2022-05-27 04:59:01 +03:00
Artyom Pavlov 06af3a63a5
add debug asserts 2022-05-27 00:22:56 +00:00
Vadim Petrochenkov 5bf23f64cc libcore: Add `iter::from_generator` which is like `iter::from_fn`, but for coroutines instead of functions 2022-05-27 01:51:31 +03:00
Matthias Krüger 82beeabf54
Rollup merge of #96033 - yaahc:expect-elaboration, r=scottmcm
Add section on common message styles for Result::expect

Based on a question from https://github.com/rust-lang/project-error-handling/issues/50#issuecomment-1092339937

~~One thing I haven't decided on yet, should I duplicate this section on `Option::expect`, link to this section, or move it somewhere else and link to that location from both docs?~~: I ended up moving the section to `std::error` and referencing it from both `Result::expect` and `Option::expect`'s docs.

I think this section, when combined with the similar update I made on [`std::panic!`](https://doc.rust-lang.org/nightly/std/macro.panic.html#when-to-use-panic-vs-result) implies that we should possibly more aggressively encourage and support the "expect as precondition" style described in this section. The consensus among the libs team seems to be that panic should be used for bugs, not expected potential failure modes. The "expect as error message" style seems to align better with the panic for unrecoverable errors style where they're seen as normal errors where the only difference is a desire to kill the current execution unit (aka erlang style error handling). I'm wondering if we should be providing a panic hook similar to `human-panic` or more strongly recommending the "expect as precondition" style of expect message.
2022-05-26 20:59:40 +02:00
Maybe Waffle 89295352ee Allow some internal instability 2022-05-26 13:00:14 +04:00
Jane Lusby ef879c680e fix broken doctest 2022-05-25 12:20:48 -07:00
Jane Lusby 720e987ac0 update option and result references to expect message docs 2022-05-25 11:37:39 -07:00
bors 9fed13030c Auto merge of #94954 - SimonSapin:null-thin3, r=yaahc
Extend ptr::null and null_mut to all thin (including extern) types

Fixes https://github.com/rust-lang/rust/issues/93959

This change was accepted in https://rust-lang.github.io/rfcs/2580-ptr-meta.html

Note that this changes the signature of **stable** functions. The change should be backward-compatible, but it is **insta-stable** since it cannot (easily, at all?) be made available only through a `#![feature(…)]` opt-in.

The RFC also proposed the same change for `NonNull::dangling`, which makes sense it terms of its signature but not in terms of its implementation. `dangling` uses `align_of()` as an address. But what `align_of()` should be for extern types or whether it should be allowed at all remains an open question.

This commit depends on https://github.com/rust-lang/rust/pull/93977, which is not yet part of the bootstrap compiler. So `#[cfg]` is used to only apply the change in stage 1+. As far a I know bounds cannot be made conditional with `#[cfg]`, so the entire functions are duplicated. This is unfortunate but temporary.

Since this duplication makes it less obvious in the diff, the new definitions differ in:

* More permissive bounds (`Thin` instead of implied `Sized`)
* Different implementation
* Having `rustc_allow_const_fn_unstable(const_fn_trait_bound)`
* Having `rustc_allow_const_fn_unstable(ptr_metadata)`
2022-05-25 13:58:51 +00:00
Dylan DPC ca269b1e79
Rollup merge of #97233 - c410-f3r:assert-lib, r=scottmcm
[RFC 2011] Library code

CC https://github.com/rust-lang/rust/pull/96496

Based on https://github.com/dtolnay/case-studies/tree/master/autoref-specialization.

Basically creates two traits with the same method name. One trait is generic over any `T` and the other is specialized to any `T: Printable`.

The compiler will then call the corresponding trait method through auto reference.

```rust
fn main() {
    let mut a = Capture::new();
    let mut b = Capture::new();

    (&Wrapper(&1i32)).try_capture(&mut a); // `try_capture` from `TryCapturePrintable`
    (&Wrapper(&vec![1i32])).try_capture(&mut b); // `try_capture` from `TryCaptureGeneric`

    assert_eq!(format!("{:?}", a), "1");
    assert_eq!(format!("{:?}", b), "N/A");
}
```

r? `@scottmcm`
2022-05-25 10:48:29 +02:00
Dylan DPC fbb17777fe
Rollup merge of #97026 - Nilstrieb:make-atomic-debug-relaxed, r=scottmcm
Change orderings of `Debug` for the Atomic types to `Relaxed`.

This reduces synchronization between threads when debugging the atomic types.  Reducing the synchronization means that executions with and without the debug calls will be more consistent, making it easier to debug.

We discussed this on the Rust Community Discord with `@ibraheemdev` before.
2022-05-25 07:31:42 +02:00
Артём Павлов [Artyom Pavlov] 26f859463e tweak doctests 2022-05-25 05:14:30 +03:00
Артём Павлов [Artyom Pavlov] c2d8445cde implement tie to even 2022-05-25 05:01:11 +03:00
Yuki Okushi 7ed7f65bac
Rollup merge of #97363 - wackbyte:sliceindex-doc-typo, r=JohnTitor
Fix a small mistake in `SliceIndex`'s documentation

Originally, it said "`get_(mut_)unchecked`," but the method's actual name is `get_unchecked_mut`.
2022-05-25 07:08:44 +09:00
Yuki Okushi 33f45b167e
Rollup merge of #93966 - rkuhn:patch-1, r=tmandry
document expectations for Waker::wake

fixes #93961

Opened PR for a discussion on the precise wording.
2022-05-25 07:08:41 +09:00
Maybe Waffle 138aa99503 Stabilize checked slice->str conversion functions 2022-05-24 22:58:28 +04:00
Maybe Waffle 7a09b8a7b5 Stabilize `{slice,array}::from_ref` 2022-05-24 22:33:31 +04:00
wackbyte ce947735c0
Fix a mistake in `SliceIndex`'s documentation 2022-05-24 13:22:41 -04:00
Dylan DPC 4bd40186db
Rollup merge of #97321 - RalfJung:int-to-fnptr, r=Dylan-DPC
explain how to turn integers into fn ptrs

(with an intermediate raw ptr, not a direct transmute)
Direct int2ptr transmute, under the semantics I am imagining, will produce a ptr with "invalid" provenance that is invalid to deref or call. We cannot give it the same semantics as int2ptr casts since those do [something complicated](https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html).

To my great surprise, that is already what the example in the `transmute` docs does. :)  I still added a comment to say that that part is important, and I added a section explicitly talking about this to the `fn()` type docs.

With https://github.com/rust-lang/miri/pull/2151, Miri will start complaining about direct int-to-fnptr transmutes (in the sense that it is UB to call the resulting pointer).
2022-05-24 15:58:26 +02:00
Dylan DPC af15e45e28
Rollup merge of #97308 - JohnTitor:stabilize-cell-filter-map, r=Mark-Simulacrum
Stabilize `cell_filter_map`

FCP has been completed: https://github.com/rust-lang/rust/issues/81061#issuecomment-1081806326
Closes #81061
2022-05-24 15:58:25 +02:00
Ralf Jung cec6dfcd67 explain how to turn integers into fn ptrs
(with an intermediate raw ptr, not a direct transmute)
2022-05-23 18:47:08 +02:00
Dylan DPC 98a8035bed
Rollup merge of #96129 - mattheww:2022-04_float_rounding, r=Dylan-DPC
Document rounding for floating-point primitive operations and string parsing

The docs for floating point don't have much to say at present about either the precision of their results or rounding behaviour.

As I understand it[^1][^2], Rust doesn't support operating with non-default rounding directions, so we need only describe roundTiesToEven.

[^1]: https://github.com/rust-lang/rust/issues/41753#issuecomment-299322887
[^2]: https://github.com/llvm/llvm-project/issues/8472#issuecomment-980888781

This PR makes a start by documenting that for primitive operations and `from_str()`.
2022-05-23 15:11:02 +02:00
Yuki Okushi 65242592c9
Stabilize `cell_filter_map` 2022-05-23 18:04:53 +09:00
bors 9e2f655863 Auto merge of #97304 - Dylan-DPC:rollup-qxrfddc, r=Dylan-DPC
Rollup of 5 pull requests

Successful merges:

 - #97087 (Clarify slice and Vec iteration order)
 - #97254 (Remove feature: `crate` visibility modifier)
 - #97271 (Add regression test for #91949)
 - #97294 (std::time : fix variable name in the doc)
 - #97303 (Fix some typos in arg checking algorithm)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-23 07:57:15 +00:00
Dylan DPC e5cf3cb97d
Rollup merge of #97087 - Nilstrieb:clarify-slice-iteration-order, r=dtolnay
Clarify slice and Vec iteration order

While already being inferable from the doc examples, it wasn't fully specified. This is the only logical way to do a slice iterator, so I think this should be uncontroversial. It also improves the `Vec::into_iter` example to better show the order and that the iterator returns owned values.
2022-05-23 07:43:49 +02:00
bors 03c8b0b6ed Auto merge of #96100 - Raekye:master, r=dtolnay
Change `NonNull::as_uninit_*` to take self by value (as opposed to reference), matching primitive pointers.

Copied from my comment on [#75402](https://github.com/rust-lang/rust/issues/75402#issuecomment-1100496823):

> I noticed that `as_uninit_*` on pointers take `self` by value (and pointers are `Copy`), e.g. see [`as_uninit_mut`](https://doc.rust-lang.org/core/primitive.pointer.html#method.as_uninit_mut).
>
> However, on `NonNull`, these functions take `self` by reference, e.g. see the function with the same name by for `NonNull`: [`as_uninit_mut`](https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_uninit_mut) takes `self` by mutable reference. Even more inconsistent, [`as_uninit_slice_mut`](https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_uninit_slice_mut) returns a mutable reference, but takes `self` by immutable reference.
>
> I think these methods should take `self` by value for consistency. The returned lifetime is unbounded anyways and not tied to the pointer/NonNull value anyways

I realized the change is trivial (if desired) so here I am creating my first PR. I think it's not a breaking change since (it's on nightly and) `NonNull` is `Copy`; all previous usages of these methods taking `self` by reference should continue to compile. However, it might cause warnings to appear on usages of `NonNull::as_uninit_mut`, which used to require the the `NonNull` variable be declared `mut`, but now it's not necessary.
2022-05-23 05:32:04 +00:00
David Tolnay 0502496b1e
Make write/print macros eagerly drop temporaries 2022-05-22 16:11:08 -07:00
Caio 664e8a9ce5 [RFC 2011] Library code 2022-05-22 07:18:32 -03:00
Ralf Jung 4505579713 adjust transmute const stabilization version 2022-05-22 08:10:53 +02:00
bors bb5e6c984d Auto merge of #97265 - JohnTitor:rollup-kgthnjt, r=JohnTitor
Rollup of 6 pull requests

Successful merges:

 - #97144 (Fix rusty grammar in `std::error::Reporter` docs)
 - #97225 (Fix `Display` for `cell::{Ref,RefMut}`)
 - #97228 (Omit stdarch workspace from rust-src)
 - #97236 (Recover when resolution did not resolve lifetimes.)
 - #97245 (Fix typo in futex RwLock::write_contended.)
 - #97259 (Fix typo in Mir phase docs)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-22 04:27:10 +00:00
Yuki Okushi d22ebf0d13
Rollup merge of #97225 - cuviper:ref-display, r=scottmcm
Fix `Display` for `cell::{Ref,RefMut}`

These guards changed to pointers in #97027, but their `Display` was
formatting that field directly, which made it show the raw pointer
value. Now we go through `Deref` to display the real value again.

Miri noticed this change, #97204, so hopefully that will be fixed.
2022-05-22 11:53:05 +09:00
bors 09ea21343a Auto merge of #94119 - c410-f3r:array-again-and-again, r=scottmcm
Stabilize `array_from_fn`

## Overall

Stabilizes `core::array::from_fn` ~~and `core::array::try_from_fn`~~ to allow the creation of custom infallible ~~and fallible~~ arrays.

Signature proposed for stabilization here, tweaked as requested in the meeting:

```rust
// in core::array

pub fn from_fn<T, const N: usize, F>(_: F) -> [T; N];
```

Examples in https://doc.rust-lang.org/nightly/std/array/fn.from_fn.html

## History

* On 2020-08-17, implementation was [proposed](https://github.com/rust-lang/rust/pull/75644).
* On 2021-09-29, tracking issue was [created](https://github.com/rust-lang/rust/issues/89379).
* On 2021-10-09, the proposed implementation was [merged](bc8ad24020).
* On 2021-12-03, the return type of `try_from_fn` was [changed](https://github.com/rust-lang/rust/pull/91286#issuecomment-985513407).

## Considerations

* It is being assumed that indices are useful and shouldn't be removed from the callbacks
* The fact that `try_from_fn` returns an unstable type `R: Try` does not prevent stabilization. Although I'm honestly not sure about it.
* The addition or not of repeat-like variants is orthogonal to this PR.

These considerations are not ways of saying what is better or what is worse. In reality, they are an attempt to move things forward, anything really.

cc https://github.com/rust-lang/rust/issues/89379
2022-05-22 01:56:50 +00:00
bors 9257f5aad0 Auto merge of #94530 - tmiasko:alignment-impls, r=dtolnay
Implement Copy, Clone, PartialEq and Eq for core::fmt::Alignment

Alignment is a fieldless exhaustive enum, so it is already possible to
clone and compare it by matching, but it is inconvenient to do so. For
example, if one would like to create a struct describing a formatter
configuration and provide a clone implementation:

```rust
pub struct Format {
    fill: char,
    width: Option<usize>,
    align: fmt::Alignment,
}

impl Clone for Format {
    fn clone(&self) -> Self {
        Format {
            align: match self.align {
                fmt::Alignment::Left => fmt::Alignment::Left,
                fmt::Alignment::Right => fmt::Alignment::Right,
                fmt::Alignment::Center => fmt::Alignment::Center,
            },
            .. *self
        }
    }
}
```

Derive Copy, Clone, PartialEq, and Eq for Alignment for convenience.
2022-05-21 19:49:51 +00:00
Guillaume Gomez 6fef5f1e24
Rollup merge of #97219 - RalfJung:ptr-invalid, r=thomcc
make ptr::invalid not the same as a regular int2ptr cast

In Miri, we would like to distinguish `ptr::invalid` from `ptr::from_exposed_provenance`, so that we can provide better diagnostics issues like https://github.com/rust-lang/miri/issues/2134, and so that we can detect the UB in programs like
```rust
fn main() {
    let x = 0u8;
    let original_ptr = &x as *const u8;
    let addr = original_ptr.expose_addr();
    let new_ptr: *const u8 = core::ptr::invalid(addr);
    unsafe {
        dbg!(*new_ptr);
    }
}
```

To achieve that, the two functions need to have different implementations. Currently, both are just `as` casts. We *could* add an intrinsic for this, but it turns out `transmute` already has the right behavior, at least as far as Miri is concerned. So I propose we just use that.

Cc `@Gankra`
2022-05-21 11:39:50 +02:00
Guillaume Gomez 1210b50dbb
Rollup merge of #97190 - SylvainDe:master, r=Dylan-DPC
Add implicit call to from_str via parse in documentation

The documentation mentions "FromStr’s from_str method is often used implicitly,
through str’s parse method. See parse’s documentation for examples.".

It may be nicer to show that in the code example as well.
2022-05-21 11:39:48 +02:00
Josh Stone 83abb7c18f Fix `Display` for `cell::{Ref,RefMut}`
These guards changed to pointers in #97027, but their `Display` was
formatting that field directly, which made it show the raw pointer
value. Now we go through `Deref` to display the real value again.
2022-05-20 11:16:30 -07:00
Ralf Jung 31c3c04498 make ptr::invalid not the same as a regular int2ptr cast 2022-05-20 17:16:41 +02:00