Commit Graph

3651 Commits

Author SHA1 Message Date
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
Caio
d917112606 Stabilize core::array::from_fn 2022-05-20 11:04:13 -03:00
Guillaume Gomez
9b25cc0543
Rollup merge of #97192 - sunfishcode:sunfishcode/rightmost, r=thomcc
Say "last" instead of "rightmost" in the documentation for `std::str:rfind`

In the documentation comment for `std::str::rfind`, say "last" instead
of "rightmost" to describe the match that `rfind` finds. This follows the
spirit of #30459, for which `trim_left` and `trim_right` were replaced by
`trim_start` and `trim_end` to be more clear about how they work on
text which is displayed right-to-left.
2022-05-20 14:03:06 +02:00
bors
52cc779524 Auto merge of #97147 - Mark-Simulacrum:stage0-bump, r=pietroalbini
stage0 bootstrap bump

r? `@pietroalbini`
2022-05-20 05:44:52 +00:00
bors
4d6992bc18 Auto merge of #97027 - cuviper:yesalias-refcell, r=thomcc
Use pointers in `cell::{Ref,RefMut}` to avoid `noalias`

When `Ref` and `RefMut` were based on references, they would get LLVM `noalias` attributes that were incorrect, because that alias guarantee is only true until the guard drops. A `&RefCell` on the same value can get a new borrow that aliases the previous guard, possibly leading to miscompilation. Using `NonNull` pointers in `Ref` and `RefCell` avoids `noalias`.

Fixes the library side of #63787, but we still might want to explore language solutions there.
2022-05-20 01:05:53 +00:00
Dan Gohman
b836cf6fb8 Say "last" instead of "rightmost" in the documentation for std::str::rfind.
In the documentation comment for `std::str::rfind`, say "last" instead
of "rightmost" to describe the match that `rfind` finds. This follows the
spirit of #30459, for which `trim_left` and `trim_right` were replaced by
`trim_start` and `trim_end` to be more clear about how they work on
text which is displayed right-to-left.
2022-05-19 15:31:17 -07:00
SylvainDe
4c1daba940 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-19 22:01:43 +02:00
Dylan DPC
12644bc39d
Rollup merge of #97155 - alygin:patch-1, r=JohnTitor
Fix doc typo

Fixes a minor doc typo for `atomic::fence()`.
2022-05-19 17:22:49 +02:00
bors
d8a3fc4d71 Auto merge of #95643 - WaffleLapkin:ptr_convenience, r=joshtriplett
Add convenience byte offset/check align functions to pointers

This PR adds the following APIs:
```rust
impl *const T {
    // feature gates `pointer_byte_offsets` and `const_pointer_byte_offsets
    pub const unsafe fn byte_offset(self, count: isize) -> Self;
    pub const fn wrapping_byte_offset(self, count: isize) -> Self;
    pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize;
    pub const unsafe fn byte_add(self, count: usize) -> Self;
    pub const unsafe fn byte_sub(self, count: usize) -> Self;
    pub const fn wrapping_byte_add(self, count: usize) -> Self;
    pub const fn wrapping_byte_sub(self, count: usize) -> Self;

    // feature gate `pointer_is_aligned`
    pub fn is_aligned(self) -> bool where T: Sized;
    pub fn is_aligned_to(self, align: usize) -> bool;
}
// ... and the same for` *mut T`
```

Note that all functions except `is_aligned` do **not** require `T: Sized` as their pointee-sized-offset counterparts.

cc `@oli-obk` (you may want to check that I've correctly placed `const`s)
cc `@RalfJung`
2022-05-18 23:18:03 +00:00
Andrew Lygin
0d99b90983
Fix doc typo 2022-05-19 00:25:14 +03:00
Mark Rousskov
32fdc6b207 Stage-step cfgs 2022-05-18 12:29:35 -04:00
Pointerbender
021a7e4877 bump stable version #94640 2022-05-17 16:50:49 +02:00
Josh Stone
1f33c921d1 Add a comment for covariant Ref 2022-05-16 17:24:53 -07:00
Josh Stone
1e53fab55a Remove outdated references to nll-rfc#40 2022-05-16 17:22:51 -07:00
Nilstrieb
4a2214885d 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.
2022-05-16 19:29:45 +02:00
bors
56d540e057 Auto merge of #97053 - CAD97:realloc-clarification, r=dtolnay
Remove potentially misleading realloc parenthetical

This parenthetical is problematic, because it suggests that the following is sound:

```rust
let layout = Layout:🆕:<[u8; 32]>();
let p1 = alloc(layout);
let p2 = realloc(p1, layout, 32);
if p1 == p2 {
    p1.write([0; 32]);
    dealloc(p1, layout);
} else {
    dealloc(p2, layout);
}
```

At the very least, this isn't the case for [ANSI `realloc`](https://en.cppreference.com/w/c/memory/realloc)

> The original pointer `ptr` is invalidated and any access to it is undefined behavior (even if reallocation was in-place).

and [Windows `HeapReAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heaprealloc) is unclear at best (`HEAP_REALLOC_IN_PLACE_ONLY`'s description may imply that the old pointer may be used if `HEAP_REALLOC_IN_PLACE_ONLY` is provided).

The conservative position is to just remove the parenthetical.

cc `@rust-lang/wg-unsafe-code-guidelines` `@rust-lang/wg-allocators`
2022-05-16 02:33:34 +00:00
gabriel-doriath-dohler
26265319c7 Rename eq_ignore_case to starts_with_ignore_case
The method doesn't test for equality. It tests if the object starts with
a given byte array, so its name is confusing.
2022-05-15 23:59:59 +00:00
CAD97
09dc24bc04 Remove potentially misleading realloc parenthetical 2022-05-14 22:30:14 -05:00
Deadbeef
af9168c467 Implement Hash for core::alloc::Layout 2022-05-14 14:44:42 +10:00
bors
9fbbe75fd7 Auto merge of #95602 - scottmcm:faster-array-intoiter-fold, r=the8472
Fix `array::IntoIter::fold` to use the optimized `Range::fold`

It was using `Iterator::by_ref` in the implementation, which ended up pessimizing it enough that, for example, it didn't vectorize when we tried it in the <https://rust-lang.zulipchat.com/#narrow/stream/257879-project-portable-simd/topic/Reducing.20sum.20into.20wider.20types> conversation.

Demonstration that the codegen test doesn't pass on the current nightly: <https://rust.godbolt.org/z/Taxev5eMn>
2022-05-14 03:12:53 +00:00
Nilstrieb
d11667f5cc 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.
2022-05-13 21:22:54 +02:00
Josh Stone
2b8041f574 Use a pointer in cell::RefMut so it's not noalias 2022-05-13 12:08:54 -07:00
Josh Stone
d369045aed Use a pointer in cell::Ref so it's not noalias 2022-05-13 11:42:10 -07:00
Simon Sapin
7ccc09b210 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(ptr_metadata)`
2022-05-13 18:03:06 +02:00
Matthias Krüger
a56211a44e
Rollup merge of #97003 - nnethercote:rm-const_fn-attrs, r=fee1-dead
Remove some unnecessary `rustc_allow_const_fn_unstable` attributes.

r? `@fee1-dead`
2022-05-13 16:03:25 +02:00
Matthias Krüger
feb18d102a
Rollup merge of #96154 - lukaslueg:unreachablehint, r=scottmcm
Expand core::hint::unreachable_unchecked() docs

Rework the docs for `unreachable_unchecked`, encouraging deliberate use, and providing a better example for action at a distance.

Fixes #95865
2022-05-13 16:03:22 +02:00
Scott McMurray
e8fc7ba6a7 Slap #[inline] on all the ByRefSized methods, per the8472's suggestion 2022-05-13 00:43:15 -07:00
Nicholas Nethercote
fd01fbc058 Remove some unnecessary rustc_allow_const_fn_unstable attributes. 2022-05-13 16:01:18 +10:00
Maybe Waffle
03d4569939 Fill-in tracking issues for features pointer_byte_offsets, const_pointer_byte_offsets and pointer_is_aligned 2022-05-12 12:54:21 +04:00
Maybe Waffle
5a5d62aeb2 Optimize ptr.is_aligned_to()
Apparently LLVM is unable to understand that if count_ones() == 1 then self != 0.
Adding `assume(align != 0)` helps generating better asm:
https://rust.godbolt.org/z/ja18YKq91
2022-05-12 12:54:21 +04:00
Maybe Waffle
6c1ebff59e Implement ptr.is_aligned() in terms of .is_aligned_to() 2022-05-12 12:54:21 +04:00
Maybe Waffle
a908eec438 Lift the Sized requirement from convenience ptr fns
Since they work on byte pointers (by `.cast::<u8>()`ing them), there is
no need to know the size of `T` and so there is no need for `T: Sized`.

The `is_aligned_to` is similar, though it doesn't need the _alignment_
of `T`.
2022-05-12 12:54:21 +04:00
Maybe Waffle
c8c91f757a Add convenience functions to pointers
The functions added:
- {*const T,*mut T}::{wrapping_,}byte_{offset,add,sub}
- {*const T,*mut T}::{byte_offset_from,is_aligned,is_aligned_to}
2022-05-12 12:54:16 +04:00
Scott McMurray
003b954a43 Apply CR suggestions; add real tracking issue 2022-05-11 17:16:25 -07:00
Scott McMurray
4bb15b3797 Add a debug check for ordering, and check for isize overflow in CTFE 2022-05-11 17:16:25 -07:00
Scott McMurray
e76b3f3b5b Rename unsigned_offset_from to sub_ptr 2022-05-11 17:16:25 -07:00
Scott McMurray
89a18cb600 Add unsigned_offset_from on pointers
Like we have `add`/`sub` which are the `usize` version of `offset`, this adds the `usize` equivalent of `offset_from`.  Like how `.add(d)` replaced a whole bunch of `.offset(d as isize)`, you can see from the changes here that it's fairly common that code actually knows the order between the pointers and *wants* a `usize`, not an `isize`.

As a bonus, this can do `sub nuw`+`udiv exact`, rather than `sub`+`sdiv exact`, which can be optimized slightly better because it doesn't have to worry about negatives.  That's why the slice iterators weren't using `offset_from`, though I haven't updated that code in this PR because slices are so perf-critical that I'll do it as its own change.

This is an intrinsic, like `offset_from`, so that it can eventually be allowed in CTFE.  It also allows checking the extra safety condition -- see the test confirming that CTFE catches it if you pass the pointers in the wrong order.
2022-05-11 17:16:25 -07:00
Dylan DPC
c5c273b30e
Rollup merge of #96674 - bstrie:vardoc, r=thomcc
docs: add link explaining variance to NonNull docs
2022-05-10 08:24:02 +02:00
Matthias Krüger
6c8001b85c
Rollup merge of #96008 - fmease:warn-on-useless-doc-hidden-on-assoc-impl-items, r=lcnr
Warn on unused `#[doc(hidden)]` attributes on trait impl items

[Zulip conversation](https://rust-lang.zulipchat.com/#narrow/stream/266220-rustdoc/topic/.E2.9C.94.20Validy.20checks.20for.20.60.23.5Bdoc.28hidden.29.5D.60).

Whether an associated item in a trait impl is shown or hidden in the documentation entirely depends on the corresponding item in the trait declaration. Rustdoc completely ignores `#[doc(hidden)]` attributes on impl items. No error or warning is emitted:

```rust
pub trait Tr { fn f(); }
pub struct Ty;
impl Tr for Ty { #[doc(hidden)] fn f() {} }
//               ^^^^^^^^^^^^^^ ignored by rustdoc and currently
//                              no error or warning issued
```

This may lead users to the wrong belief that the attribute has an effect. In fact, several such cases are found in the standard library (I've removed all of them in this PR).
There does not seem to exist any incentive to allow this in the future either: Impl'ing a trait for a type means the type *fully* conforms to its API. Users can add `#[doc(hidden)]` to the whole impl if they want to hide the implementation or add the attribute to the corresponding associated item in the trait declaration to hide the specific item. Hiding an implementation of an associated item does not make much sense: The associated item can still be found on the trait page.

This PR emits the warn-by-default lint `unused_attribute` for this case with a future-incompat warning.

`@rustbot` label T-compiler T-rustdoc A-lint
2022-05-09 18:45:36 +02:00
Matthias Krüger
28d800ce1c
Rollup merge of #95483 - golddranks:improve_float_docs, r=joshtriplett
Improve floating point documentation

This is my attempt to improve/solve https://github.com/rust-lang/rust/issues/95468 and https://github.com/rust-lang/rust/issues/73328 .

Added/refined explanations:
- Refine the "NaN as a special value" top level explanation of f32
- Refine `const NAN` docstring: add an explanation about there being multitude of NaN bitpatterns and disclaimer about the portability/stability guarantees.
- Refine `fn is_sign_positive` and `fn is_sign_negative` docstrings: add disclaimer about the sign bit of NaNs.
- Refine `fn min` and `fn max` docstrings: explain the semantics and their relationship to the standard and libm better.
- Refine `fn trunc` docstrings: explain the semantics slightly more.
- Refine `fn powi` docstrings: add disclaimer that the rounding behaviour might be different from `powf`.
- Refine `fn copysign` docstrings: add disclaimer about payloads of NaNs.
- Refine `minimum` and `maximum`: add disclaimer that "propagating NaN" doesn't mean that propagating the NaN bit patterns is guaranteed.
- Refine `max` and `min` docstrings: add "ignoring NaN" to bring the one-row explanation to parity with `minimum` and `maximum`.

Cosmetic changes:
- Reword `NaN` and `NAN` as plain "NaN", unless they refer to the specific `const NAN`.
- Reword "a number" to `self` in function docstrings to clarify.
- Remove "Returns NAN if the number is NAN" from `abs`, as this is told to be the default behavior in the top explanation.
2022-05-09 18:45:35 +02:00
bors
8a2fe75d0e Auto merge of #95960 - jhpratt:remove-rustc_deprecated, r=compiler-errors
Remove `#[rustc_deprecated]`

This removes `#[rustc_deprecated]` and introduces diagnostics to help users to the right direction (that being `#[deprecated]`). All uses of `#[rustc_deprecated]` have been converted. CI is expected to fail initially; this requires #95958, which includes converting `stdarch`.

I plan on following up in a short while (maybe a bootstrap cycle?) removing the diagnostics, as they're only intended to be short-term.
2022-05-09 04:47:30 +00:00
bors
cb12198715 Auto merge of #96846 - matthiaskrgr:rollup-yxu9ot9, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #96617 (Fix incorrect syntax suggestion with `pub async fn`)
 - #96828 (Further elaborate the lack of guarantees from `Hasher`)
 - #96829 (Fix the `x.py clippy` command)
 - #96830 (Add and tweak const-generics tests)
 - #96835 (Add more eslint rules)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-08 21:37:26 +00:00
León Orell Valerian Liehr
9d157ada35 Warn on unused doc(hidden) on trait impl items 2022-05-08 22:53:14 +02:00
Matthias Krüger
2c4d7a5463
Rollup merge of #96828 - scottmcm:clarify-hasher-write, r=Amanieu
Further elaborate the lack of guarantees from `Hasher`

I realized that I got too excited in #94598 by adding new methods, and forgot to do the documentation to really answer the core question in #94026.

This PR just has that doc update.

r? `@Amanieu`
2022-05-08 21:31:17 +02:00
bors
68461648bf Auto merge of #96302 - Serial-ATA:more-diagnostic-items, r=manishearth
Add more diagnostic items

This just adds a handful diagnostic items I noticed were missing.

Would it be worth doing this for all of the remaining types? I'm willing to do it if it'd be helpful.
2022-05-08 19:08:34 +00:00
Scott McMurray
83f785bff9 Further elaborate the lack of guarantees from Hasher 2022-05-07 17:44:30 -07:00
Matthias Krüger
1386a02dc1
Rollup merge of #96336 - Nilstrieb:link-to-correct-as_mut-in-ptr-as_ref, r=JohnTitor
Link to correct `as_mut` in docs for `pointer::as_ref`

It previously linked to the unstable const-mut-cast method instead of
the `mut` counterpart for `as_ref`.

Closes #96327
2022-05-07 22:44:36 +02:00
Nikolaos Chatzikonstantinou
7c1d241f2b
Fix a minor typo in the description of Formatter 2022-05-07 19:32:54 +09:00
Jane Lusby
7b5dce900d This is a pretty good start if you ask me 2022-05-06 15:03:25 -07:00
bors
8c4fc9d9a4 Auto merge of #94598 - scottmcm:prefix-free-hasher-methods, r=Amanieu
Add a dedicated length-prefixing method to `Hasher`

This accomplishes two main goals:
- Make it clear who is responsible for prefix-freedom, including how they should do it
- Make it feasible for a `Hasher` that *doesn't* care about Hash-DoS resistance to get better performance by not hashing lengths

This does not change rustc-hash, since that's in an external crate, but that could potentially use it in future.

Fixes #94026

r? rust-lang/libs

---

The core of this change is the following two new methods on `Hasher`:

```rust
pub trait Hasher {
    /// Writes a length prefix into this hasher, as part of being prefix-free.
    ///
    /// If you're implementing [`Hash`] for a custom collection, call this before
    /// writing its contents to this `Hasher`.  That way
    /// `(collection![1, 2, 3], collection![4, 5])` and
    /// `(collection![1, 2], collection![3, 4, 5])` will provide different
    /// sequences of values to the `Hasher`
    ///
    /// The `impl<T> Hash for [T]` includes a call to this method, so if you're
    /// hashing a slice (or array or vector) via its `Hash::hash` method,
    /// you should **not** call this yourself.
    ///
    /// This method is only for providing domain separation.  If you want to
    /// hash a `usize` that represents part of the *data*, then it's important
    /// that you pass it to [`Hasher::write_usize`] instead of to this method.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(hasher_prefixfree_extras)]
    /// # // Stubs to make the `impl` below pass the compiler
    /// # struct MyCollection<T>(Option<T>);
    /// # impl<T> MyCollection<T> {
    /// #     fn len(&self) -> usize { todo!() }
    /// # }
    /// # impl<'a, T> IntoIterator for &'a MyCollection<T> {
    /// #     type Item = T;
    /// #     type IntoIter = std::iter::Empty<T>;
    /// #     fn into_iter(self) -> Self::IntoIter { todo!() }
    /// # }
    ///
    /// use std:#️⃣:{Hash, Hasher};
    /// impl<T: Hash> Hash for MyCollection<T> {
    ///     fn hash<H: Hasher>(&self, state: &mut H) {
    ///         state.write_length_prefix(self.len());
    ///         for elt in self {
    ///             elt.hash(state);
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Note to Implementers
    ///
    /// If you've decided that your `Hasher` is willing to be susceptible to
    /// Hash-DoS attacks, then you might consider skipping hashing some or all
    /// of the `len` provided in the name of increased performance.
    #[inline]
    #[unstable(feature = "hasher_prefixfree_extras", issue = "88888888")]
    fn write_length_prefix(&mut self, len: usize) {
        self.write_usize(len);
    }

    /// Writes a single `str` into this hasher.
    ///
    /// If you're implementing [`Hash`], you generally do not need to call this,
    /// as the `impl Hash for str` does, so you can just use that.
    ///
    /// This includes the domain separator for prefix-freedom, so you should
    /// **not** call `Self::write_length_prefix` before calling this.
    ///
    /// # Note to Implementers
    ///
    /// The default implementation of this method includes a call to
    /// [`Self::write_length_prefix`], so if your implementation of `Hasher`
    /// doesn't care about prefix-freedom and you've thus overridden
    /// that method to do nothing, there's no need to override this one.
    ///
    /// This method is available to be overridden separately from the others
    /// as `str` being UTF-8 means that it never contains `0xFF` bytes, which
    /// can be used to provide prefix-freedom cheaper than hashing a length.
    ///
    /// For example, if your `Hasher` works byte-by-byte (perhaps by accumulating
    /// them into a buffer), then you can hash the bytes of the `str` followed
    /// by a single `0xFF` byte.
    ///
    /// If your `Hasher` works in chunks, you can also do this by being careful
    /// about how you pad partial chunks.  If the chunks are padded with `0x00`
    /// bytes then just hashing an extra `0xFF` byte doesn't necessarily
    /// provide prefix-freedom, as `"ab"` and `"ab\u{0}"` would likely hash
    /// the same sequence of chunks.  But if you pad with `0xFF` bytes instead,
    /// ensuring at least one padding byte, then it can often provide
    /// prefix-freedom cheaper than hashing the length would.
    #[inline]
    #[unstable(feature = "hasher_prefixfree_extras", issue = "88888888")]
    fn write_str(&mut self, s: &str) {
        self.write_length_prefix(s.len());
        self.write(s.as_bytes());
    }
}
```

With updates to the `Hash` implementations for slices and containers to call `write_length_prefix` instead of `write_usize`.

`write_str` defaults to using `write_length_prefix` since, as was pointed out in the issue, the `write_u8(0xFF)` approach is insufficient for hashers that work in chunks, as those would hash `"a\u{0}"` and `"a"` to the same thing.  But since `SipHash` works byte-wise (there's an internal buffer to accumulate bytes until a full chunk is available) it overrides `write_str` to continue to use the add-non-UTF-8-byte approach.

---

Compatibility:

Because the default implementation of `write_length_prefix` calls `write_usize`, the changed hash implementation for slices will do the same thing the old one did on existing `Hasher`s.
2022-05-06 09:43:57 +00:00
Lukas Lueg
cd1746b2b4 Clarify unreachable_unchecked docs 2022-05-06 09:34:41 +02:00
Scott McMurray
ebdcb08abf For now, don't change the details of hashing a str
We might want to change the default before stabilizing (or maybe even after), but for getting in the new unstable methods, leave it as-is for now.  That way it won't break cargo and such.
2022-05-06 00:14:44 -07:00
Scott McMurray
98054377ee Add a dedicated length-prefixing method to Hasher
This accomplishes two main goals:
- Make it clear who is responsible for prefix-freedom, including how they should do it
- Make it feasible for a `Hasher` that *doesn't* care about Hash-DoS resistance to get better performance by not hashing lengths

This does not change rustc-hash, since that's in an external crate, but that could potentially use it in future.
2022-05-06 00:03:38 -07:00
Michael Goulet
ef949daf03
Rollup merge of #96639 - adpaco-aws:fix-offset-from-typo, r=scottmcm
Fix typo in `offset_from` documentation

Small fix for what I think is a typo in the `offset_from` documentation.

Someone reading this may understand that the distance in bytes is obtained by dividing the distance by `mem::size_of::<T>()`, but here we just want to define "units of T" in terms of bytes (i.e., units of T == bytes / `mem::size_of::<T>()`).
2022-05-05 19:34:23 -07:00
Michael Goulet
87ad928c15
Rollup merge of #96174 - RalfJung:no-run-transmute, r=scottmcm
mark ptr-int-transmute test as no_run

This causes [CI failures in Miri](https://github.com/rust-lang/miri-test-libstd/runs/6062500259?check_suite_focus=true) since ptr-int-transmutes are rejected there (when strict provenance is enabled).
2022-05-05 19:34:22 -07:00
bors
74cea9fdb9 Auto merge of #96520 - lcnr:general-incoherent-impls, r=petrochenkov
generalize "incoherent impls" impl for user defined types

To allow the move of `trait Error` into core.

continues the work from #94963, finishes https://github.com/rust-lang/compiler-team/issues/487

r? `@petrochenkov` cc `@yaahc`
2022-05-05 23:24:36 +00:00
Matthias Krüger
47801413d9
Rollup merge of #95359 - jhpratt:int_roundings, r=joshtriplett
Update `int_roundings` methods from feedback

This updates `#![feature(int_roundings)]` (#88581) from feedback. All methods now take `NonZeroX`. The documentation makes clear that they panic in debug mode and wrap in release mode.

r? `@joshtriplett`

`@rustbot` label +T-libs +T-libs-api +S-waiting-on-review
2022-05-05 15:43:00 +02:00
lcnr
209dd2cb0a generalize "incoherent impls" impl for custom types 2022-05-05 10:53:00 +02:00
bors
3d18f945ca Auto merge of #96630 - m-ysk:fix/issue-88038, r=notriddle
Include nonexported macro_rules! macros in the doctest target

Fixes #88038

This PR aims to include nonexported `macro_rules!` macros in the doctest target. For more details, please see the above issue.
2022-05-05 07:25:18 +00:00
bors
12d3f107c1 Auto merge of #96626 - thomcc:rand-bump, r=m-ou-se
Avoid using `rand::thread_rng` in the stdlib benchmarks.

This is kind of an anti-pattern because it introduces extra nondeterminism for no real reason. In thread_rng's case this comes both from the random seed and also from the reseeding operations it does, which occasionally does syscalls (which adds additional nondeterminism). The impact of this would be pretty small in most cases, but it's a good practice to avoid (particularly because avoiding it was not hard).

Anyway, several of our benchmarks already did the right thing here anyway, so the change was pretty easy and mostly just applying it more universally. That said, the stdlib benchmarks aren't particularly stable (nor is our benchmark framework particularly great), so arguably this doesn't matter that much in practice.

~~Anyway, this also bumps the `rand` dev-dependency to 0.8, since it had fallen somewhat out of date.~~ Nevermind, too much of a headache.
2022-05-05 05:08:44 +00:00
Jacob Pratt
dde590d180
Update int_roundings methods from feedback 2022-05-04 23:20:29 -04:00
mbartlett21
6d523e9a75
Fix the generator example for pin!() 2022-05-05 09:58:13 +10:00
Josh Triplett
0fc5c524f5 Stabilize bool::then_some 2022-05-04 13:22:08 +02:00
Roland Kuhn
3d808d52de
add caveat discussed in #74335 2022-05-04 10:58:23 +02:00
bors
086bf7a8ff Auto merge of #96280 - lygstate:ffi-fixes, r=joshtriplett
library/core: Fixes implement of c_uint, c_long, c_ulong

Fixes: aa67016624 ("make memcmp return a value of c_int_width instead of i32")
Introduce c_num_definition to getting the cfg_if logic easier to maintain
Add newlines for easier code reading

Signed-off-by: Yonggang Luo <luoyonggang@gmail.com>
2022-05-03 17:22:58 +00:00
bstrie
6096cfbfff docs: add link explaining variance to NonNull docs 2022-05-03 11:57:24 -04:00
Yoshiki Matsuda
3d12fd0faf ignore a doctest for the non-exported macro 2022-05-03 18:33:56 +09:00
Yonggang Luo
2e69549043
Update library/core/src/ffi/mod.rs
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2022-05-03 10:42:46 +08:00
The 8472
a68a5d219d This aligns the inline attributes of existing __iterator_get_unchecked with those of next() on adapters that have both.
It improves the performance of iterators using unchecked access when building in incremental mode
(due to the larger CGU count?). It might negatively affect incremental compile times for better runtime results,
but considering that the equivalent `next()` implementations also are `#[inline]` and usually are more complex this
should be ok.

```
./x.py bench library/core -i --stage 0 --test-args bench_trusted_random_access

OLD: 119,172 ns/iter
NEW:  17,714 ns/iter
```
2022-05-02 20:54:46 +02:00
The 8472
e3db41bf97 add benchmark 2022-05-02 20:54:46 +02:00
Adrian Palacios
9b36a47831 Fix typo in offset_from documentation 2022-05-02 14:41:21 +00:00
Pyry Kontio
dea776512b Fix nits 2022-05-02 23:29:02 +09:00
Thom Chiovoloni
0812759840
Avoid use of rand::thread_rng in stdlib benchmarks 2022-05-02 00:08:21 -07:00
Yuki Okushi
f58135449e
Rollup merge of #96567 - alex-semenyuk:fix_docs_for_logs_func, r=Mark-Simulacrum
Fix docs for u32 and i32 logs func

Closes #96545
2022-05-02 10:41:57 +09:00
bors
4dd8b420c0 Auto merge of #96521 - petrochenkov:docrules, r=notriddle,GuillaumeGomez
rustdoc: Resolve doc links referring to `macro_rules` items

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

UPD: the fallback to considering *all* `macro_rules` in the crate for unresolved names is not removed in this PR, it will be removed separately and will be run through crater.
2022-05-01 20:28:10 +00:00
Scott McMurray
e094ee5f10 Add do yeet expressions to allow experimentation in nightly
Using an obviously-placeholder syntax.  An RFC would still be needed before this could have any chance at stabilization, and it might be removed at any point.

But I'd really like to have it in nightly at least to ensure it works well with try_trait_v2, especially as we refactor the traits.
2022-04-30 17:40:27 -07:00
Vadim Petrochenkov
6083db7c4e Fix some links in the standard library 2022-05-01 00:02:34 +03:00
bors
579d26876d Auto merge of #96348 - overdrivenpotato:inline-location, r=the8472
Inline core::panic::Location methods

This avoids the overhead of a function call when used.
2022-04-30 16:33:12 +00:00
Jane Losare-Lusby
72898acdba spicy 2022-04-30 03:32:41 +00:00
alexey semenyuk
6ee70bc6b3
Fix documentation for log functions int 2022-04-29 23:21:50 +00:00
alexey semenyuk
ec90f9dd33
Fix documentation for log functions unsigned int 2022-04-29 23:16:53 +00:00
Serial
09b0b8b6e2 Add more diagnostic items 2022-04-28 16:42:20 -04:00
Dylan DPC
2c1d58b8cc
Rollup merge of #96480 - user-simon:patch-1, r=Dylan-DPC
Fixed grammatical error in example comment

Added missing "we" in sentence.
2022-04-28 20:13:03 +02:00
Simon
332f326334
Fixed grammatical error in example comment 2022-04-27 17:27:02 +02:00
Michael Goulet
83d701e569 Better error messages when collecting into [T; n] 2022-04-26 21:37:10 -07:00
Guillaume Gomez
2b8bf0d530
Rollup merge of #95949 - SoniEx2:patch-5, r=m-ou-se
Implement Default for AssertUnwindSafe

Trait impls are still insta-stable yeah...?
2022-04-26 13:22:27 +02:00
Dylan DPC
93db30aa7f
Rollup merge of #96149 - est31:remove_unused_macro_matchers, r=petrochenkov
Remove unused macro rules

Removes rules of internal macros that weren't triggered.
2022-04-26 01:21:20 +02:00
Dylan DPC
51b86848ff
Rollup merge of #90312 - r00ster91:search, r=Dylan-DPC
Fix some confusing wording and improve slice-search-related docs

This adds more links between `contains` and `binary_search` because I do think they have some relevant connections. If your (big) slice happens to be sorted and you know it, surely you should be using `[3; 100].binary_search(&5).is_ok()` over `[3; 100].contains(&5)`?
This also fixes the confusing "searches this sorted X" wording which just sounds really weird because it doesn't know whether it's actually sorted. It should be but it may not be. The new wording should make it clearer that you will probably want to sort it and in the same sentence it also mentions the related function `contains`.
Similarly, this mentions `binary_search` on `contains`' docs.
This also fixes some other minor stuff and inconsistencies.
2022-04-26 01:21:20 +02:00
Marko Mijalkovic
92a584177d Inline core::panic::Location methods 2022-04-23 14:41:47 -04:00
bors
6b4563bf93 Auto merge of #90602 - mbartlett21:const-intoiterator, r=oli-obk
Unstably constify `impl<I: Iterator> IntoIterator for I`

This constifies the default `IntoIterator` implementation under the `const_intoiterator_identity` feature.

Tracking Issue: #90603
2022-04-23 15:41:45 +00:00
bors
1e9aa8a96b Auto merge of #95971 - workingjubilee:no-weird-fp-in-const, r=oli-obk
No "weird" floats in const fn {from,to}_bits

I suspect this code is subtly incorrect and that we don't even e.g. use x87-style floats in CTFE, so I don't have to guard against that case. A future PR will be hopefully removing them from concern entirely, anyways. But at the moment I wanted to get this rolling because small questions like that one seem best answered by review.

r? `@oli-obk`
cc `@eddyb` `@thomcc`
2022-04-23 13:00:54 +00:00
Nilstrieb
521bb810be Link to correct as_mut in docs for pointer::as_ref
It previously linked to the unstable const-mut-cast method instead of
the `mut` counterpart for `as_ref`.
2022-04-23 13:42:26 +02:00
Jubilee Young
4da8682523 Remove unnecessary const-time x87-related checks 2022-04-22 19:34:33 -07:00
Jubilee Young
bb555b828c Fix comments for float classify 2022-04-22 18:34:34 -07:00
Yonggang Luo
1d5948f473 library/core: Fixes implement of c_uint, c_long, c_ulong
Fixes: aa67016624 ("make memcmp return a value of c_int_width instead of i32")
Introduce c_num_definition to getting the cfg_if logic easier to maintain
Add newlines for easier code reading

Signed-off-by: Yonggang Luo <luoyonggang@gmail.com>
2022-04-21 17:18:32 +08:00
mbartlett21
4879875c76
Change file locations to be links to GitHub 2022-04-20 13:14:32 +10:00
mbartlett21
671a8723c6
Fix locations for intrinsics impls 2022-04-20 09:28:07 +10:00
bors
d5ae66c12c Auto merge of #92287 - JulianKnodt:slice_remainder, r=yaahc
Add slice::remainder

This adds a remainder function to the Slice iterator, so that a caller can access unused
elements if iteration stops.

Addresses #91733
2022-04-18 23:34:24 +00:00
Jane Lusby
00a315c515
Update library/core/src/result.rs
Co-authored-by: Emil Thorenfeldt <emt@magenta.dk>
2022-04-18 16:31:21 -07:00
Jane Lusby
eca7dd20d5
Update library/core/src/result.rs
Co-authored-by: Emil Thorenfeldt <emt@magenta.dk>
2022-04-18 16:31:13 -07:00
est31
3c1e1661e7 Remove unused macro rules 2022-04-18 23:28:06 +02:00
Dylan DPC
55e399771e
Rollup merge of #96156 - est31:use_from_le_bytes, r=Dylan-DPC
Replace u8to64_le macro with u64::from_le_bytes

The macro was a reimplementation of the function.
2022-04-18 18:22:07 +02:00
Dylan DPC
a6ad1394f3
Rollup merge of #96136 - thomcc:lifetime-wording, r=RalfJung
Reword clarification on lifetime for ptr->ref safety docs

I believe the current wording of the safety comment is somewhat misleading, and that this is more accurate. Suggested by `@CAD97` in this thread on the topic https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/Lifetime.20of.20reference.20pointer.20docs.20issue

Just to check that this is correct, CC `@RalfJung.`

I suppose it's open for interpretation as to whether or not this is more clear. I think it is.
2022-04-18 18:22:04 +02:00
Ralf Jung
74d77d058b mark ptr-int-transmute test as no_run 2022-04-18 10:04:31 -04:00
est31
9e7a319f01 Replace u8to64_le macro with u64::from_le_bytes
The macro was a reimplementation of the function.
2022-04-17 22:55:33 +02:00
Lukas Lueg
3615cb476b Expand core::hint::unreachable_unchecked() docs
Fixes #95865
2022-04-17 20:58:36 +02:00
kadmin
494901ced6 Add slice::remainder
This adds a remainder function to the Slice iterator, so that a caller can access unused
elements if iteration stops.
2022-04-17 17:19:45 +00:00
bors
ac8b11810f Auto merge of #96010 - eduardosm:Unique-on-top-of-NonNull, r=m-ou-se,tmiasko
Implement `core::ptr::Unique` on top of `NonNull`

Removes the use `rustc_layout_scalar_valid_range_start` and some `unsafe` blocks.
2022-04-17 05:26:08 +00:00
Thom Chiovoloni
be30e40440
Reword clarification on lifetime for ptr->ref safety docs 2022-04-16 21:39:43 -07:00
Matthew Woodcraft
16c81fa9a6 Document the numeric value returned by string parsing for floats 2022-04-16 22:03:24 +01:00
Matthew Woodcraft
6fa061c5f9 Document rounding for floating-point primitive operations
State that the four primitive operations honour IEEE 754 roundTiesToEven.

Documenting under "Primitive Type f32"; f64 refers to that.
2022-04-16 21:58:36 +01:00
Giles Cope
bf02d1ea5f
No need to check the assert all the time. 2022-04-16 19:30:23 +01:00
Dylan DPC
4ed7627117
Rollup merge of #96081 - eduardosm:masks_usize_size_agnostic, r=yaahc
Make some `usize`-typed masks definitions agnostic to the size of `usize`

Some masks where defined as
```rust
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
```
where it was assumed that `usize` is never wider than 64, which is currently true.

To make those constants valid in a hypothetical 128-bit target, these constants have been redefined in an `usize`-width-agnostic way
```rust
const NONASCII_MASK: usize = usize::from_ne_bytes([0x80; size_of::<usize>()]);
```

There are already some cases where Rust anticipates the possibility of supporting 128-bit targets, such as not implementing `From<usize>` for `u64`.
2022-04-16 14:26:01 +02:00
Dylan DPC
bd007ba928
Rollup merge of #96038 - beyarkay:patch-1, r=m-ou-se
docs: add link from zip to unzip

The docs for `Iterator::unzip` explain that it is kind of an inverse operation to `Iterator::zip` and guide the reader to the `zip` docs, but the `zip` docs don't let the user know that they can undo the `zip` operation with `unzip`. This change modifies the docs to help the user find `unzip`.
2022-04-16 14:25:58 +02:00
Raekye
d5f96e6ade Change as_uninit_* methods on NonNull from taking self by
reference to taking `self` by value. This is consistent with the methods
of the same names on primitive pointers. The returned lifetime was
already previously unbounded.
2022-04-15 21:21:02 -04:00
ltdk
63a8652961 MaybeUninit array cleanup
* Links MaybeUninit::uninit_array to meta-tracking issue
* Links MaybeUninit::array_assume_init to meta-tracking issue
* Unstably constifies MaybeUninit::array_assume_init
2022-04-15 20:53:50 -04:00
Dylan DPC
20bf34f8c5
Rollup merge of #94461 - jhpratt:2024-edition, r=pnkfelix
Create (unstable) 2024 edition

[On Zulip](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Deprecating.20macro.20scoping.20shenanigans/near/272860652), there was a small aside regarding creating the 2024 edition now as opposed to later. There was a reasonable amount of support and no stated opposition.

This change creates the 2024 edition in the compiler and creates a prelude for the 2024 edition. There is no current difference between the 2021 and 2024 editions. Cargo and other tools will need to be updated separately, as it's not in the same repository. This change permits the vast majority of work towards the next edition to proceed _now_ instead of waiting until 2024.

For sanity purposes, I've merged the "hello" UI tests into a single file with multiple revisions. Otherwise we'd end up with a file per edition, despite them being essentially identical.

````@rustbot```` label +T-lang +S-waiting-on-review

Not sure on the relevant team, to be honest.
2022-04-15 20:50:43 +02:00
Dylan DPC
27e2d811e6
Rollup merge of #94457 - jhpratt:stabilize-derive_default_enum, r=davidtwco
Stabilize `derive_default_enum`

This stabilizes `#![feature(derive_default_enum)]`, as proposed in [RFC 3107](https://github.com/rust-lang/rfcs/pull/3107) and tracked in #87517. In short, it permits you to `#[derive(Default)]` on `enum`s, indicating what the default should be by placing a `#[default]` attribute on the desired variant (which must be a unit variant in the interest of forward compatibility).

```````@rustbot``````` label +S-waiting-on-review +T-lang
2022-04-15 20:50:43 +02:00
Jane Lusby
5d98acb19c update docs for option to crossreference to the result docs 2022-04-15 10:24:34 -07:00
Eduardo Sánchez Muñoz
93ae6f80e3 Make some usize-typed masks definition agnostic to the size of usize
Some masks where defined as
```rust
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
```
where it was assumed that `usize` is never wider than 64, which is currently true.

To make those constants valid in a hypothetical 128-bit target, these constants have been redefined in an `usize`-width-agnostic way
```rust
const NONASCII_MASK: usize = usize::from_ne_bytes([0x80; size_of::<usize>()]);
```

There are already some cases where Rust anticipates the possibility of supporting 128-bit targets, such as not implementing `From<usize>` for `u64`.
2022-04-15 17:04:59 +02:00
Jane Lusby
80c362b92b add should_panic annotations 2022-04-14 13:22:24 -07:00
Vadim Petrochenkov
7f3cc2fbbf library: Use type aliases to make CStr(ing) in libcore/liballoc unstable 2022-04-14 21:53:11 +03:00
Vadim Petrochenkov
5bee741a08 library: Move CStr to libcore, and CString to liballoc 2022-04-14 21:53:11 +03:00
Jane Lusby
3d951b3d21 add necessary text attribute to code block of panic output 2022-04-14 11:40:27 -07:00
Артём Павлов
65c75b2db7 Use rounding in float to Duration conversion methods 2022-04-14 20:44:09 +03:00
Eduardo Sánchez Muñoz
2a91eeac1a Implement core::ptr::Unique on top of NonNull
Removes the use `rustc_layout_scalar_valid_range_start` and some `unsafe` blocks.
2022-04-14 19:35:40 +02:00
Boyd Kane
d73e32867f
Remove trailing whitespace
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
2022-04-14 11:19:49 +02:00
Boyd Kane
f6d957701f
docs: add link from zip to unzip
The docs for `Iterator::unzip` explain that it is kind of an inverse operation to `Iterator::zip` and guide the reader to the `zip` docs, but the `zip` docs don't let the user know that they can undo the `zip` operation with `unzip`. This change modifies the docs to help the user find `unzip`.
2022-04-14 09:51:47 +02:00
Jacob Pratt
4fbe73e0b7
Remove use of #[rustc_deprecated] 2022-04-14 01:33:13 -04:00
Jane Lusby
dfb37cb088 Add section on common message styles for Result::expect 2022-04-13 19:08:10 -07:00
Dylan DPC
e95f2db98f
Rollup merge of #96006 - hkBst:patch-2, r=Dylan-DPC
Add a missing article

Add a missing article
2022-04-13 17:35:37 +02:00
Marijn Schouten
c008d45187
Add a missing article
Add a missing article
2022-04-13 13:33:09 +02:00
Marijn Schouten
212e98bc3e
Add missing article to fix "few" to "a few".
Add missing article to fix "few" (not many) to "a few" (some).
2022-04-13 13:24:28 +02:00
Dylan DPC
633c391225
Rollup merge of #95984 - wcampbell0x2a:fix-spelling, r=thomcc
Fix spelling in docs for `can_not_overflow`

Introduced in https://github.com/rust-lang/rust/pull/95399
2022-04-13 05:54:13 +02:00
Dylan DPC
6aa875aa96
Rollup merge of #95914 - c410-f3r:meta-vars, r=petrochenkov
Implement tuples using recursion

Because it is c00l3r™, requires less repetition and can be used as a reference for external people.

This change is non-essential and I am not sure about potential performance impacts so feel free to close this PR if desired.

r? `@petrochenkov`
2022-04-12 23:16:58 +02:00
Caio
23bf977758 Implement tuples using recursion 2022-04-12 16:23:36 -03:00
wcampbell
9ea89e1d3d Fix spelling in docs for can_not_overflow 2022-04-12 13:29:56 -04:00
Jubilee Young
83581796b2 Ban subnormals and NaNs in const {from,to}_bits 2022-04-12 02:27:25 -07:00
Jubilee Young
b200483412 Rectify float classification impls for weird FPUs
Careful handling does its best to take care of both Armv7's
"unenhanced" Neon as well as the x87 FPU.
2022-04-12 02:27:25 -07:00
bors
4e1927db3c Auto merge of #95399 - gilescope:plan_b, r=scottmcm
Faster parsing for lower numbers for radix up to 16 (cont.)

( Continuation of https://github.com/rust-lang/rust/pull/83371 )

With LingMan's change I think this is potentially ready.
2022-04-12 05:54:50 +00:00
bors
36f4ded69e Auto merge of #93408 - liangyongrui:master, r=scottmcm
fix Layout struct member naming style
2022-04-12 00:18:51 +00:00
Soni L
8d5a4963df
Implement Default for AssertUnwindSafe
Trait impls are still insta-stable yeah...?
2022-04-11 17:56:27 -03:00
Dylan DPC
ae6f75a0c3
Rollup merge of #95895 - CAD97:patch-2, r=Dylan-DPC
Clarify str::from_utf8_unchecked's invariants

Specifically, make it clear that it is immediately UB to pass ill-formed UTF-8 into the function. The previous wording left space to interpret that the UB only occurred when calling another function, which "assumes that `&str`s are valid UTF-8."

This does not change whether str being UTF-8 is a safety or a validity invariant. (As per previous discussion, it is a safety invariant, not a validity invariant.) It just makes it clear that valid UTF-8 is a precondition of str::from_utf8_unchecked, and that emitting an Abstract Machine fault (e.g. UB or a sanitizer error) on invalid UTF-8 is a valid thing to do.

If user code wants to create an unsafe `&str` pointing to ill-formed UTF-8, it must be done via transmutes. Also, just, don't.

Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/str.3A.3Afrom_utf8_unchecked.20Safety.20requirement
2022-04-11 20:00:44 +02:00
Dylan DPC
82a6463b1c
Rollup merge of #95894 - nyanpasu64:fix-pin-docs, r=Dylan-DPC
Fix formatting error in pin.rs docs

Not sure if there's more formatting issues I missed; I kinda lost interest reading midway through.
2022-04-11 20:00:43 +02:00
Matthias Krüger
e25bc303f1
Rollup merge of #95743 - yaahc:binary-search-clarification, r=Mark-Simulacrum
Update binary_search example to instead redirect to partition_point

Inspired by discussion in the tracking issue for `Result::into_ok_or_err`: https://github.com/rust-lang/rust/issues/82223#issuecomment-1067098167

People are surprised by us not providing a `Result<T, T> -> T` conversion, and the main culprit for this confusion seems to be the `binary_search` API. We should instead redirect people to the equivalent API that implicitly does that `Result<T, T> -> T` conversion internally which should obviate the need for the `into_ok_or_err` function and give us time to work towards a more general solution that applies to all enums rather than just `Result` such as making or_patterns usable for situations like this via postfix `match`.

I choose to duplicate the example rather than simply moving it from `binary_search` to partition point because most of the confusion seems to arise when people are looking at `binary_search`. It makes sense to me to have the example presented immediately rather than requiring people to click through to even realize there is an example. If I had to put it in only one place I'd leave it in `binary_search` and remove it from `partition_point` but it seems pretty obviously relevant to `partition_point` so I figured the best option would be to duplicate it.
2022-04-11 12:06:52 +02:00
Giles Cope
3ee7bb19c6
better def of is signed in tests. 2022-04-11 07:37:53 +01:00
liangyongrui
03b2588837 fix Layout struct member naming style 2022-04-11 13:35:18 +08:00
Christopher Durham
b92cd1a32c
Clarify str::from_utf8_unchecked's invariants
Specifically, make it clear that it is immediately UB to pass ill-formed UTF-8 into the function. The previous wording left space to interpret that the UB only occurred when calling another function, which "assumes that `&str`s are valid UTF-8."

This does not change whether str being UTF-8 is a safety or a validity invariant. (As per previous discussion, it is a safety invariant, not a validity invariant.) It just makes it clear that valid UTF-8 is a precondition of str::from_utf8_unchecked, and that emitting an Abstract Machine fault (e.g. UB or a sanitizer error) on invalid UTF-8 is a valid thing to do.

If user code wants to create an unsafe `&str` pointing to ill-formed UTF-8, it must be done via transmutes. Also, just, don't.
2022-04-10 15:04:57 -05:00
nyanpasu64
bb3a071df8
Fix formatting error in pin.rs docs 2022-04-10 12:41:31 -07:00
Dylan DPC
c0655dec7e
Rollup merge of #95566 - eduardosm:std_char_consts_and_methods, r=Mark-Simulacrum
Avoid duplication of doc comments in `std::char` constants and functions

For those consts and functions, only the summary is kept and a reference to the `char` associated const/method is included.

Additionaly, re-exported functions have been converted to function definitions that call the previously re-exported function. This makes it easier to add a deprecated attribute to these functions in the future.
2022-04-10 21:03:34 +02:00
Giles Cope
79e8653656
No need to use Default 2022-04-10 18:20:13 +01:00
Giles Cope
515906a669
Use Add, Sub, Mul traits instead of unsafe 2022-04-10 18:13:48 +01:00
Dylan DPC
7726265ae0
Rollup merge of #95831 - redzic:xor-uppercase, r=workingjubilee
Use bitwise XOR in to_ascii_uppercase

This saves an instruction compared to the previous approach, which
was to unset the fifth bit with bitwise OR.

Comparison of generated assembly on x86: https://godbolt.org/z/GdfvdGs39

This can also affect autovectorization, saving SIMD instructions as well: https://godbolt.org/z/cnPcz75T9

Not sure if `u8::to_ascii_lowercase` should also be changed, since using bitwise OR for that function does not require an extra bitwise negate since the code is setting a bit rather than unsetting a bit. `char::to_ascii_uppercase` already uses XOR, so no change seems to be required there.
2022-04-09 18:26:30 +02:00
Dylan DPC
5092946041
Rollup merge of #95805 - c410-f3r:meta-vars, r=petrochenkov
Left overs of #95761

These are just nits. Feel free to close this PR if all modifications are not worth merging.

* `#![feature(decl_macro)]` is not needed anymore in `rustc_expand`
* `tuple_impls` does not require `$Tuple:ident`. I guess it is there to enhance readability?

r? ```@petrochenkov```
2022-04-09 18:26:27 +02:00
Dylan DPC
e4b4bf1535
Rollup merge of #95361 - scottmcm:valid-align, r=Mark-Simulacrum
Make non-power-of-two alignments a validity error in `Layout`

Inspired by the zulip conversation about how `Layout` should better enforce `size <= isize::MAX as usize`, this uses an N-variant enum on N-bit platforms to require at the validity level that the existing invariant of "must be a power of two" is upheld.

This was MIRI can catch it, and means there's a more-specific type for `Layout` to store than just `NonZeroUsize`.

It's left as `pub(crate)` here; a future PR could consider giving it a tracking issue for non-internal usage.
2022-04-09 18:26:25 +02:00
Dylan DPC
8d7392232c
Rollup merge of #95787 - yaahc:panic-doc-update-v2, r=dtolnay
reword panic vs result section to remove recoverable vs unrecoverable framing

Based on feedback from the Error Handling FAQ: https://github.com/rust-lang/project-error-handling/issues/50#issuecomment-1090876982

r? ````@dtolnay````
2022-04-09 05:58:44 +02:00
Scott McMurray
fe0c08a4f2 Make non-power-of-two alignments a validity error in Layout
Inspired by the zulip conversation about how `Layout` should better enforce `size < isize::MAX as usize`, this uses an N-variant enum on N-bit platforms to require at the validity level that the existing invariant of "must be a power of two" is upheld.

This was MIRI can catch it, and means there's a more-specific type for `Layout` to store than just `NonZeroUsize`.
2022-04-08 20:17:38 -07:00
Redzic
1e6365d075 Use bitwise XOR in to_ascii_uppercase
This saves an instruction compared to the previous approach, which
was to unset the fifth bit with bitwise OR.
2022-04-08 20:06:54 -05:00
Caio
e946aa3a74 Left overs of #95761 2022-04-08 10:30:24 -03:00
Dylan DPC
1f80881a94
Rollup merge of #95761 - c410-f3r:meta-var-stuff, r=petrochenkov
Kickstart the inner usage of `macro_metavar_expr`

There can be more use-cases but I am out of ideas.

cc #83527
r? ``@petrochenkov``
2022-04-08 11:48:24 +02:00
Dylan DPC
d5232c6b93
Rollup merge of #95579 - Cyborus04:slice_flatten, r=scottmcm
Add `<[[T; N]]>::flatten{_mut}`

Adds `flatten` to convert `&[[T; N]]` to `&[T]` (and `flatten_mut` for `&mut [[T; N]]` to `&mut [T]`)
2022-04-08 11:48:21 +02:00
Cyborus04
06788fd7a4 add <[[T; N]]>::flatten, <[[T; N]]>::flatten_mut, and Vec::<[T; N]>::into_flattened 2022-04-08 00:54:39 -04:00
Jacob Pratt
a3dd654ae9
Add documentation 2022-04-07 20:03:24 -04:00
Jacob Pratt
abf2b4c04d
Stabilize derive_default_enum 2022-04-07 20:03:19 -04:00
Jane Lusby
aa3c141c86 reword panic vs result section to remove recoverable vs unrecoverable framing 2022-04-07 13:44:57 -07:00
Caio
3191d27f48 Kickstart the inner usage of macro_metavar_expr 2022-04-07 08:13:41 -03:00
bors
ed6c958ee4 Auto merge of #95760 - Dylan-DPC:rollup-uskzggh, r=Dylan-DPC
Rollup of 4 pull requests

Successful merges:

 - #95189 (Stop flagging unexpected inner attributes as outer ones in certain diagnostics)
 - #95752 (Regression test for #82866)
 - #95753 (Correct safety reasoning in `str::make_ascii_{lower,upper}case()`)
 - #95757 (Use gender neutral terms)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-04-07 09:50:11 +00:00
Dylan DPC
6639604bd6
Rollup merge of #95753 - ChayimFriedman2:patch-1, r=dtolnay
Correct safety reasoning in `str::make_ascii_{lower,upper}case()`

I don't understand why the previous comment was used (it was inserted in #66564), but it doesn't explain why these functions are safe, only why `str::as_bytes{_mut}()` are safe.

If someone thinks they make perfect sense, I'm fine with closing this PR.
2022-04-07 11:17:16 +02:00
bors
f565016edd Auto merge of #95678 - pietroalbini:pa-1.62.0-bootstrap, r=Mark-Simulacrum
Bump bootstrap compiler to 1.61.0 beta

This PR bumps the bootstrap compiler to the 1.61.0 beta. The first commit changes the stage0 compiler, the second commit applies the "mechanical" changes and the third and fourth commits apply changes explained in the relevant comments.

r? `@Mark-Simulacrum`
2022-04-07 07:34:04 +00:00
Chayim Refael Friedman
b399e7ea7c
Correct safety reasoning in str::make_ascii_{lower,upper}case() 2022-04-07 07:52:07 +03:00